commit 4d322f679834fce358a628129e68c31c444341a6 Author: Jonas L Date: Mon Feb 25 00:00:00 2019 +0000 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3e14967 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +*.iml +.gradle +/local.properties +/.idea/caches/build_file_checksums.ser +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +.DS_Store +/build +/captures +.externalNativeBuild +.idea diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2cb3f1d --- /dev/null +++ b/LICENSE @@ -0,0 +1,675 @@ + 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. + + opentimelimit-android + Copyright (C) 2019 timelimit.io + + 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: + + opentimelimit-android Copyright (C) 2019 timelimit.io + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..9a39284 --- /dev/null +++ b/Readme.md @@ -0,0 +1,3 @@ +# TimeLimit + +This App allows setting time limits for the usage of Android phones/ devices. diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..26f4858 --- /dev/null +++ b/app/.gitignore @@ -0,0 +1,3 @@ +/build +play-key.json +keystore.properties diff --git a/app/asset sources b/app/asset sources new file mode 100644 index 0000000..5a16927 --- /dev/null +++ b/app/asset sources @@ -0,0 +1,4 @@ +ic_launcher: https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html#foreground.type=clipart&foreground.clipart=timelapse&foreground.space.trim=1&foreground.space.pad=0.25&foreColor=rgb(255%2C%20255%2C%20255)&backColor=rgb(0%2C%20150%2C%20136)&crop=0&backgroundShape=square&effects=score&name=ic_launcher +ic_stat_timelapse: https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=timelapse&source.space.trim=1&source.space.pad=0&name=ic_stat_timelapse +ic_stat_block: https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=block&source.space.trim=1&source.space.pad=0&name=ic_stat_block +ic_stat_check: https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=check&source.space.trim=1&source.space.pad=0&name=ic_stat_check \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..d2bda47 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,211 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * 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 . + */ + +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' +apply plugin: "androidx.navigation.safeargs.kotlin" +apply plugin: 'kotlin-kapt' +apply plugin: 'com.github.triplet.play' +apply plugin: 'com.getkeepsafe.dexcount' + +androidExtensions { + experimental = true +} + +android { + compileSdkVersion 28 + defaultConfig { + applicationId "io.timelimit.android" + minSdkVersion 19 + targetSdkVersion 28 + versionCode 30 + versionName "0.5.4 Beta" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + kapt { + arguments { + arg("room.schemaLocation", "$projectDir/schemas".toString()) + } + } + buildConfigField 'String', 'googlePlayKey', '"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqxGPPhjSGrSI4jfIJmw83dDGTO4Sg74nXhOoHl5Omyvxa1Hv+Tzp/wC97emXSmKq9Li2bV4q3yJLjtLJtoDmh9V1vpdyjH13qOidhIUYOtlkGexbwKz56jZwRFXGBIy0RFDDr3j5DLfUWMk0dqplLgIHDqsdUNY50419oMGKAOCX3DEw+ky+0zMY/hlUkZHnd0HLi0CYNkdZyMMYnk8OiOZ3YoDU/vz9PTf93MCAONYcXBlo3Y5hdVY2tyH4qNZh1eyqe0Trz4fRf+y1ljoa0s4ZqYskbsgpy+zUbGb82cxmATAsrdJMnNKMEa30HBvfMzKiOPR6sq3A8PPPoWT5KQIDAQAB"' + } + + flavorDimensions 'api', 'channel', 'server' + productFlavors { + storeVersion { + dimension 'channel' + buildConfigField 'boolean', 'storeCompilant', 'true' + applicationIdSuffix ".store" + } + directVersion { + dimension 'channel' + buildConfigField 'boolean', 'storeCompilant', 'false' + applicationIdSuffix ".direct" + } + + googleApi { + dimension 'api' + buildConfigField 'boolean', 'useGoogleApis', 'true' + buildConfigField 'String', "googleAuthClientId", '"700283994167-4vklse9lj88oo41bd5aav8t0r9ohjhh6.apps.googleusercontent.com"' + applicationIdSuffix ".google" + } + noGoogleApi { + dimension 'api' + buildConfigField 'boolean', 'useGoogleApis', 'false' + applicationIdSuffix ".aosp" + } + + developmentServer { + dimension 'server' + // this is your own computer when using the Android Emulator + buildConfigField 'String', 'serverUrl', '"http://10.0.2.2:8080"' + buildConfigField 'boolean', 'hasServer', 'true' + applicationIdSuffix '.developmentserver' + } + productionServer { + dimension 'server' + buildConfigField 'String', 'serverUrl', '"https://api.timelimit.io"' + buildConfigField 'String', 'serverDomain', '"api.timelimit.io"' + buildConfigField 'boolean', 'hasServer', 'true' + // no applicationIdSuffix + } + noServer { + dimension 'server' + buildConfigField 'String', 'serverUrl', '"https://128.0.0.1"' + buildConfigField 'boolean', 'hasServer', 'false' + applicationIdSuffix '.offline' + } + } + + signingConfigs { + release { + // empty + } + } + + variantFilter { variant -> + def dim = variant.flavors.collectEntries { + [(it.productFlavor.dimension): it.productFlavor.name] + } + + if (dim.channel == 'storeVersion' && dim.api == 'noGoogleApi') { + variant.setIgnore(true) + } + } + + lintOptions { + disable 'GoogleAppIndexingWarning' + baseline file("lint-baseline.xml") + } + + dataBinding { + enabled = true + } + + buildTypes { + debug { + minifyEnabled true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + + release { + minifyEnabled true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + signingConfig signingConfigs.release + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } +} + +dependencies { + def nav_version = "1.0.0-beta02" + def room_version = "2.0.0" + def work_version = '1.0.0-rc01' + def paging_version = "2.1.0" + + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + implementation 'androidx.appcompat:appcompat:1.0.2' + implementation 'androidx.legacy:legacy-support-v4:1.0.0' + implementation 'androidx.cardview:cardview:1.0.0' + + implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0' + + implementation "android.arch.navigation:navigation-fragment-ktx:$nav_version" + implementation "android.arch.navigation:navigation-ui:$nav_version" + implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3' + implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0' + + implementation "androidx.room:room-runtime:$room_version" + kapt "androidx.room:room-compiler:$room_version" + testImplementation "androidx.room:room-testing:$room_version" + + implementation "androidx.paging:paging-runtime:$paging_version" + + implementation "android.arch.work:work-runtime:$work_version" + implementation "android.arch.work:work-runtime-ktx:$work_version" + androidTestImplementation "android.arch.work:work-testing:$work_version" + + implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.0' + implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.0' + + testImplementation 'junit:junit:4.12' + androidTestImplementation 'androidx.test:runner:1.1.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' + + implementation 'com.jakewharton.threetenabp:threetenabp:1.1.0' + + implementation 'org.mindrot:jbcrypt:0.4' + + implementation 'com.getkeepsafe.taptargetview:taptargetview:1.11.0' + + implementation 'com.google.android:flexbox:1.0.0' + + implementation 'com.jaredrummler:android-device-names:1.1.7' + + implementation 'com.squareup.okhttp3:okhttp:3.11.0' + implementation 'com.squareup.okhttp3:logging-interceptor:3.8.1' + + googleApiImplementation 'com.google.android.gms:play-services-auth:16.0.1' + + implementation 'org.solovyev.android:checkout:1.2.1' + + implementation('io.socket:socket.io-client:1.0.0') { + exclude group: 'org.json', module: 'json' + } +} + +play { + jsonFile = file("play-key.json") + track = "production" +} + +// based on https://stackoverflow.com/a/20573171 +def propsFile = project.file('keystore.properties') +def configName = 'release' + +if (propsFile.exists() && android.signingConfigs.hasProperty(configName)) { + def props = new Properties() + props.load(new FileInputStream(propsFile)) + android.signingConfigs[configName].storeFile = file(props['storeFile']) + android.signingConfigs[configName].storePassword = props['storePassword'] + android.signingConfigs[configName].keyAlias = props['keyAlias'] + android.signingConfigs[configName].keyPassword = props['keyPassword'] +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..37d0bd0 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,50 @@ +# TimeLimit Copyright 2019 Jonas Lochmann +# +# 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 version 3 of the License. +# +# 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 . + +# 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 + +-dontwarn okhttp3.** +-dontwarn okio.** + +# ServiceLoader support +-keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {} +-keepnames class kotlinx.coroutines.CoroutineExceptionHandler {} + +# Most of volatile fields are updated with AFU and should not be mangled +-keepclassmembernames class kotlinx.** { + volatile ; +} + +# readable stack traces +-keepattributes SourceFile,LineNumberTable \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/1.json b/app/schemas/io.timelimit.android.data.RoomDatabase/1.json new file mode 100644 index 0000000..04dd4c7 --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/1.json @@ -0,0 +1,566 @@ +{ + "formatVersion": 1, + "database": { + "version": 1, + "identityHash": "5d45b0c4b64933836c1a74d2afccba94", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"5d45b0c4b64933836c1a74d2afccba94\")" + ] + } +} \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/10.json b/app/schemas/io.timelimit.android.data.RoomDatabase/10.json new file mode 100644 index 0000000..2d25d80 --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/10.json @@ -0,0 +1,626 @@ +{ + "formatVersion": 1, + "database": { + "version": 10, + "identityHash": "296a30b106e25bcc42a3a6a244363bd9", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, `category_for_not_assigned_apps` TEXT NOT NULL, `relax_primary_device` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryForNotAssignedApps", + "columnName": "category_for_not_assigned_apps", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relaxPrimaryDevice", + "columnName": "relax_primary_device", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `did_reboot` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, `did_report_uninstall` INTEGER NOT NULL, `is_user_kept_signed_in` INTEGER NOT NULL, `show_device_connected` INTEGER NOT NULL, `default_user` TEXT NOT NULL, `default_user_timeout` INTEGER NOT NULL, `consider_reboot_manipulation` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationDidReboot", + "columnName": "did_reboot", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "didReportUninstall", + "columnName": "did_report_uninstall", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isUserKeptSignedIn", + "columnName": "is_user_kept_signed_in", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "showDeviceConnected", + "columnName": "show_device_connected", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "defaultUser", + "columnName": "default_user", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "defaultUserTimeout", + "columnName": "default_user_timeout", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "considerRebootManipulation", + "columnName": "consider_reboot_manipulation", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, `parent_category_id` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentCategoryId", + "columnName": "parent_category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"296a30b106e25bcc42a3a6a244363bd9\")" + ] + } +} \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/11.json b/app/schemas/io.timelimit.android.data.RoomDatabase/11.json new file mode 100644 index 0000000..474db5c --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/11.json @@ -0,0 +1,632 @@ +{ + "formatVersion": 1, + "database": { + "version": 11, + "identityHash": "726b4d126996f95e98b6c82460054928", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, `category_for_not_assigned_apps` TEXT NOT NULL, `relax_primary_device` INTEGER NOT NULL, `mail_notification_flags` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryForNotAssignedApps", + "columnName": "category_for_not_assigned_apps", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relaxPrimaryDevice", + "columnName": "relax_primary_device", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mailNotificationFlags", + "columnName": "mail_notification_flags", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `did_reboot` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, `did_report_uninstall` INTEGER NOT NULL, `is_user_kept_signed_in` INTEGER NOT NULL, `show_device_connected` INTEGER NOT NULL, `default_user` TEXT NOT NULL, `default_user_timeout` INTEGER NOT NULL, `consider_reboot_manipulation` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationDidReboot", + "columnName": "did_reboot", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "didReportUninstall", + "columnName": "did_report_uninstall", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isUserKeptSignedIn", + "columnName": "is_user_kept_signed_in", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "showDeviceConnected", + "columnName": "show_device_connected", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "defaultUser", + "columnName": "default_user", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "defaultUserTimeout", + "columnName": "default_user_timeout", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "considerRebootManipulation", + "columnName": "consider_reboot_manipulation", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, `parent_category_id` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentCategoryId", + "columnName": "parent_category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"726b4d126996f95e98b6c82460054928\")" + ] + } +} \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/2.json b/app/schemas/io.timelimit.android.data.RoomDatabase/2.json new file mode 100644 index 0000000..1b3e590 --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/2.json @@ -0,0 +1,572 @@ +{ + "formatVersion": 1, + "database": { + "version": 2, + "identityHash": "a3f6f88938fcdd4963f203242fca86c2", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, `did_report_uninstall` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "didReportUninstall", + "columnName": "did_report_uninstall", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"a3f6f88938fcdd4963f203242fca86c2\")" + ] + } +} \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/3.json b/app/schemas/io.timelimit.android.data.RoomDatabase/3.json new file mode 100644 index 0000000..d334c74 --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/3.json @@ -0,0 +1,578 @@ +{ + "formatVersion": 1, + "database": { + "version": 3, + "identityHash": "4463bf96d427775c34813b976d2fd8da", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, `did_report_uninstall` INTEGER NOT NULL, `is_user_kept_signed_in` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "didReportUninstall", + "columnName": "did_report_uninstall", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isUserKeptSignedIn", + "columnName": "is_user_kept_signed_in", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"4463bf96d427775c34813b976d2fd8da\")" + ] + } +} \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/4.json b/app/schemas/io.timelimit.android.data.RoomDatabase/4.json new file mode 100644 index 0000000..023c956 --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/4.json @@ -0,0 +1,584 @@ +{ + "formatVersion": 1, + "database": { + "version": 4, + "identityHash": "886fe08a6ed3bfe4c7f2ddd76dd2c357", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, `category_for_not_assigned_apps` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryForNotAssignedApps", + "columnName": "category_for_not_assigned_apps", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, `did_report_uninstall` INTEGER NOT NULL, `is_user_kept_signed_in` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "didReportUninstall", + "columnName": "did_report_uninstall", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isUserKeptSignedIn", + "columnName": "is_user_kept_signed_in", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"886fe08a6ed3bfe4c7f2ddd76dd2c357\")" + ] + } +} \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/5.json b/app/schemas/io.timelimit.android.data.RoomDatabase/5.json new file mode 100644 index 0000000..1c87b91 --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/5.json @@ -0,0 +1,590 @@ +{ + "formatVersion": 1, + "database": { + "version": 5, + "identityHash": "d25fe525f2ce2a7101b71bc352b2ab82", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, `category_for_not_assigned_apps` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryForNotAssignedApps", + "columnName": "category_for_not_assigned_apps", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, `did_report_uninstall` INTEGER NOT NULL, `is_user_kept_signed_in` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "didReportUninstall", + "columnName": "did_report_uninstall", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isUserKeptSignedIn", + "columnName": "is_user_kept_signed_in", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, `parent_category_id` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentCategoryId", + "columnName": "parent_category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"d25fe525f2ce2a7101b71bc352b2ab82\")" + ] + } +} \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/6.json b/app/schemas/io.timelimit.android.data.RoomDatabase/6.json new file mode 100644 index 0000000..b0fbb5b --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/6.json @@ -0,0 +1,596 @@ +{ + "formatVersion": 1, + "database": { + "version": 6, + "identityHash": "999803e37c89dd3538d992f6e8fe4561", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, `category_for_not_assigned_apps` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryForNotAssignedApps", + "columnName": "category_for_not_assigned_apps", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, `did_report_uninstall` INTEGER NOT NULL, `is_user_kept_signed_in` INTEGER NOT NULL, `show_device_connected` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "didReportUninstall", + "columnName": "did_report_uninstall", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isUserKeptSignedIn", + "columnName": "is_user_kept_signed_in", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "showDeviceConnected", + "columnName": "show_device_connected", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, `parent_category_id` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentCategoryId", + "columnName": "parent_category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"999803e37c89dd3538d992f6e8fe4561\")" + ] + } +} \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/7.json b/app/schemas/io.timelimit.android.data.RoomDatabase/7.json new file mode 100644 index 0000000..4606269 --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/7.json @@ -0,0 +1,614 @@ +{ + "formatVersion": 1, + "database": { + "version": 7, + "identityHash": "760121dcaa3241db6ff12deb71544429", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, `category_for_not_assigned_apps` TEXT NOT NULL, `relax_primary_device` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryForNotAssignedApps", + "columnName": "category_for_not_assigned_apps", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relaxPrimaryDevice", + "columnName": "relax_primary_device", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, `did_report_uninstall` INTEGER NOT NULL, `is_user_kept_signed_in` INTEGER NOT NULL, `show_device_connected` INTEGER NOT NULL, `default_user` TEXT NOT NULL, `default_user_timeout` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "didReportUninstall", + "columnName": "did_report_uninstall", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isUserKeptSignedIn", + "columnName": "is_user_kept_signed_in", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "showDeviceConnected", + "columnName": "show_device_connected", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "defaultUser", + "columnName": "default_user", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "defaultUserTimeout", + "columnName": "default_user_timeout", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, `parent_category_id` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentCategoryId", + "columnName": "parent_category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"760121dcaa3241db6ff12deb71544429\")" + ] + } +} \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/8.json b/app/schemas/io.timelimit.android.data.RoomDatabase/8.json new file mode 100644 index 0000000..f69bf46 --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/8.json @@ -0,0 +1,614 @@ +{ + "formatVersion": 1, + "database": { + "version": 8, + "identityHash": "760121dcaa3241db6ff12deb71544429", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, `category_for_not_assigned_apps` TEXT NOT NULL, `relax_primary_device` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryForNotAssignedApps", + "columnName": "category_for_not_assigned_apps", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relaxPrimaryDevice", + "columnName": "relax_primary_device", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, `did_report_uninstall` INTEGER NOT NULL, `is_user_kept_signed_in` INTEGER NOT NULL, `show_device_connected` INTEGER NOT NULL, `default_user` TEXT NOT NULL, `default_user_timeout` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "didReportUninstall", + "columnName": "did_report_uninstall", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isUserKeptSignedIn", + "columnName": "is_user_kept_signed_in", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "showDeviceConnected", + "columnName": "show_device_connected", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "defaultUser", + "columnName": "default_user", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "defaultUserTimeout", + "columnName": "default_user_timeout", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, `parent_category_id` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentCategoryId", + "columnName": "parent_category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"760121dcaa3241db6ff12deb71544429\")" + ] + } +} \ No newline at end of file diff --git a/app/schemas/io.timelimit.android.data.RoomDatabase/9.json b/app/schemas/io.timelimit.android.data.RoomDatabase/9.json new file mode 100644 index 0000000..ead725c --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/9.json @@ -0,0 +1,626 @@ +{ + "formatVersion": 1, + "database": { + "version": 9, + "identityHash": "296a30b106e25bcc42a3a6a244363bd9", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `second_password_salt` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` INTEGER NOT NULL, `mail` TEXT NOT NULL, `current_device` TEXT NOT NULL, `category_for_not_assigned_apps` TEXT NOT NULL, `relax_primary_device` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "password", + "columnName": "password", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "secondPasswordSalt", + "columnName": "second_password_salt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeZone", + "columnName": "timezone", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "disableLimitsUntil", + "columnName": "disable_limits_until", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mail", + "columnName": "mail", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentDevice", + "columnName": "current_device", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryForNotAssignedApps", + "columnName": "category_for_not_assigned_apps", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "relaxPrimaryDevice", + "columnName": "relax_primary_device", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `model` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `current_user_id` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `network_time` TEXT NOT NULL, `current_protection_level` TEXT NOT NULL, `highest_permission_level` TEXT NOT NULL, `current_usage_stats_permission` TEXT NOT NULL, `highest_usage_stats_permission` TEXT NOT NULL, `current_notification_access_permission` TEXT NOT NULL, `highest_notification_access_permission` TEXT NOT NULL, `current_app_version` INTEGER NOT NULL, `highest_app_version` INTEGER NOT NULL, `tried_disabling_device_admin` INTEGER NOT NULL, `did_reboot` INTEGER NOT NULL, `had_manipulation` INTEGER NOT NULL, `did_report_uninstall` INTEGER NOT NULL, `is_user_kept_signed_in` INTEGER NOT NULL, `show_device_connected` INTEGER NOT NULL, `default_user` TEXT NOT NULL, `default_user_timeout` INTEGER NOT NULL, `consider_reboot_manipulation` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "model", + "columnName": "model", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addedAt", + "columnName": "added_at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "currentUserId", + "columnName": "current_user_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "installedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "networkTime", + "columnName": "network_time", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentProtectionLevel", + "columnName": "current_protection_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestProtectionLevel", + "columnName": "highest_permission_level", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentUsageStatsPermission", + "columnName": "current_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestUsageStatsPermission", + "columnName": "highest_usage_stats_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentNotificationAccessPermission", + "columnName": "current_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "highestNotificationAccessPermission", + "columnName": "highest_notification_access_permission", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "currentAppVersion", + "columnName": "current_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "highestAppVersion", + "columnName": "highest_app_version", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationTriedDisablingDeviceAdmin", + "columnName": "tried_disabling_device_admin", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "manipulationDidReboot", + "columnName": "did_reboot", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hadManipulation", + "columnName": "had_manipulation", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "didReportUninstall", + "columnName": "did_report_uninstall", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isUserKeptSignedIn", + "columnName": "is_user_kept_signed_in", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "showDeviceConnected", + "columnName": "show_device_connected", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "defaultUser", + "columnName": "default_user", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "defaultUserTimeout", + "columnName": "default_user_timeout", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "considerRebootManipulation", + "columnName": "consider_reboot_manipulation", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isLaunchable", + "columnName": "launchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recommendation", + "columnName": "recommendation", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_app_device_id", + "unique": false, + "columnNames": [ + "device_id" + ], + "createSql": "CREATE INDEX `index_app_device_id` ON `${TABLE_NAME}` (`device_id`)" + }, + { + "name": "index_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`category_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`category_id`, `package_name`))", + "fields": [ + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_category_app_category_id", + "unique": false, + "columnNames": [ + "category_id" + ], + "createSql": "CREATE INDEX `index_category_app_category_id` ON `${TABLE_NAME}` (`category_id`)" + }, + { + "name": "index_category_app_package_name", + "unique": false, + "columnNames": [ + "package_name" + ], + "createSql": "CREATE INDEX `index_category_app_package_name` ON `${TABLE_NAME}` (`package_name`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "category", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `child_id` TEXT NOT NULL, `title` TEXT NOT NULL, `blocked_times` TEXT NOT NULL, `extra_time` INTEGER NOT NULL, `temporarily_blocked` INTEGER NOT NULL, `base_version` TEXT NOT NULL, `apps_version` TEXT NOT NULL, `rules_version` TEXT NOT NULL, `usedtimes_version` TEXT NOT NULL, `parent_category_id` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "childId", + "columnName": "child_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "blockedMinutesInWeek", + "columnName": "blocked_times", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "extraTimeInMillis", + "columnName": "extra_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "temporarilyBlocked", + "columnName": "temporarily_blocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "baseVersion", + "columnName": "base_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "assignedAppsVersion", + "columnName": "apps_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timeLimitRulesVersion", + "columnName": "rules_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "usedTimesVersion", + "columnName": "usedtimes_version", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentCategoryId", + "columnName": "parent_category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "used_time", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day_of_epoch` INTEGER NOT NULL, `used_time` INTEGER NOT NULL, `category_id` TEXT NOT NULL, PRIMARY KEY(`category_id`, `day_of_epoch`))", + "fields": [ + { + "fieldPath": "dayOfEpoch", + "columnName": "day_of_epoch", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "usedMillis", + "columnName": "used_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "category_id", + "day_of_epoch" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "time_limit_rule", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `category_id` TEXT NOT NULL, `apply_to_extra_time_usage` INTEGER NOT NULL, `day_mask` INTEGER NOT NULL, `max_time` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "categoryId", + "columnName": "category_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "applyToExtraTimeUsage", + "columnName": "apply_to_extra_time_usage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dayMask", + "columnName": "day_mask", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maximumTimeInMillis", + "columnName": "max_time", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "id" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "temporarily_allowed_app", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`device_id` TEXT NOT NULL, `package_name` TEXT NOT NULL, PRIMARY KEY(`device_id`, `package_name`))", + "fields": [ + { + "fieldPath": "deviceId", + "columnName": "device_id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "device_id", + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "pending_sync_action", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`sequence_number` INTEGER NOT NULL, `action` TEXT NOT NULL, `integrity` TEXT NOT NULL, `scheduled_for_upload` INTEGER NOT NULL, `type` TEXT NOT NULL, `user_id` TEXT NOT NULL, PRIMARY KEY(`sequence_number`))", + "fields": [ + { + "fieldPath": "sequenceNumber", + "columnName": "sequence_number", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encodedAction", + "columnName": "action", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "integrity", + "columnName": "integrity", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scheduledForUpload", + "columnName": "scheduled_for_upload", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "userId", + "columnName": "user_id", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "sequence_number" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_pending_sync_action_scheduled_for_upload", + "unique": false, + "columnNames": [ + "scheduled_for_upload" + ], + "createSql": "CREATE INDEX `index_pending_sync_action_scheduled_for_upload` ON `${TABLE_NAME}` (`scheduled_for_upload`)" + } + ], + "foreignKeys": [] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"296a30b106e25bcc42a3a6a244363bd9\")" + ] + } +} \ No newline at end of file diff --git a/app/src/androidTest/java/io/timelimit/android/ExampleInstrumentedTest.kt b/app/src/androidTest/java/io/timelimit/android/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..f1393dd --- /dev/null +++ b/app/src/androidTest/java/io/timelimit/android/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package io.timelimit.android + +import androidx.test.InstrumentationRegistry +import androidx.test.runner.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getTargetContext() + assertEquals("io.timelimit.android", appContext.packageName) + } +} diff --git a/app/src/androidTest/java/io/timelimit/android/logic/TestAppLogicTest.kt b/app/src/androidTest/java/io/timelimit/android/logic/TestAppLogicTest.kt new file mode 100644 index 0000000..b6461f5 --- /dev/null +++ b/app/src/androidTest/java/io/timelimit/android/logic/TestAppLogicTest.kt @@ -0,0 +1,72 @@ +package io.timelimit.android.logic + +import androidx.test.InstrumentationRegistry +import io.timelimit.android.data.model.NetworkTime +import io.timelimit.android.integration.platform.ProtectionLevel +import io.timelimit.android.integration.platform.dummy.DummyApps +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Test + +class TestAppLogicTest { + companion object { + private const val PAUSE_L = 300L + private const val PARENT_PASSWORD = "secretsecret123" + } + + @Test + fun testDoesNotBlockAppWithoutSetup() { + runBlocking (Dispatchers.Main) { + val appLogic = TestAppLogic( + maximumProtectionLevel = ProtectionLevel.SimpleDeviceAdmin, + context = InstrumentationRegistry.getTargetContext() + ) + + try { + appLogic.timeApi.emulateTimePassing(PAUSE_L) + delay(PAUSE_L) + + assertEquals(null, appLogic.platformIntegration.getAndResetShowAppLockScreen()) + + appLogic.platformIntegration.foregroundApp = DummyApps.taskmanagerLocalApp.packageName + + appLogic.timeApi.emulateTimePassing(PAUSE_L) + delay(PAUSE_L) + + assertEquals(null, appLogic.platformIntegration.getAndResetShowAppLockScreen()) + } finally { + appLogic.logic.shutdown() + } + } + } + + @Test + fun testDoesBlockAppAfterSetup() { + runBlocking (Dispatchers.Main) { + val appLogic = TestAppLogic( + maximumProtectionLevel = ProtectionLevel.SimpleDeviceAdmin, + context = InstrumentationRegistry.getTargetContext() + ) + + try { + appLogic.logic.appSetupLogic.setupForLocalUse(PARENT_PASSWORD, NetworkTime.Disabled, InstrumentationRegistry.getTargetContext()) + + appLogic.timeApi.emulateTimePassing(PAUSE_L) + delay(PAUSE_L) + + assertEquals(null, appLogic.platformIntegration.getAndResetShowAppLockScreen()) + + appLogic.platformIntegration.foregroundApp = DummyApps.taskmanagerLocalApp.packageName + + appLogic.timeApi.emulateTimePassing(PAUSE_L) + delay(PAUSE_L) + + assertEquals(DummyApps.taskmanagerLocalApp.packageName, appLogic.platformIntegration.getAndResetShowAppLockScreen()) + } finally { + appLogic.logic.shutdown() + } + } + } +} diff --git a/app/src/androidTest/java/io/timelimit/android/sync/actions/Actions.kt b/app/src/androidTest/java/io/timelimit/android/sync/actions/Actions.kt new file mode 100644 index 0000000..23a1a21 --- /dev/null +++ b/app/src/androidTest/java/io/timelimit/android/sync/actions/Actions.kt @@ -0,0 +1,16 @@ +package io.timelimit.android.sync.actions + +import org.json.JSONObject +import org.junit.Test + +class Actions { + @Test + fun decrementCategoryExtraTimeShouldBeSerializedAndParsedCorrectly() { + val originalAction = DecrementCategoryExtraTimeAction(categoryId = "abcdef", extraTimeToSubtract = 1000 * 30) + + val serializedAction = SerializationUtil.serializeAction(originalAction) + val parsedAction = ActionParser.parseAppLogicAction(JSONObject(serializedAction)) + + assert(parsedAction == originalAction) + } +} \ No newline at end of file diff --git a/app/src/developmentServer/AndroidManifest.xml b/app/src/developmentServer/AndroidManifest.xml new file mode 100644 index 0000000..2d731af --- /dev/null +++ b/app/src/developmentServer/AndroidManifest.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/app/src/developmentServer/java/io/timelimit/pinning/CertificatePinning.kt b/app/src/developmentServer/java/io/timelimit/pinning/CertificatePinning.kt new file mode 100644 index 0000000..6662440 --- /dev/null +++ b/app/src/developmentServer/java/io/timelimit/pinning/CertificatePinning.kt @@ -0,0 +1,24 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.pinning + +import io.timelimit.android.BuildConfig +import okhttp3.CertificatePinner + +object CertificatePinning { + val configuration = CertificatePinner.Builder() + .build() +} diff --git a/app/src/directVersion/res/values/strings.xml b/app/src/directVersion/res/values/strings.xml new file mode 100644 index 0000000..8e1046e --- /dev/null +++ b/app/src/directVersion/res/values/strings.xml @@ -0,0 +1,18 @@ + + + + @string/admin_description_direct + \ No newline at end of file diff --git a/app/src/directVersion/res/xml-v21/admin.xml b/app/src/directVersion/res/xml-v21/admin.xml new file mode 100644 index 0000000..62a0e74 --- /dev/null +++ b/app/src/directVersion/res/xml-v21/admin.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/app/src/directVersion/res/xml/admin.xml b/app/src/directVersion/res/xml/admin.xml new file mode 100644 index 0000000..a96572a --- /dev/null +++ b/app/src/directVersion/res/xml/admin.xml @@ -0,0 +1,22 @@ + + + + + + + + + \ No newline at end of file diff --git a/app/src/googleApi/java/io/timelimit/android/flavors/GoogleSignInUtil.kt b/app/src/googleApi/java/io/timelimit/android/flavors/GoogleSignInUtil.kt new file mode 100644 index 0000000..7c09760 --- /dev/null +++ b/app/src/googleApi/java/io/timelimit/android/flavors/GoogleSignInUtil.kt @@ -0,0 +1,50 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.flavors + +import android.app.Activity +import android.content.Intent +import com.google.android.gms.auth.api.signin.GoogleSignIn +import com.google.android.gms.auth.api.signin.GoogleSignInClient +import com.google.android.gms.auth.api.signin.GoogleSignInOptions +import com.google.android.gms.common.api.ApiException +import io.timelimit.android.BuildConfig + +class GoogleSignInUtil(private val activity: Activity) { + private val client: GoogleSignInClient by lazy { + GoogleSignIn.getClient( + activity, + GoogleSignInOptions.Builder() + .requestEmail() + .requestIdToken(BuildConfig.googleAuthClientId) + .build() + ) + } + + fun getSignInIntent() = client.signInIntent + + fun processActivityResult(data: Intent?): String? { + val task = GoogleSignIn.getSignedInAccountFromIntent(data) + + try { + return task.getResult(ApiException::class.java)?.idToken + } catch (ex: ApiException) { + // login failed + + return null + } + } +} diff --git a/app/src/googleApiStoreVersionProductionServer/play/contactEmail b/app/src/googleApiStoreVersionProductionServer/play/contactEmail new file mode 100644 index 0000000..c1bb1a7 --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/contactEmail @@ -0,0 +1 @@ +support@timelimit.io \ No newline at end of file diff --git a/app/src/googleApiStoreVersionProductionServer/play/contactPhone b/app/src/googleApiStoreVersionProductionServer/play/contactPhone new file mode 100644 index 0000000..e69de29 diff --git a/app/src/googleApiStoreVersionProductionServer/play/contactWebsite b/app/src/googleApiStoreVersionProductionServer/play/contactWebsite new file mode 100644 index 0000000..328d0ed --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/contactWebsite @@ -0,0 +1 @@ +https://timelimit.io \ No newline at end of file diff --git a/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/fulldescription b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/fulldescription new file mode 100644 index 0000000..3c6021a --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/fulldescription @@ -0,0 +1,17 @@ +Mit TimeLimit kann die Nutzungsdauer flexibel beschränkt werden. Es gibt frei wählbare Sperrzeiten, um z.B. zu verhindern, dass zu spät noch gespielt wird. Dabei können je nach App andere Regeln festgelegt werden. + +Je nach Version kann eine Extrazeit festgelegt werden, z.B. als Belohnung. Diese kann frei eingeteilt werden und wird automatisch verbraucht, sobald die reguläre Zeit vorbei ist. Es ist zusätzlich möglich, die Nutzung der Extrazeit einzuschränken. + +Je nach Version können die Zeitbegrenzungen vorübergehend deaktiviert werden. + +Es gibt zusätzlich einen vernetzten Modus. In diesem können Einstellungen von jedem Gerät aus geändert werden. In der Vollversion ist es außerdem möglich, ferngesteuert Geräte vorübergehend zu sperren. + +Außerdem können in der Vollversion für einen Benutzer mehrere Geräte hinterlegt werden und der Nutzer kann jeweils eins dieser Geräte zur Benutzung wählen. Die verbrauchten Zeiten werden dabei automatisch über alle Geräte addiert. + +Es gibt eine detailierte Dokumentation der Bedienung und Funktionen dieser App unter https://timelimit.io/de/dokumentation/ + +Je nach Android-Version verwendet TimeLimit die Berechtigung zum Nutzungsdatenzugriff oder die "GET_TASKS"-Berechtigung. Diese werden ausschließlich zur Erkennung der momentan genutzten App verwendet. Auf der Basis der momentan genutzten App erfolgt eine Sperrung, eine Freigabe oder eine Berechnung der verbleibenden Nutzungsdauer. + +Die Geräte-Administrator-Berechtigung wird genutzt, um ein Deinstallieren von TimeLimit zu erkennen. + +TimeLimit verwendet den Benachrichtigungszugriff, um auch die Benachrichtigungen von gesperrten Apps zu sperren. Es erfolgt keine Speicherung von Benachrichtigungen oder deren Inhalten. diff --git a/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/phoneScreenshots/1.png b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/phoneScreenshots/1.png new file mode 100644 index 0000000..a3b90af Binary files /dev/null and b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/phoneScreenshots/1.png differ diff --git a/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/phoneScreenshots/2.png b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/phoneScreenshots/2.png new file mode 100644 index 0000000..3e4e0ed Binary files /dev/null and b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/phoneScreenshots/2.png differ diff --git a/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/shortdescription b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/shortdescription new file mode 100644 index 0000000..b4a8669 --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/shortdescription @@ -0,0 +1 @@ +Einfach die Nutzungszeit beschränken \ No newline at end of file diff --git a/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/title b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/title new file mode 100644 index 0000000..998e63f --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/title @@ -0,0 +1 @@ +TimeLimit Beta - Nutzungszeit beschränken \ No newline at end of file diff --git a/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/video b/app/src/googleApiStoreVersionProductionServer/play/de-DE/listing/video new file mode 100644 index 0000000..e69de29 diff --git a/app/src/googleApiStoreVersionProductionServer/play/de-DE/whatsnew b/app/src/googleApiStoreVersionProductionServer/play/de-DE/whatsnew new file mode 100644 index 0000000..2399f5f --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/de-DE/whatsnew @@ -0,0 +1,4 @@ +- E-Mail-Benachrichtigungen bei Manipulationen (nur bei neuen Benutzern standardmäßig aktiviert) +- Hinweis, wenn auf einem anderen Gerät eine ältere App-Version installiert ist +- Umbenennen von Kind-Benutzern + diff --git a/app/src/googleApiStoreVersionProductionServer/play/defaultLanguage b/app/src/googleApiStoreVersionProductionServer/play/defaultLanguage new file mode 100644 index 0000000..f2b0341 --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/defaultLanguage @@ -0,0 +1 @@ +en-US \ No newline at end of file diff --git a/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/fulldescription b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/fulldescription new file mode 100644 index 0000000..eb2ddfd --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/fulldescription @@ -0,0 +1,15 @@ +With TimeLimit, you can limit the usage duration flexibly. You can freely select times at which the usage is blocked, e.g. to prevent that games are played very late. You can chose different settings for different Apps. + +Depending on the version, you can add extra time, e.g. as reward. This can be set freely and is spent automatically when the regular limit was reached. Additionally, it's possible to limit the usage of extra time. + +Depending on the version, you can disable the time limits temporarily. + +There exists a connected mode. In this mode, you can change the settings from every device. Additionally, in the premium version you can temporarily block devices remotely. + +Moreover, you can assign one user to multiple devices in the premium version. The user can select one device for using it. The times are then added across all devices. + +Depending on the Android version, TimeLimit uses the permission for the usage stats access or the GET_TASKS permission. These are only used to detect the currently used App. Based on the currently used App, the App is blocked, allowed, or the remaining time is calculated. + +The device admin permission is used to detect an uninstallation of TimeLimit. + +TimeLimit uses the notification access to block notifications of blocked apps. Notifications and their contents are not saved. \ No newline at end of file diff --git a/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/phoneScreenshots/1.png b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/phoneScreenshots/1.png new file mode 100644 index 0000000..21fe8f3 Binary files /dev/null and b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/phoneScreenshots/1.png differ diff --git a/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/phoneScreenshots/2.png b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/phoneScreenshots/2.png new file mode 100644 index 0000000..b041fc3 Binary files /dev/null and b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/phoneScreenshots/2.png differ diff --git a/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/shortdescription b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/shortdescription new file mode 100644 index 0000000..a65bfb2 --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/shortdescription @@ -0,0 +1 @@ +Simply limit the usage duration \ No newline at end of file diff --git a/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/title b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/title new file mode 100644 index 0000000..46c8806 --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/title @@ -0,0 +1 @@ +TimeLimit Beta - limit usage duration \ No newline at end of file diff --git a/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/video b/app/src/googleApiStoreVersionProductionServer/play/en-US/listing/video new file mode 100644 index 0000000..e69de29 diff --git a/app/src/googleApiStoreVersionProductionServer/play/en-US/whatsnew b/app/src/googleApiStoreVersionProductionServer/play/en-US/whatsnew new file mode 100644 index 0000000..d84b1fb --- /dev/null +++ b/app/src/googleApiStoreVersionProductionServer/play/en-US/whatsnew @@ -0,0 +1,3 @@ +- mail notifications about manipulations (enabled by default for new users only) +- info if an other device uses an older App version +- renaming of child users diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..f5e1abf --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,121 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/feature graphic.png b/app/src/main/feature graphic.png new file mode 100644 index 0000000..c9bf09c Binary files /dev/null and b/app/src/main/feature graphic.png differ diff --git a/app/src/main/feature graphic.xcf b/app/src/main/feature graphic.xcf new file mode 100644 index 0000000..76fb42d Binary files /dev/null and b/app/src/main/feature graphic.xcf differ diff --git a/app/src/main/java/io/timelimit/android/Application.kt b/app/src/main/java/io/timelimit/android/Application.kt new file mode 100644 index 0000000..e03d042 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/Application.kt @@ -0,0 +1,32 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android + +import android.app.Application +import com.jakewharton.threetenabp.AndroidThreeTen +import org.solovyev.android.checkout.Billing + +class Application : Application() { + override fun onCreate() { + super.onCreate() + + AndroidThreeTen.init(this) + } + + val billing = Billing(this, object: Billing.DefaultConfiguration() { + override fun getPublicKey() = BuildConfig.googlePlayKey + }) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/async/Threads.kt b/app/src/main/java/io/timelimit/android/async/Threads.kt new file mode 100644 index 0000000..df7b0a5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/async/Threads.kt @@ -0,0 +1,27 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.async + +import android.os.Handler +import android.os.Looper +import java.util.concurrent.Executors + +object Threads { + val database = Executors.newSingleThreadExecutor()!! + val mainThreadHandler = Handler(Looper.getMainLooper()) + val network = Executors.newSingleThreadExecutor() + val crypto = Executors.newSingleThreadExecutor() +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/coroutines/AwaitExecutorExecution.kt b/app/src/main/java/io/timelimit/android/coroutines/AwaitExecutorExecution.kt new file mode 100644 index 0000000..439e7a2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/coroutines/AwaitExecutorExecution.kt @@ -0,0 +1,45 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.coroutines + +import java.util.concurrent.Executor +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException +import kotlin.coroutines.suspendCoroutine + +suspend fun Executor.executeAndWait(runnable: Runnable) { + suspendCoroutine { + this.execute { + try { + runnable.run() + + it.resume(null) + } catch (ex: Exception) { + it.resumeWithException(ex) + } + } + } +} + +suspend fun Executor.executeAndWait(function: () -> R) = suspendCoroutine { + this.execute { + try { + it.resume(function()) + } catch (ex: Exception) { + it.resumeWithException(ex) + } + } +} diff --git a/app/src/main/java/io/timelimit/android/coroutines/CoroutineFragment.kt b/app/src/main/java/io/timelimit/android/coroutines/CoroutineFragment.kt new file mode 100644 index 0000000..6cf63ac --- /dev/null +++ b/app/src/main/java/io/timelimit/android/coroutines/CoroutineFragment.kt @@ -0,0 +1,35 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.coroutines + +import androidx.fragment.app.Fragment +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlin.coroutines.CoroutineContext + +open class CoroutineFragment: Fragment(), CoroutineScope { + private val job = Job() + + override val coroutineContext: CoroutineContext + get() = job + Dispatchers.Main + + override fun onDestroy() { + super.onDestroy() + + job.cancel() + } +} diff --git a/app/src/main/java/io/timelimit/android/coroutines/OkHttp.kt b/app/src/main/java/io/timelimit/android/coroutines/OkHttp.kt new file mode 100644 index 0000000..5f0993b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/coroutines/OkHttp.kt @@ -0,0 +1,38 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.coroutines + +import okhttp3.Call +import okhttp3.Callback +import okhttp3.Response +import java.io.IOException +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException +import kotlin.coroutines.suspendCoroutine + +suspend fun Call.waitForResponse(): Response { + return suspendCoroutine { + this.enqueue(object: Callback { + override fun onFailure(call: Call, e: IOException) { + it.resumeWithException(e) + } + + override fun onResponse(call: Call, response: Response) { + it.resume(response) + } + }) + } +} diff --git a/app/src/main/java/io/timelimit/android/coroutines/RunAsync.kt b/app/src/main/java/io/timelimit/android/coroutines/RunAsync.kt new file mode 100644 index 0000000..27cee49 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/coroutines/RunAsync.kt @@ -0,0 +1,39 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.coroutines + +import io.timelimit.android.async.Threads +import kotlinx.coroutines.* + +fun runAsync(block: suspend CoroutineScope.() -> T) { + GlobalScope.launch (Dispatchers.Main) { + block() + }.invokeOnCompletion { + if (it != null && (!(it is CancellationException))) { + Threads.mainThreadHandler.post { + throw it + } + } + } +} + +fun runAsyncExpectForever(block: suspend CoroutineScope.() -> T) { + runAsync { + block() + + throw IllegalStateException() + } +} diff --git a/app/src/main/java/io/timelimit/android/crypto/AES.kt b/app/src/main/java/io/timelimit/android/crypto/AES.kt new file mode 100644 index 0000000..31a35d4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/crypto/AES.kt @@ -0,0 +1,21 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.crypto + +object AES { + const val KEY_LENGTH_BYTES = 16 + const val IV_LENGTH_BYTES = 16 +} diff --git a/app/src/main/java/io/timelimit/android/crypto/HexString.kt b/app/src/main/java/io/timelimit/android/crypto/HexString.kt new file mode 100644 index 0000000..0f0764b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/crypto/HexString.kt @@ -0,0 +1,61 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.crypto + +object HexString { + fun toHex(data: ByteArray): String { + return StringBuilder(data.size * 2).apply { + for (i in data.indices) { + append(Integer.toString(data[i].toInt() shr 4 and 15, 16)) + append(Integer.toString(data[i].toInt() and 15, 16)) + } + }.toString() + } + + fun fromHex(value: String): ByteArray { + if (value.length % 2 != 0) { + throw IllegalArgumentException() + } + + val result = ByteArray(value.length / 2) + + for (index in result.indices) { + result.set( + index = index, + value = ( + (Integer.parseInt(value[index * 2 + 0].toString(), 16) shl 4) or + Integer.parseInt(value[index * 2 + 1].toString(), 16) + ).toByte() + ) + } + + return result + } + + fun assertIsHexString(value: String) { + if (value.length % 2 != 0) { + throw IllegalArgumentException() + } + + value.forEach { + char -> + + if ("0123456789abcdef".indexOf(char) == -1) { + throw IllegalArgumentException() + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/crypto/PasswordHashing.kt b/app/src/main/java/io/timelimit/android/crypto/PasswordHashing.kt new file mode 100644 index 0000000..5c482d2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/crypto/PasswordHashing.kt @@ -0,0 +1,33 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.crypto + +import org.mindrot.jbcrypt.BCrypt + +object PasswordHashing { + fun hashSync(password: String) = hashSyncWithSalt(password, generateSalt()) + + fun hashSyncWithSalt(password: String, salt: String): String = BCrypt.hashpw(password, salt) + fun generateSalt(): String = BCrypt.gensalt() + + fun validateSync(password: String, hashed: String): Boolean { + try { + return BCrypt.checkpw(password, hashed) + } catch (ex: Exception) { + return false + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/crypto/RandomBytes.kt b/app/src/main/java/io/timelimit/android/crypto/RandomBytes.kt new file mode 100644 index 0000000..73742f0 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/crypto/RandomBytes.kt @@ -0,0 +1,30 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.crypto + +import java.security.SecureRandom + +object RandomBytes { + private val random: SecureRandom by lazy { SecureRandom() } + + fun randomBytes(length: Int): ByteArray { + val result = ByteArray(length) + + random.nextBytes(result) + + return result + } +} diff --git a/app/src/main/java/io/timelimit/android/crypto/Sha512.kt b/app/src/main/java/io/timelimit/android/crypto/Sha512.kt new file mode 100644 index 0000000..d44087d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/crypto/Sha512.kt @@ -0,0 +1,28 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.crypto + +import java.security.MessageDigest + +object Sha512 { + private val messageDigest: MessageDigest by lazy { MessageDigest.getInstance("SHA-512") } + + fun hashSync(data: String): String { + return HexString.toHex(hashSync(data.toByteArray(charset("UTF-8")))) + } + + fun hashSync(data: ByteArray) = messageDigest.digest(data) +} diff --git a/app/src/main/java/io/timelimit/android/data/Database.kt b/app/src/main/java/io/timelimit/android/data/Database.kt new file mode 100644 index 0000000..d13c69b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/Database.kt @@ -0,0 +1,59 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data + +import io.timelimit.android.data.dao.* +import java.io.Closeable + +interface Database { + fun app(): AppDao + fun categoryApp(): CategoryAppDao + fun category(): CategoryDao + fun config(): ConfigDao + fun device(): DeviceDao + fun timeLimitRules(): TimeLimitRuleDao + fun usedTimes(): UsedTimeDao + fun user(): UserDao + fun temporarilyAllowedApp(): TemporarilyAllowedAppDao + fun pendingSyncAction(): PendingSyncActionDao + + fun beginTransaction() + fun setTransactionSuccessful() + fun endTransaction() + + fun deleteAllData() + fun close() +} + +fun Database.transaction(): Transaction { + val db = this + + db.beginTransaction() + + return object: Transaction { + override fun setSuccess() { + db.setTransactionSuccessful() + } + + override fun close() { + db.endTransaction() + } + } +} + +interface Transaction: Closeable { + fun setSuccess() +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/data/IdGenerator.kt b/app/src/main/java/io/timelimit/android/data/IdGenerator.kt new file mode 100644 index 0000000..17b1543 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/IdGenerator.kt @@ -0,0 +1,54 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data + +import java.security.SecureRandom + +object IdGenerator { + private const val LENGTH = 6 + private const val CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + private val random: SecureRandom by lazy { SecureRandom() } + + fun generateId(): String { + val output = StringBuilder(LENGTH) + + for (i in 1..LENGTH) { + output.append(CHARS[random.nextInt(CHARS.length)]) + } + + return output.toString() + } + + private fun isIdValid(id: String): Boolean { + if (id.length != LENGTH) { + return false + } + + for (char in id) { + if (!CHARS.contains(char)) { + return false + } + } + + return true + } + + fun assertIdValid(id: String) { + if (!isIdValid(id)) { + throw IllegalArgumentException() + } + } +} diff --git a/app/src/main/java/io/timelimit/android/data/JsonSerializable.kt b/app/src/main/java/io/timelimit/android/data/JsonSerializable.kt new file mode 100644 index 0000000..f5cac87 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/JsonSerializable.kt @@ -0,0 +1,22 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data + +import android.util.JsonWriter + +interface JsonSerializable { + fun serialize(writer: JsonWriter) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/data/Migrations.kt b/app/src/main/java/io/timelimit/android/data/Migrations.kt new file mode 100644 index 0000000..36fea37 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/Migrations.kt @@ -0,0 +1,88 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +object DatabaseMigrations { + val MIGRATE_TO_V2 = object: Migration(1, 2) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE device ADD COLUMN did_report_uninstall INTEGER NOT NULL DEFAULT 0") + } + } + + val MIGRATE_TO_V3 = object: Migration(2, 3) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE device ADD COLUMN is_user_kept_signed_in INTEGER NOT NULL DEFAULT 0") + } + } + + val MIGRATE_TO_V4 = object: Migration(3, 4) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE `user` ADD COLUMN `category_for_not_assigned_apps` TEXT NOT NULL DEFAULT \"\"") + } + } + + val MIGRATE_TO_V5 = object: Migration(4, 5) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE `category` ADD COLUMN `parent_category_id` TEXT NOT NULL DEFAULT \"\"") + } + } + + val MIGRATE_TO_V6 = object: Migration(5, 6) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE `device` ADD COLUMN `show_device_connected` INTEGER NOT NULL DEFAULT 0") + } + } + + val MIGRATE_TO_V7 = object: Migration(6, 7) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE `device` ADD COLUMN `default_user` TEXT NOT NULL DEFAULT \"\"") + database.execSQL("ALTER TABLE `device` ADD COLUMN `default_user_timeout` INTEGER NOT NULL DEFAULT 0") + database.execSQL("ALTER TABLE `user` ADD COLUMN `relax_primary_device` INTEGER NOT NULL DEFAULT 0") + } + } + + val MIGRATE_TO_V8 = object: Migration(7, 8) { + override fun migrate(database: SupportSQLiteDatabase) { + // this is empty + // + // a new possible enum value was added, the version upgrade enables the downgrade mechanism + } + } + + val MIGRATE_TO_V9 = object: Migration(8, 9) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE `device` ADD COLUMN `did_reboot` INTEGER NOT NULL DEFAULT 0") + database.execSQL("ALTER TABLE `device` ADD COLUMN `consider_reboot_manipulation` INTEGER NOT NULL DEFAULT 0") + } + } + + val MIGRATE_TO_V10 = object: Migration(9, 10) { + override fun migrate(database: SupportSQLiteDatabase) { + // this is empty + // + // a new possible enum value was added, the version upgrade enables the downgrade mechanism + } + } + + val MIGRATE_TO_V11 = object: Migration(10, 11) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE `user` ADD COLUMN `mail_notification_flags` INTEGER NOT NULL DEFAULT 0") + } + } +} diff --git a/app/src/main/java/io/timelimit/android/data/RoomDatabase.kt b/app/src/main/java/io/timelimit/android/data/RoomDatabase.kt new file mode 100644 index 0000000..7cab25e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/RoomDatabase.kt @@ -0,0 +1,106 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase +import io.timelimit.android.data.model.* + +@Database(entities = [ + User::class, + Device::class, + App::class, + CategoryApp::class, + Category::class, + UsedTimeItem::class, + TimeLimitRule::class, + ConfigurationItem::class, + TemporarilyAllowedApp::class, + PendingSyncAction::class +], version = 11) +abstract class RoomDatabase: RoomDatabase(), io.timelimit.android.data.Database { + companion object { + private val lock = Object() + private var instance: io.timelimit.android.data.Database? = null + const val DEFAULT_DB_NAME = "db" + const val BACKUP_DB_NAME = "db2" + + fun with(context: Context): io.timelimit.android.data.Database { + if (instance == null) { + synchronized(lock) { + if (instance == null) { + instance = createOrOpenLocalStorageInstance(context, DEFAULT_DB_NAME) + } + } + } + + return instance!! + } + + fun createInMemoryInstance(context: Context): io.timelimit.android.data.Database { + return Room.inMemoryDatabaseBuilder( + context, + io.timelimit.android.data.RoomDatabase::class.java + ).build() + } + + fun createOrOpenLocalStorageInstance(context: Context, name: String): io.timelimit.android.data.Database { + return Room.databaseBuilder( + context, + io.timelimit.android.data.RoomDatabase::class.java, + name + ) + .setJournalMode(JournalMode.TRUNCATE) + .fallbackToDestructiveMigration() + .addMigrations( + DatabaseMigrations.MIGRATE_TO_V2, + DatabaseMigrations.MIGRATE_TO_V3, + DatabaseMigrations.MIGRATE_TO_V4, + DatabaseMigrations.MIGRATE_TO_V5, + DatabaseMigrations.MIGRATE_TO_V6, + DatabaseMigrations.MIGRATE_TO_V7, + DatabaseMigrations.MIGRATE_TO_V8, + DatabaseMigrations.MIGRATE_TO_V9, + DatabaseMigrations.MIGRATE_TO_V10, + DatabaseMigrations.MIGRATE_TO_V11 + ) + .build() + } + } + + // the room compiler needs this + override fun setTransactionSuccessful() { + super.setTransactionSuccessful() + } + + override fun beginTransaction() { + super.beginTransaction() + } + + override fun endTransaction() { + super.endTransaction() + } + + override fun deleteAllData() { + clearAllTables() + } + + override fun close() { + super.close() + } +} diff --git a/app/src/main/java/io/timelimit/android/data/backup/DatabaseBackup.kt b/app/src/main/java/io/timelimit/android/data/backup/DatabaseBackup.kt new file mode 100644 index 0000000..f2f87dc --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/backup/DatabaseBackup.kt @@ -0,0 +1,146 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.backup + +import android.content.Context +import android.util.Log +import androidx.core.util.AtomicFile +import io.timelimit.android.BuildConfig +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.data.RoomDatabase +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import okio.Okio +import java.util.concurrent.Executors + +class DatabaseBackup(private val context: Context) { + companion object { + private const val CONFIG_FILE = "config.json" + private const val LOG_TAG = "DatabaseBackup" + + private var instance: DatabaseBackup? = null + private val lock = Object() + + fun with(context: Context): DatabaseBackup { + if (instance == null) { + synchronized(lock) { + if (instance == null) { + instance = DatabaseBackup(context.applicationContext) + } + } + } + + return instance!! + } + } + + private val executor = Executors.newSingleThreadExecutor() + private val jsonFile = AtomicFile(context.getDatabasePath(CONFIG_FILE)) + private val databaseFile = context.getDatabasePath(RoomDatabase.DEFAULT_DB_NAME) + private val databaseBackupFile = context.getDatabasePath(RoomDatabase.BACKUP_DB_NAME) + private val lock = Mutex() + + suspend fun tryRestoreDatabaseBackupAsyncAndWait() { + executor.executeAndWait { tryRestoreDatabaseBackupSync() } + } + + private fun tryRestoreDatabaseBackupSync() { + runBlocking { + lock.withLock { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "try restoring backup") + } + + val database = RoomDatabase.with(context) + + if (database.config().getOwnDeviceIdSync().orEmpty().isNotEmpty()) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "database is not empty -> don't restore backup") + } + + return@runBlocking + } + + try { + jsonFile.openRead().use { inputStream -> + + DatabaseBackupLowlevel.restoreFromBackupJson(database, inputStream) + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "database was restored from backup") + } + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "error during restoring database backup", ex) + } + } + } + } + } + + fun tryCreateDatabaseBackupAsync() { + executor.submit { tryCreateDatabaseBackupSync() } + } + + private fun tryCreateDatabaseBackupSync() { + runBlocking { + lock.withLock { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "create backup") + } + + try { + // create a temp copy of the database + databaseBackupFile.delete() + Okio.buffer(Okio.source(databaseFile)).readAll(Okio.sink(databaseBackupFile)) + + // open the temp copy + val database = RoomDatabase.createOrOpenLocalStorageInstance(context, RoomDatabase.BACKUP_DB_NAME) + + try { + // open the output file + val output = jsonFile.startWrite() + + try { + DatabaseBackupLowlevel.outputAsBackupJson(database, output) + + jsonFile.finishWrite(output) + } catch (ex: Exception) { + jsonFile.failWrite(output) + + throw ex + } + + null + } finally { + database.close() + } + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "failed to create backup", ex) + } + + null + } finally { + // delete the temp copy + databaseBackupFile.delete() + } + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/data/backup/DatabaseBackupLowlevel.kt b/app/src/main/java/io/timelimit/android/data/backup/DatabaseBackupLowlevel.kt new file mode 100644 index 0000000..df4056c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/backup/DatabaseBackupLowlevel.kt @@ -0,0 +1,190 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.backup + +import android.util.JsonReader +import android.util.JsonWriter +import io.timelimit.android.data.Database +import io.timelimit.android.data.JsonSerializable +import io.timelimit.android.data.model.* +import io.timelimit.android.data.transaction +import java.io.InputStream +import java.io.InputStreamReader +import java.io.OutputStream +import java.io.OutputStreamWriter + +object DatabaseBackupLowlevel { + private const val PAGE_SIZE = 50 + + private const val APP = "app" + private const val CATEGORY = "category" + private const val CATEGORY_APP = "categoryApp" + private const val CONFIG = "config" + private const val DEVICE = "device" + private const val PENDING_SYNC_ACTION = "pendingSyncAction" + private const val TIME_LIMIT_RULE = "timelimitRule" + private const val USED_TIME_ITEM = "usedTime" + private const val USER = "user" + + fun outputAsBackupJson(database: Database, outputStream: OutputStream) { + val writer = JsonWriter(OutputStreamWriter(outputStream, Charsets.UTF_8)) + + writer.beginObject() + + fun handleCollection( + name: String, + readPage: (offset: Int, pageSize: Int) -> List + ) { + writer.name(name).beginArray() + + var offset = 0 + + while (true) { + val page = readPage(offset, PAGE_SIZE) + offset += page.size + + if (page.isEmpty()) { + break + } + + page.forEach { it.serialize(writer) } + } + + writer.endArray() + } + + handleCollection(APP) {offset, pageSize -> database.app().getAppPageSync(offset, pageSize) } + handleCollection(CATEGORY) {offset: Int, pageSize: Int -> database.category().getCategoryPageSync(offset, pageSize) } + handleCollection(CATEGORY_APP) { offset, pageSize -> database.categoryApp().getCategoryAppPageSync(offset, pageSize) } + + writer.name(CONFIG).beginArray() + database.config().getConfigItemsSync().forEach { it.serialize(writer) } + writer.endArray() + + handleCollection(DEVICE) { offset, pageSize -> database.device().getDevicePageSync(offset, pageSize) } + handleCollection(PENDING_SYNC_ACTION) { offset, pageSize -> database.pendingSyncAction().getPendingSyncActionPageSync(offset, pageSize) } + handleCollection(TIME_LIMIT_RULE) { offset, pageSize -> database.timeLimitRules().getRulePageSync(offset, pageSize) } + handleCollection(USED_TIME_ITEM) { offset, pageSize -> database.usedTimes().getUsedTimePageSync(offset, pageSize) } + handleCollection(USER) { offset, pageSize -> database.user().getUserPageSync(offset, pageSize) } + + writer.endObject().flush() + } + + fun restoreFromBackupJson(database: Database, inputStream: InputStream) { + val reader = JsonReader(InputStreamReader(inputStream, Charsets.UTF_8)) + + database.transaction().use { + transaction -> + + database.deleteAllData() + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + APP -> { + reader.beginArray() + + while (reader.hasNext()) { + database.app().addAppSync(App.parse(reader)) + } + + reader.endArray() + } + CATEGORY -> { + reader.beginArray() + + while (reader.hasNext()) { + database.category().addCategory(Category.parse(reader)) + } + + reader.endArray() + } + CATEGORY_APP -> { + reader.beginArray() + + while (reader.hasNext()) { + database.categoryApp().addCategoryAppSync(CategoryApp.parse(reader)) + } + + reader.endArray() + } + CONFIG -> { + reader.beginArray() + + while (reader.hasNext()) { + val item = ConfigurationItem.parse(reader) + + if (item != null) { + database.config().updateValueOfKeySync(item) + } + } + + reader.endArray() + } + DEVICE -> { + reader.beginArray() + + while (reader.hasNext()) { + database.device().addDeviceSync(Device.parse(reader)) + } + + reader.endArray() + } + PENDING_SYNC_ACTION -> { + reader.beginArray() + + while (reader.hasNext()) { + database.pendingSyncAction().addSyncActionSync(PendingSyncAction.parse(reader)) + } + + reader.endArray() + } + TIME_LIMIT_RULE -> { + reader.beginArray() + + while (reader.hasNext()) { + database.timeLimitRules().addTimeLimitRule(TimeLimitRule.parse(reader)) + } + + reader.endArray() + } + USED_TIME_ITEM -> { + reader.beginArray() + + while (reader.hasNext()) { + database.usedTimes().insertUsedTime(UsedTimeItem.parse(reader)) + } + + reader.endArray() + } + USER -> { + reader.beginArray() + + while (reader.hasNext()) { + database.user().addUserSync(User.parse(reader)) + } + + reader.endArray() + } + else -> reader.skipValue() + } + } + reader.endObject() + + transaction.setSuccess() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/data/customtypes/Bitmask.kt b/app/src/main/java/io/timelimit/android/data/customtypes/Bitmask.kt new file mode 100644 index 0000000..27c5d0b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/customtypes/Bitmask.kt @@ -0,0 +1,115 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.customtypes + +import android.os.Parcelable +import android.text.TextUtils +import androidx.room.TypeConverter +import kotlinx.android.parcel.Parcelize +import java.util.* +import kotlin.collections.ArrayList + +sealed class Bitmask(private val data: BitSet) { + fun read(index: Int): Boolean { + return data[index] + } +} + +data class MutableBitmask (val data: BitSet): Bitmask(data) { + fun write(index: Int, value: Boolean) { + data[index] = value + } + + fun toImmutable(): ImmutableBitmask { + return ImmutableBitmask(data.clone() as BitSet) + } +} + +@Parcelize +data class ImmutableBitmask(val dataNotToModify: BitSet): Bitmask(dataNotToModify), Parcelable { + fun toMutable(): MutableBitmask { + return MutableBitmask(dataNotToModify) + } +} + +// format: index of start of set bits, index of stop of set bits, ... +class ImmutableBitmaskAdapter { + @TypeConverter + fun toString(mask: ImmutableBitmask) = ImmutableBitmaskJson.serialize(mask) + + @TypeConverter + fun toImmutableBitmask(data: String) = ImmutableBitmaskJson.parse(data, null) +} + +object ImmutableBitmaskJson { + fun serialize(mask: ImmutableBitmask): String { + val output = ArrayList() + + if (mask.read(0)) { + // if first bit is set + + output.add(0) + } else { + // if first bit is not set + + val start = mask.dataNotToModify.nextSetBit(0) + + if (start == -1) { + // nothing is set + return "" + } + + output.add(start) + } + + do { + val startIndex = output.last() + val stopIndex = mask.dataNotToModify.nextClearBit(startIndex) + + output.add(stopIndex) + + val nextStartIndex = mask.dataNotToModify.nextSetBit(stopIndex) + if (nextStartIndex == -1) { + break + } else { + output.add(nextStartIndex) + } + } while (true) + + return TextUtils.join(",", output.map { it.toString() }) + } + + fun parse(data: String, maxSize: Int?): ImmutableBitmask { + val indexes = data.split(",").filter{ it.isNotBlank() }.map { it.toInt() } + val iterator = indexes.iterator() + val output = BitSet() + + while (iterator.hasNext()) { + val start = iterator.next() + val end = iterator.next() + + if (maxSize != null) { + if (start > maxSize || end > maxSize) { + throw IllegalArgumentException() + } + } + + output.set(start, end) + } + + return ImmutableBitmask(output) + } +} diff --git a/app/src/main/java/io/timelimit/android/data/dao/AppDao.kt b/app/src/main/java/io/timelimit/android/data/dao/AppDao.kt new file mode 100644 index 0000000..2e5a695 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/AppDao.kt @@ -0,0 +1,58 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.dao + +import androidx.lifecycle.LiveData +import androidx.room.* +import io.timelimit.android.data.model.App +import io.timelimit.android.data.model.AppRecommendation +import io.timelimit.android.data.model.AppRecommendationConverter + +@Dao +@TypeConverters( + AppRecommendationConverter::class +) +interface AppDao { + @Query("DELETE FROM app WHERE device_id = :deviceId") + fun deleteAllAppsByDeviceId(deviceId: String) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun addAppsSync(apps: Collection) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun addAppSync(app: App) + + @Query("DELETE FROM app WHERE device_id = :deviceId AND package_name IN (:packageNames)") + fun removeAppsByDeviceIdAndPackageNamesSync(deviceId: String, packageNames: List) + + @Query("SELECT * FROM app WHERE device_id IN (:deviceIds)") + fun getAppsByDeviceIds(deviceIds: List): LiveData> + + @Query("SELECT * FROM app") + fun getAllApps(): LiveData> + + @Query("SELECT * FROM app WHERE device_id IN (:deviceIds) AND package_name = :packageName") + fun getAppsByDeviceIdsAndPackageName(deviceIds: List, packageName: String): LiveData> + + @Query("SELECT * FROM app WHERE device_id = :deviceId") + fun getAppsByDeviceIdAsync(deviceId: String): LiveData> + + @Query("SELECT * FROM app LIMIT :pageSize OFFSET :offset") + fun getAppPageSync(offset: Int, pageSize: Int): List + + @Query("SELECT * FROM app WHERE recommendation = :recommendation") + fun getAppsByRecommendationLive(recommendation: AppRecommendation): LiveData> +} diff --git a/app/src/main/java/io/timelimit/android/data/dao/CategoryAppDao.kt b/app/src/main/java/io/timelimit/android/data/dao/CategoryAppDao.kt new file mode 100644 index 0000000..983ce13 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/CategoryAppDao.kt @@ -0,0 +1,49 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.dao + +import androidx.lifecycle.LiveData +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import io.timelimit.android.data.model.CategoryApp + +@Dao +abstract class CategoryAppDao { + @Query("SELECT * FROM category_app WHERE category_id IN (:categoryIds) AND package_name = :packageName") + abstract fun getCategoryApp(categoryIds: List, packageName: String): LiveData + + @Query("SELECT * FROM category_app WHERE category_id = :categoryId") + abstract fun getCategoryApps(categoryId: String): LiveData> + + @Query("SELECT * FROM category_app WHERE category_id IN (:categoryIds)") + abstract fun getCategoryApps(categoryIds: List): LiveData> + + @Insert + abstract fun addCategoryAppsSync(items: Collection) + + @Insert + abstract fun addCategoryAppSync(item: CategoryApp) + + @Query("DELETE FROM category_app WHERE category_id IN (:categoryIds) AND package_name IN (:packageNames)") + abstract fun removeCategoryAppsSyncByCategoryIds(packageNames: List, categoryIds: List) + + @Query("DELETE FROM category_app WHERE category_id = :categoryId") + abstract fun deleteCategoryAppsByCategoryId(categoryId: String) + + @Query("SELECT * FROM category_app LIMIT :pageSize OFFSET :offset") + abstract fun getCategoryAppPageSync(offset: Int, pageSize: Int): List +} diff --git a/app/src/main/java/io/timelimit/android/data/dao/CategoryDao.kt b/app/src/main/java/io/timelimit/android/data/dao/CategoryDao.kt new file mode 100644 index 0000000..6f51131 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/CategoryDao.kt @@ -0,0 +1,119 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.dao + +import androidx.lifecycle.LiveData +import androidx.room.* +import io.timelimit.android.data.customtypes.ImmutableBitmask +import io.timelimit.android.data.customtypes.ImmutableBitmaskAdapter +import io.timelimit.android.data.model.Category +import io.timelimit.android.livedata.map +import java.util.* + +@Dao +abstract class CategoryDao { + @Query("SELECT * FROM category WHERE child_id = :childId") + abstract fun getCategoriesByChildId(childId: String): LiveData> + + fun getCategoriesByChildIdMappedByCategoryId(childId: String): LiveData> = getCategoriesByChildId(childId).map { + val result = HashMap() + it.forEach { result[it.id] = it } + Collections.unmodifiableMap(result) + } + + @Query("SELECT * FROM category WHERE child_id = :childId AND id = :categoryId") + abstract fun getCategoryByChildIdAndId(childId: String, categoryId: String): LiveData + + @Query("SELECT * FROM category WHERE id = :categoryId") + abstract fun getCategoryByIdSync(categoryId: String): Category? + + @Query("SELECT * FROM category WHERE child_id = :childId") + abstract fun getCategoriesByChildIdSync(childId: String): List + + @Query("DELETE FROM category WHERE id = :categoryId") + abstract fun deleteCategory(categoryId: String) + + @Insert + abstract fun addCategory(category: Category) + + @Query("UPDATE category SET title = :newTitle WHERE id = :categoryId") + abstract fun updateCategoryTitle(categoryId: String, newTitle: String) + + @Query("UPDATE category SET extra_time = :newExtraTime WHERE id = :categoryId") + abstract fun updateCategoryExtraTime(categoryId: String, newExtraTime: Long) + + @Query("UPDATE category SET extra_time = extra_time + :addedExtraTime WHERE id = :categoryId") + abstract fun incrementCategoryExtraTime(categoryId: String, addedExtraTime: Long) + + @Query("UPDATE category SET extra_time = MAX(0, extra_time - :removedExtraTime) WHERE id = :categoryId") + abstract fun subtractCategoryExtraTime(categoryId: String, removedExtraTime: Int) + + @TypeConverters(ImmutableBitmaskAdapter::class) + @Query("UPDATE category SET blocked_times = :blockedMinutesInWeek WHERE id = :categoryId") + abstract fun updateCategoryBlockedTimes(categoryId: String, blockedMinutesInWeek: ImmutableBitmask) + + @Query("UPDATE category SET temporarily_blocked = :blocked WHERE id = :categoryId") + abstract fun updateCategoryTemporarilyBlocked(categoryId: String, blocked: Boolean) + + @Query("SELECT id, base_version, apps_version, rules_version, usedtimes_version FROM category") + abstract fun getCategoriesWithVersionNumbers(): LiveData> + + @Query("UPDATE category SET apps_version = :assignedAppsVersion WHERE id = :categoryId") + abstract fun updateCategoryAssignedAppsVersion(categoryId: String, assignedAppsVersion: String) + + @Query("UPDATE category SET rules_version = :rulesVersion WHERE id = :categoryId") + abstract fun updateCategoryRulesVersion(categoryId: String, rulesVersion: String) + + @Query("UPDATE category SET usedtimes_version = :usedTimesVersion WHERE id = :categoryId") + abstract fun updateCategoryUsedTimesVersion(categoryId: String, usedTimesVersion: String) + + @Update + abstract fun updateCategorySync(category: Category) + + @Query("UPDATE category SET apps_version = \"\", rules_version = \"\", usedtimes_version = \"\", base_version = \"\"") + abstract fun deleteAllCategoriesVersionNumbers() + + @Query("SELECT * FROM category LIMIT :pageSize OFFSET :offset") + abstract fun getCategoryPageSync(offset: Int, pageSize: Int): List + + @Query("SELECT id, child_id, temporarily_blocked FROM category") + abstract fun getAllCategoriesShortInfo(): LiveData> + + @Query("UPDATE category SET parent_category_id = :parentCategoryId WHERE id = :categoryId") + abstract fun updateParentCategory(categoryId: String, parentCategoryId: String) +} + +data class CategoryWithVersionNumbers( + @ColumnInfo(name = "id") + val categoryId: String, + @ColumnInfo(name = "base_version") + val baseVersion: String, + @ColumnInfo(name = "apps_version") + val assignedAppsVersion: String, + @ColumnInfo(name = "rules_version") + val timeLimitRulesVersion: String, + @ColumnInfo(name = "usedtimes_version") + val usedTimeItemsVersion: String +) + +data class CategoryShortInfo( + @ColumnInfo(name = "child_id") + val childId: String, + @ColumnInfo(name = "id") + val categoryId: String, + @ColumnInfo(name = "temporarily_blocked") + val temporarilyBlocked: Boolean +) diff --git a/app/src/main/java/io/timelimit/android/data/dao/ConfigDao.kt b/app/src/main/java/io/timelimit/android/data/dao/ConfigDao.kt new file mode 100644 index 0000000..ce98149 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/ConfigDao.kt @@ -0,0 +1,211 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.dao + +import androidx.lifecycle.LiveData +import androidx.lifecycle.Transformations +import androidx.room.* +import io.timelimit.android.data.model.ConfigurationItem +import io.timelimit.android.data.model.ConfigurationItemType +import io.timelimit.android.data.model.ConfigurationItemTypeConverter +import io.timelimit.android.data.model.ConfigurationItemTypeUtil +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.map + +@Dao +@TypeConverters(ConfigurationItemTypeConverter::class) +abstract class ConfigDao { + @Query("SELECT * FROM config WHERE id IN (:keys)") + protected abstract fun getConfigItemsSync(keys: List): List + + fun getConfigItemsSync() = getConfigItemsSync(ConfigurationItemTypeUtil.TYPES.map { ConfigurationItemTypeUtil.serialize(it) }) + + @Query("SELECT * FROM config WHERE id = :key") + protected abstract fun getRowByKeyAsync(key: ConfigurationItemType): LiveData + + private fun getValueOfKeyAsync(key: ConfigurationItemType): LiveData { + return Transformations.map(getRowByKeyAsync(key)) { it?.value }.ignoreUnchanged() + } + + @Query("SELECT * FROM config WHERE id = :key") + protected abstract fun getRowByKeySync(key: ConfigurationItemType): ConfigurationItem? + + private fun getValueOfKeySync(key: ConfigurationItemType): String? { + return getRowByKeySync(key)?.value + } + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun updateValueOfKeySync(item: ConfigurationItem) + + @Query("DELETE FROM config WHERE id = :key") + protected abstract fun removeConfigItemSync(key: ConfigurationItemType) + + private fun updateValueSync(key: ConfigurationItemType, value: String?) { + if (value != null) { + updateValueOfKeySync(ConfigurationItem(key, value)) + } else { + removeConfigItemSync(key) + } + } + + fun getOwnDeviceId(): LiveData { + return getValueOfKeyAsync(ConfigurationItemType.OwnDeviceId) + } + + fun getOwnDeviceIdSync(): String? { + return getValueOfKeySync(ConfigurationItemType.OwnDeviceId) + } + + fun setOwnDeviceIdSync(deviceId: String) { + updateValueSync(ConfigurationItemType.OwnDeviceId, deviceId) + } + + fun getDeviceListVersion(): LiveData { + return getValueOfKeyAsync(ConfigurationItemType.DeviceListVersion).map { + if (it == null) { + "" + } else { + it + } + } + } + + fun setDeviceListVersionSync(deviceListVersion: String) { + updateValueSync(ConfigurationItemType.DeviceListVersion, deviceListVersion) + } + + fun getUserListVersion(): LiveData { + return getValueOfKeyAsync(ConfigurationItemType.UserListVersion).map { + if (it == null) { + "" + } else { + it + } + } + } + + fun setUserListVersionSync(userListVersion: String) { + updateValueSync(ConfigurationItemType.UserListVersion, userListVersion) + } + + private fun getNextSyncActionSequenceNumberSync(): Long { + val row = getValueOfKeySync(ConfigurationItemType.NextSyncSequenceNumber) + + if (row == null) { + return 0 + } else { + return row.toLong() + } + } + + private fun setNextSyncActionSequenceNumberSync(nextSyncSequenceNumber: Long) { + updateValueSync(ConfigurationItemType.NextSyncSequenceNumber, nextSyncSequenceNumber.toString()) + } + + fun getNextSyncActionSequenceActionAndIncrementIt(): Long { + val current = getNextSyncActionSequenceNumberSync() + setNextSyncActionSequenceNumberSync(current + 1) + + return current + } + + fun getDeviceAuthTokenSync(): String { + val value = getValueOfKeySync(ConfigurationItemType.DeviceAuthToken) + + if (value == null) { + return "" + } else { + return value + } + } + + fun getDeviceAuthTokenAsync(): LiveData = getValueOfKeyAsync(ConfigurationItemType.DeviceAuthToken).map { + if (it == null) { + "" + } else { + it + } + } + + fun setDeviceAuthTokenSync(token: String) { + updateValueSync(ConfigurationItemType.DeviceAuthToken, token) + } + + fun getFullVersionUntilAsync() = getValueOfKeyAsync(ConfigurationItemType.FullVersionUntil).map { + if (it == null || it.isEmpty()) { + 0L + } else { + it.toLong() + } + } + + fun setFullVersionUntilSync(fullVersionUntil: Long) { + updateValueSync(ConfigurationItemType.FullVersionUntil, fullVersionUntil.toString()) + } + + private fun getShownHintsLive(): LiveData { + return getValueOfKeyAsync(ConfigurationItemType.ShownHints).map { + if (it == null) { + 0 + } else { + it.toLong(16) + } + } + } + + private fun getShownHintsSync(): Long { + val v = getValueOfKeySync(ConfigurationItemType.ShownHints) + + if (v == null) { + return 0 + } else { + return v.toLong(16) + } + } + + fun wereHintsShown(flags: Long) = getShownHintsLive().map { + (it and flags) == flags + }.ignoreUnchanged() + + fun wereAnyHintsShown() = getShownHintsLive().map { it != 0L }.ignoreUnchanged() + + fun setHintsShownSync(flags: Long) { + updateValueSync( + ConfigurationItemType.ShownHints, + (getShownHintsSync() or flags).toString(16) + ) + } + + fun resetShownHintsSync() { + updateValueSync(ConfigurationItemType.ShownHints, null) + } + + fun wasDeviceLockedSync() = getValueOfKeySync(ConfigurationItemType.WasDeviceLocked) == "true" + fun setWasDeviceLockedSync(value: Boolean) = updateValueSync(ConfigurationItemType.WasDeviceLocked, if (value) "true" else "false") + + fun getLastAppVersionWhichSynced() = getValueOfKeySync(ConfigurationItemType.LastAppVersionWhichSynced) + fun setLastAppVersionWhichSynced(version: String) = updateValueSync(ConfigurationItemType.LastAppVersionWhichSynced, version) + + fun setLastScreenOnTime(time: Long) = updateValueSync(ConfigurationItemType.LastScreenOnTime, time.toString()) + fun getLastScreenOnTime() = getValueOfKeySync(ConfigurationItemType.LastScreenOnTime)?.toLong() ?: 0L + + fun setServerMessage(message: String?) = updateValueSync(ConfigurationItemType.ServerMessage, message ?: "") + fun getServerMessage() = getValueOfKeyAsync(ConfigurationItemType.ServerMessage).map { if (it.isNullOrBlank()) null else it } + + fun getCustomServerUrlSync() = getValueOfKeySync(ConfigurationItemType.CustomServerUrl) ?: "" + fun getCustomServerUrlAsync() = getValueOfKeyAsync(ConfigurationItemType.CustomServerUrl).map { it ?: "" } + fun setCustomServerUrlSync(url: String) = updateValueSync(ConfigurationItemType.CustomServerUrl, url) +} diff --git a/app/src/main/java/io/timelimit/android/data/dao/DeviceDao.kt b/app/src/main/java/io/timelimit/android/data/dao/DeviceDao.kt new file mode 100644 index 0000000..7410568 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/DeviceDao.kt @@ -0,0 +1,95 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.dao + +import androidx.lifecycle.LiveData +import androidx.room.* +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.NetworkTime +import io.timelimit.android.data.model.NetworkTimeAdapter +import io.timelimit.android.integration.platform.NewPermissionStatusConverter +import io.timelimit.android.integration.platform.ProtectionLevelConverter +import io.timelimit.android.integration.platform.RuntimePermissionStatusConverter + +@Dao +@TypeConverters( + NetworkTimeAdapter::class, + ProtectionLevelConverter::class, + RuntimePermissionStatusConverter::class, + NewPermissionStatusConverter::class +) +abstract class DeviceDao { + @Query("SELECT * FROM device WHERE id = :deviceId") + abstract fun getDeviceById(deviceId: String): LiveData + + @Query("SELECT * FROM device WHERE id = :deviceId") + abstract fun getDeviceByIdSync(deviceId: String): Device? + + @Query("SELECT * FROM device") + abstract fun getAllDevicesLive(): LiveData> + + @Query("SELECT * FROM device") + abstract fun getAllDevicesSync(): List + + @Insert + abstract fun addDeviceSync(device: Device) + + @Query("UPDATE device SET current_user_id = :userId, is_user_kept_signed_in = 0 WHERE id = :deviceId") + abstract fun updateDeviceUser(deviceId: String, userId: String) + + @Query("UPDATE device SET default_user = :defaultUserId, is_user_kept_signed_in = 0 WHERE id = :deviceId") + abstract fun updateDeviceDefaultUser(deviceId: String, defaultUserId: String) + + @Query("SELECT id, apps_version FROM device") + abstract fun getInstalledAppsVersions(): LiveData> + + @Query("DELETE FROM device WHERE id IN (:deviceIds)") + abstract fun removeDevicesById(deviceIds: List) + + @Update + abstract fun updateDeviceEntry(device: Device) + + @Query("UPDATE device SET apps_version = :appsVersion WHERE id = :deviceId") + abstract fun updateAppsVersion(deviceId: String, appsVersion: String) + + @Query("SELECT * FROM device WHERE current_user_id = :userId") + abstract fun getDevicesByUserId(userId: String): LiveData> + + @Query("UPDATE device SET apps_version = \"\"") + abstract fun deleteAllInstalledAppsVersions() + + @Query("UPDATE device SET network_time = :mode WHERE id = :deviceId") + abstract fun updateNetworkTimeVerification(deviceId: String, mode: NetworkTime) + + @Query("UPDATE device SET name = :name WHERE id = :deviceId") + abstract fun updateDeviceName(deviceId: String, name: String): Int + + @Query("SELECT * FROM device LIMIT :pageSize OFFSET :offset") + abstract fun getDevicePageSync(offset: Int, pageSize: Int): List + + @Query("UPDATE device SET current_user_id = \"\", is_user_kept_signed_in = 0 WHERE current_user_id = :userId") + abstract fun unassignCurrentUserFromAllDevices(userId: String) + + @Query("UPDATE device SET is_user_kept_signed_in = :keepSignedIn WHERE id = :deviceId") + abstract fun updateKeepSignedIn(deviceId: String, keepSignedIn: Boolean) +} + +data class DeviceWithAppVersion( + @ColumnInfo(name = "id") + val deviceId: String, + @ColumnInfo(name = "apps_version") + val installedAppsVersions: String +) diff --git a/app/src/main/java/io/timelimit/android/data/dao/PendingSyncActionDao.kt b/app/src/main/java/io/timelimit/android/data/dao/PendingSyncActionDao.kt new file mode 100644 index 0000000..52e5cc2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/PendingSyncActionDao.kt @@ -0,0 +1,62 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.dao + +import androidx.lifecycle.LiveData +import androidx.paging.DataSource +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import io.timelimit.android.data.model.PendingSyncAction + +@Dao +interface PendingSyncActionDao { + @Insert + fun addSyncActionSync(action: PendingSyncAction) + + @Query("DELETE FROM pending_sync_action WHERE sequence_number IN (:sequenceNumbers)") + fun removeSyncActionsBySequenceNumbersSync(sequenceNumbers: List) + + @Query("UPDATE pending_sync_action SET `action` = :action WHERE sequence_number = :sequenceNumber") + fun updateEncodedActionSync(sequenceNumber: Long, action: String) + + @Query("UPDATE pending_sync_action SET scheduled_for_upload = 1 WHERE sequence_number <= :highestSequenceNumberToMark") + fun markSyncActionsAsScheduledForUpload(highestSequenceNumberToMark: Long) + + @Query("SELECT * FROM pending_sync_action WHERE scheduled_for_upload = 0 ORDER BY sequence_number ASC LIMIT :limit") + fun getNextUnscheduledActionsSync(limit: Int): List + + @Query("SELECT * FROM pending_sync_action WHERE scheduled_for_upload = 1 ORDER BY sequence_number ASC LIMIT :limit") + fun getScheduledActionsSync(limit: Int): List + + @Query("SELECT COUNT(*) FROM pending_sync_action WHERE scheduled_for_upload = 1") + fun countScheduledActionsSync(): Long + + @Query("SELECT COUNT(*) FROM pending_sync_action WHERE scheduled_for_upload = 0") + fun countUnscheduledActionsSync(): Long + + @Query("SELECT COUNT(*) FROM pending_sync_action") + fun countAllActionsLive(): LiveData + + @Query("SELECT * FROM pending_sync_action WHERE scheduled_for_upload = 0 ORDER BY sequence_number DESC") + fun getLatestUnscheduledActionSync(): PendingSyncAction? + + @Query("SELECT * FROM pending_sync_action LIMIT :pageSize OFFSET :offset") + fun getPendingSyncActionPageSync(offset: Int, pageSize: Int): List + + @Query("SELECT * FROM pending_sync_action ORDER BY sequence_number ASC") + fun getAllPendingSyncActionsPaged(): DataSource.Factory +} diff --git a/app/src/main/java/io/timelimit/android/data/dao/TemporarilyAllowedAppDao.kt b/app/src/main/java/io/timelimit/android/data/dao/TemporarilyAllowedAppDao.kt new file mode 100644 index 0000000..721e3b4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/TemporarilyAllowedAppDao.kt @@ -0,0 +1,39 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.dao + +import androidx.lifecycle.LiveData +import androidx.lifecycle.Transformations +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import io.timelimit.android.data.model.TemporarilyAllowedApp + +@Dao +abstract class TemporarilyAllowedAppDao { + @Query("SELECT * FROM temporarily_allowed_app WHERE device_id = :deviceId") + abstract fun getTemporarilyAllowedAppsInternal(deviceId: String): LiveData> + + fun getTemporarilyAllowedApps(deviceId: String): LiveData> { + return Transformations.map(getTemporarilyAllowedAppsInternal(deviceId)) { it.map { it.packageName } } + } + + @Insert + abstract fun addTemporarilyAllowedAppSync(app: TemporarilyAllowedApp) + + @Query("DELETE FROM temporarily_allowed_app WHERE device_id = :deviceId") + abstract fun removeAllTemporarilyAllowedAppsSync(deviceId: String) +} diff --git a/app/src/main/java/io/timelimit/android/data/dao/TimeLimitRuleDao.kt b/app/src/main/java/io/timelimit/android/data/dao/TimeLimitRuleDao.kt new file mode 100644 index 0000000..7d821e9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/TimeLimitRuleDao.kt @@ -0,0 +1,59 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.dao + +import androidx.lifecycle.LiveData +import androidx.room.* +import io.timelimit.android.data.model.TimeLimitRule + +@Dao +abstract class TimeLimitRuleDao { + @Query("SELECT * FROM time_limit_rule WHERE category_id = :categoryId") + abstract fun getTimeLimitRulesByCategory(categoryId: String): LiveData> + + @Query("SELECT * FROM time_limit_rule WHERE category_id IN (:categoryIds)") + abstract fun getTimeLimitRulesByCategories(categoryIds: List): LiveData> + + @Query("SELECT * FROM time_limit_rule WHERE category_id = :categoryId") + abstract fun getTimeLimitRulesByCategorySync(categoryId: String): List + + @Query("DELETE FROM time_limit_rule WHERE category_id = :categoryId") + abstract fun deleteTimeLimitRulesByCategory(categoryId: String) + + @Insert + abstract fun addTimeLimitRule(rule: TimeLimitRule) + + @Update + abstract fun updateTimeLimitRule(rule: TimeLimitRule) + + @Delete + abstract fun deleteTimeLimitRule(rule: TimeLimitRule) + + @Query("SELECT * FROM time_limit_rule WHERE id = :timeLimitRuleId") + abstract fun getTimeLimitRuleByIdSync(timeLimitRuleId: String): TimeLimitRule? + + @Query("SELECT * FROM time_limit_rule WHERE id = :timeLimitRuleId") + abstract fun getTimeLimitRuleByIdLive(timeLimitRuleId: String): LiveData + + @Query("DELETE FROM time_limit_rule WHERE id = :timeLimitRuleId") + abstract fun deleteTimeLimitRuleByIdSync(timeLimitRuleId: String) + + @Query("DELETE FROM time_limit_rule WHERE id IN (:timeLimitRuleIds)") + abstract fun deleteTimeLimitRulesByIdsSync(timeLimitRuleIds: List) + + @Query("SELECT * FROM time_limit_rule LIMIT :pageSize OFFSET :offset") + abstract fun getRulePageSync(offset: Int, pageSize: Int): List +} diff --git a/app/src/main/java/io/timelimit/android/data/dao/UsedTimeDao.kt b/app/src/main/java/io/timelimit/android/data/dao/UsedTimeDao.kt new file mode 100644 index 0000000..7681aab --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/UsedTimeDao.kt @@ -0,0 +1,71 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.dao + +import android.util.SparseArray +import androidx.lifecycle.LiveData +import androidx.lifecycle.Transformations +import androidx.paging.DataSource +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import io.timelimit.android.data.model.UsedTimeItem +import io.timelimit.android.livedata.ignoreUnchanged + +@Dao +abstract class UsedTimeDao { + @Query("SELECT * FROM used_time WHERE category_id = :categoryId AND day_of_epoch >= :startingDayOfEpoch AND day_of_epoch <= :endDayOfEpoch") + protected abstract fun getUsedTimesOfWeekInternal(categoryId: String, startingDayOfEpoch: Int, endDayOfEpoch: Int): LiveData> + + fun getUsedTimesOfWeek(categoryId: String, firstDayOfWeekAsEpochDay: Int): LiveData> { + return Transformations.map(getUsedTimesOfWeekInternal(categoryId, firstDayOfWeekAsEpochDay, firstDayOfWeekAsEpochDay + 6).ignoreUnchanged()) { + val result = SparseArray() + + it.forEach { + result.put(it.dayOfEpoch - firstDayOfWeekAsEpochDay, it) + } + + result + } + } + + @Insert + abstract fun insertUsedTime(item: UsedTimeItem) + + @Insert + abstract fun insertUsedTimes(item: List) + + @Query("UPDATE used_time SET used_time = :newUsedTime WHERE category_id = :categoryId AND day_of_epoch = :dayOfEpoch") + abstract fun updateUsedTime(categoryId: String, dayOfEpoch: Int, newUsedTime: Long) + + @Query("UPDATE used_time SET used_time = used_time + :timeToAdd WHERE category_id = :categoryId AND day_of_epoch = :dayOfEpoch") + abstract fun addUsedTime(categoryId: String, dayOfEpoch: Int, timeToAdd: Int): Int + + @Query("SELECT * FROM used_time WHERE category_id = :categoryId AND day_of_epoch = :dayOfEpoch") + abstract fun getUsedTimeItem(categoryId: String, dayOfEpoch: Int): LiveData + + @Query("DELETE FROM used_time WHERE category_id = :categoryId") + abstract fun deleteUsedTimeItems(categoryId: String) + + @Query("SELECT * FROM used_time LIMIT :pageSize OFFSET :offset") + abstract fun getUsedTimePageSync(offset: Int, pageSize: Int): List + + @Query("SELECT * FROM used_time WHERE category_id = :categoryId ORDER BY day_of_epoch DESC") + abstract fun getUsedTimesByCategoryId(categoryId: String): DataSource.Factory + + @Query("SELECT * FROM used_time WHERE category_id IN (:categoryIds) AND day_of_epoch >= :startingDayOfEpoch AND day_of_epoch <= :endDayOfEpoch") + abstract fun getUsedTimesByDayAndCategoryIds(categoryIds: List, startingDayOfEpoch: Int, endDayOfEpoch: Int): LiveData> +} diff --git a/app/src/main/java/io/timelimit/android/data/dao/UserDao.kt b/app/src/main/java/io/timelimit/android/data/dao/UserDao.kt new file mode 100644 index 0000000..c5448af --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/UserDao.kt @@ -0,0 +1,74 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.dao + +import androidx.lifecycle.LiveData +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import androidx.room.Update +import io.timelimit.android.data.model.User + +@Dao +abstract class UserDao { + @Query("SELECT * from user WHERE id = :userId") + abstract fun getUserByIdLive(userId: String): LiveData + + @Query("SELECT * from user WHERE id = :userId AND type = \"child\"") + abstract fun getChildUserByIdLive(userId: String): LiveData + + @Query("SELECT * from user WHERE id = :userId AND type = \"parent\"") + abstract fun getParentUserByIdLive(userId: String): LiveData + + @Query("SELECT * from user WHERE id = :userId") + abstract fun getUserByIdSync(userId: String): User? + + @Insert + abstract fun addUserSync(user: User) + + @Query("SELECT * FROM user") + abstract fun getAllUsersLive(): LiveData> + + @Query("SELECT * FROM user") + abstract fun getAllUsersSync(): List + + @Query("SELECT * FROM user WHERE type = \"parent\"") + abstract fun getParentUsersLive(): LiveData> + + @Query("SELECT * FROM user WHERE type = \"parent\"") + abstract fun getParentUsersSync(): List + + @Query("DELETE FROM user WHERE id IN (:userIds)") + abstract fun deleteUsersByIds(userIds: List) + + @Update + abstract fun updateUserSync(user: User) + + @Query("UPDATE user SET disable_limits_until = :timestamp WHERE id = :childId AND type = \"child\"") + abstract fun updateDisableChildUserLimitsUntil(childId: String, timestamp: Long): Int + + @Query("SELECT * FROM user LIMIT :pageSize OFFSET :offset") + abstract fun getUserPageSync(offset: Int, pageSize: Int): List + + @Query("UPDATE user SET category_for_not_assigned_apps = :categoryId WHERE id = :childId") + abstract fun updateCategoryForUnassignedApps(childId: String, categoryId: String) + + @Query("UPDATE user SET category_for_not_assigned_apps = \"\" WHERE category_for_not_assigned_apps = :categoryId") + abstract fun removeAsCategoryForUnassignedApps(categoryId: String) + + @Query("UPDATE user SET timezone = :timezone WHERE id = :userId") + abstract fun updateUserTimezone(userId: String, timezone: String) +} diff --git a/app/src/main/java/io/timelimit/android/data/extensions/UserDate.kt b/app/src/main/java/io/timelimit/android/data/extensions/UserDate.kt new file mode 100644 index 0000000..cdbb924 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/extensions/UserDate.kt @@ -0,0 +1,32 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.extensions + +import androidx.lifecycle.LiveData +import io.timelimit.android.data.model.User +import io.timelimit.android.date.DateInTimezone +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.liveDataFromFunction +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.RealTimeLogic + +fun LiveData.getDateLive(realTimeLogic: RealTimeLogic) = this.mapToTimezone().switchMap { + timeZone -> + + liveDataFromFunction { + DateInTimezone.newInstance(realTimeLogic.getCurrentTimeInMillis(), timeZone) + } +}.ignoreUnchanged() diff --git a/app/src/main/java/io/timelimit/android/data/extensions/UserTimezone.kt b/app/src/main/java/io/timelimit/android/data/extensions/UserTimezone.kt new file mode 100644 index 0000000..35c5d38 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/extensions/UserTimezone.kt @@ -0,0 +1,32 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.extensions + +import androidx.lifecycle.LiveData +import io.timelimit.android.data.model.User +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.map +import java.util.* + +fun User?.getTimezone(): TimeZone { + return if (this != null) { + TimeZone.getTimeZone(this.timeZone) + } else { + null + } ?: TimeZone.getDefault() +} + +fun LiveData.mapToTimezone() = this.map { it.getTimezone() }.ignoreUnchanged() diff --git a/app/src/main/java/io/timelimit/android/data/model/App.kt b/app/src/main/java/io/timelimit/android/data/model/App.kt new file mode 100644 index 0000000..0c91e74 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/App.kt @@ -0,0 +1,122 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.model + +import android.util.JsonReader +import android.util.JsonWriter +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.TypeConverter +import androidx.room.TypeConverters +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.JsonSerializable + +@Entity(primaryKeys = ["device_id", "package_name"], tableName = "app") +@TypeConverters(AppRecommendationConverter::class) +data class App ( + @ColumnInfo(index = true, name = "device_id") + val deviceId: String, + @ColumnInfo(index = true, name = "package_name") + val packageName: String, + @ColumnInfo(name = "title") + val title: String, + @ColumnInfo(name = "launchable") + val isLaunchable: Boolean, + @ColumnInfo(name = "recommendation") + val recommendation: AppRecommendation +): JsonSerializable { + companion object { + private const val DEVICE_ID = "d" + private const val PACKAGE_NAME = "p" + private const val TITLE = "t" + private const val IS_LAUNCHABLE = "l" + private const val RECOMMENDATION = "r" + + fun parse(reader: JsonReader): App { + var deviceId: String? = null + var packageName: String? = null + var title: String? = null + var isLaunchable: Boolean? = null + var recommendation: AppRecommendation? = null + + reader.beginObject() + + while (reader.hasNext()) { + when (reader.nextName()) { + DEVICE_ID -> deviceId = reader.nextString() + PACKAGE_NAME -> packageName = reader.nextString() + TITLE -> title = reader.nextString() + IS_LAUNCHABLE -> isLaunchable = reader.nextBoolean() + RECOMMENDATION -> recommendation = AppRecommendationJson.parse(reader.nextString()) + else -> reader.skipValue() + } + } + + reader.endObject() + + return App( + deviceId = deviceId!!, + packageName = packageName!!, + title = title!!, + isLaunchable = isLaunchable!!, + recommendation = recommendation!! + ) + } + } + + init { + IdGenerator.assertIdValid(deviceId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(DEVICE_ID).value(deviceId) + writer.name(PACKAGE_NAME).value(packageName) + writer.name(TITLE).value(title) + writer.name(IS_LAUNCHABLE).value(isLaunchable) + writer.name(RECOMMENDATION).value(AppRecommendationJson.serialize(recommendation)) + + writer.endObject() + } +} + +enum class AppRecommendation { + None, Whitelist, Blacklist +} + +class AppRecommendationConverter { + @TypeConverter + fun toAppRecommendation(value: String) = AppRecommendationJson.parse(value) + + @TypeConverter + fun toString(value: AppRecommendation) = AppRecommendationJson.serialize(value) +} + +object AppRecommendationJson { + fun parse(value: String) = when(value) { + "whitelist" -> AppRecommendation.Whitelist + "blacklist" -> AppRecommendation.Blacklist + "none" -> AppRecommendation.None + else -> throw IllegalArgumentException() + } + + fun serialize(value: AppRecommendation) = when(value) { + AppRecommendation.None -> "none" + AppRecommendation.Blacklist -> "blacklist" + AppRecommendation.Whitelist -> "whitelist" + } +} diff --git a/app/src/main/java/io/timelimit/android/data/model/Category.kt b/app/src/main/java/io/timelimit/android/data/model/Category.kt new file mode 100644 index 0000000..6f868ec --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/Category.kt @@ -0,0 +1,154 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.model + +import android.util.JsonReader +import android.util.JsonWriter +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey +import androidx.room.TypeConverters +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.JsonSerializable +import io.timelimit.android.data.customtypes.ImmutableBitmask +import io.timelimit.android.data.customtypes.ImmutableBitmaskAdapter +import io.timelimit.android.data.customtypes.ImmutableBitmaskJson + +@Entity(tableName = "category") +@TypeConverters(ImmutableBitmaskAdapter::class) +data class Category( + @PrimaryKey + @ColumnInfo(name = "id") + val id: String, + @ColumnInfo(name = "child_id") + val childId: String, + @ColumnInfo(name = "title") + val title: String, + @ColumnInfo(name = "blocked_times") + val blockedMinutesInWeek: ImmutableBitmask, // 10080 bit -> ~10 KB + @ColumnInfo(name = "extra_time") + val extraTimeInMillis: Long, + @ColumnInfo(name = "temporarily_blocked") + val temporarilyBlocked: Boolean, + @ColumnInfo(name = "base_version") + val baseVersion: String, + @ColumnInfo(name = "apps_version") + val assignedAppsVersion: String, + @ColumnInfo(name = "rules_version") + val timeLimitRulesVersion: String, + @ColumnInfo(name = "usedtimes_version") + val usedTimesVersion: String, + @ColumnInfo(name = "parent_category_id") + val parentCategoryId: String +): JsonSerializable { + companion object { + const val MINUTES_PER_DAY = 60 * 24 + const val BLOCKED_MINUTES_IN_WEEK_LENGTH = MINUTES_PER_DAY * 7 + + private const val ID = "id" + private const val CHILD_ID = "cid" + private const val TITLE = "T" + private const val BLOCKED_MINUTES_IN_WEEK = "b" + private const val EXTRA_TIME_IN_MILLIS = "et" + private const val TEMPORARILY_BLOCKED = "tb" + private const val BASE_VERSION = "vb" + private const val ASSIGNED_APPS_VERSION = "va" + private const val RULES_VERSION = "vr" + private const val USED_TIMES_VERSION = "vu" + private const val PARENT_CATEGORY_ID = "pc" + + fun parse(reader: JsonReader): Category { + var id: String? = null + var childId: String? = null + var title: String? = null + var blockedMinutesInWeek: ImmutableBitmask? = null + var extraTimeInMillis: Long? = null + var temporarilyBlocked: Boolean? = null + var baseVersion: String? = null + var assignedAppsVersion: String? = null + var timeLimitRulesVersion: String? = null + var usedTimesVersion: String? = null + // this field was added later so it has got a default value + var parentCategoryId = "" + + reader.beginObject() + + while (reader.hasNext()) { + when (reader.nextName()) { + ID -> id = reader.nextString() + CHILD_ID -> childId = reader.nextString() + TITLE -> title = reader.nextString() + BLOCKED_MINUTES_IN_WEEK -> blockedMinutesInWeek = ImmutableBitmaskJson.parse(reader.nextString(), BLOCKED_MINUTES_IN_WEEK_LENGTH) + EXTRA_TIME_IN_MILLIS -> extraTimeInMillis = reader.nextLong() + TEMPORARILY_BLOCKED -> temporarilyBlocked = reader.nextBoolean() + BASE_VERSION -> baseVersion = reader.nextString() + ASSIGNED_APPS_VERSION -> assignedAppsVersion = reader.nextString() + RULES_VERSION -> timeLimitRulesVersion = reader.nextString() + USED_TIMES_VERSION -> usedTimesVersion = reader.nextString() + PARENT_CATEGORY_ID -> parentCategoryId = reader.nextString() + else -> reader.skipValue() + } + } + + reader.endObject() + + return Category( + id = id!!, + childId = childId!!, + title = title!!, + blockedMinutesInWeek = blockedMinutesInWeek!!, + extraTimeInMillis = extraTimeInMillis!!, + temporarilyBlocked = temporarilyBlocked!!, + baseVersion = baseVersion!!, + assignedAppsVersion = assignedAppsVersion!!, + timeLimitRulesVersion = timeLimitRulesVersion!!, + usedTimesVersion = usedTimesVersion!!, + parentCategoryId = parentCategoryId + ) + } + } + + init { + IdGenerator.assertIdValid(id) + IdGenerator.assertIdValid(childId) + + if (extraTimeInMillis < 0) { + throw IllegalStateException() + } + + if (title.isEmpty()) { + throw IllegalArgumentException() + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(ID).value(id) + writer.name(CHILD_ID).value(childId) + writer.name(TITLE).value(title) + writer.name(BLOCKED_MINUTES_IN_WEEK).value(ImmutableBitmaskJson.serialize(blockedMinutesInWeek)) + writer.name(EXTRA_TIME_IN_MILLIS).value(extraTimeInMillis) + writer.name(TEMPORARILY_BLOCKED).value(temporarilyBlocked) + writer.name(BASE_VERSION).value(baseVersion) + writer.name(ASSIGNED_APPS_VERSION).value(assignedAppsVersion) + writer.name(RULES_VERSION).value(timeLimitRulesVersion) + writer.name(USED_TIMES_VERSION).value(usedTimesVersion) + writer.name(PARENT_CATEGORY_ID).value(parentCategoryId) + + writer.endObject() + } +} diff --git a/app/src/main/java/io/timelimit/android/data/model/CategoryApp.kt b/app/src/main/java/io/timelimit/android/data/model/CategoryApp.kt new file mode 100644 index 0000000..ef0f783 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/CategoryApp.kt @@ -0,0 +1,75 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.model + +import android.util.JsonReader +import android.util.JsonWriter +import androidx.room.ColumnInfo +import androidx.room.Entity +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.JsonSerializable + +@Entity(primaryKeys = ["category_id", "package_name"], tableName = "category_app") +data class CategoryApp( + @ColumnInfo(index = true, name = "category_id") + val categoryId: String, + @ColumnInfo(index = true, name = "package_name") + val packageName: String +): JsonSerializable { + companion object { + private const val CATEGORY_ID = "c" + private const val PACKAGE_NAME = "p" + + fun parse(reader: JsonReader): CategoryApp { + var categoryId: String? = null + var packageName: String? = null + + reader.beginObject() + + while (reader.hasNext()) { + when (reader.nextName()) { + CATEGORY_ID -> categoryId = reader.nextString() + PACKAGE_NAME -> packageName = reader.nextString() + else -> reader.skipValue() + } + } + + reader.endObject() + + return CategoryApp( + categoryId = categoryId!!, + packageName = packageName!! + ) + } + } + + init { + IdGenerator.assertIdValid(categoryId) + + if (packageName.isEmpty()) { + throw IllegalArgumentException() + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(CATEGORY_ID).value(categoryId) + writer.name(PACKAGE_NAME).value(packageName) + + writer.endObject() + } +} diff --git a/app/src/main/java/io/timelimit/android/data/model/ConfigurationItem.kt b/app/src/main/java/io/timelimit/android/data/model/ConfigurationItem.kt new file mode 100644 index 0000000..fa505f8 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/ConfigurationItem.kt @@ -0,0 +1,168 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.model + +import android.util.JsonReader +import android.util.JsonWriter +import androidx.room.* +import io.timelimit.android.data.JsonSerializable + +@Entity(tableName = "config") +@TypeConverters(ConfigurationItemTypeConverter::class) +data class ConfigurationItem( + @PrimaryKey + @ColumnInfo(name = "id") + val key: ConfigurationItemType, + @ColumnInfo(name = "value") + val value: String +): JsonSerializable { + companion object { + private const val KEY = "k" + private const val VALUE = "v" + + // returns null if parsing failed + fun parse(reader: JsonReader): ConfigurationItem? { + var key: Int? = null + var value: String? = null + + reader.beginObject() + + while (reader.hasNext()) { + when (reader.nextName()) { + KEY -> key = reader.nextInt() + VALUE -> value = reader.nextString() + else -> reader.skipValue() + } + } + + reader.endObject() + + key!! + value!! + + try { + return ConfigurationItem( + key = ConfigurationItemTypeUtil.parse(key), + value = value + ) + } catch (ex: Exception) { + return null + } + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(KEY).value(ConfigurationItemTypeUtil.serialize(key)) + writer.name(VALUE).value(value) + + writer.endObject() + } +} + +// TODO: validate config item values + +enum class ConfigurationItemType { + OwnDeviceId, + UserListVersion, + DeviceListVersion, + NextSyncSequenceNumber, + DeviceAuthToken, + FullVersionUntil, + ShownHints, + WasDeviceLocked, + LastAppVersionWhichSynced, + LastScreenOnTime, + ServerMessage, + CustomServerUrl +} + +object ConfigurationItemTypeUtil { + private const val OWN_DEVICE_ID = 1 + private const val USER_LIST_VERSION = 2 + private const val DEVICE_LIST_VERSION = 3 + private const val NEXT_SYNC_SEQUENCE_NUMBER = 4 + private const val DEVICE_AUTH_TOKEN = 5 + private const val FULL_VERSION_UNTIL = 6 + private const val SHOWN_HINTS = 7 + private const val WAS_DEVICE_LOCKED = 9 + private const val LAST_APP_VERSION_WHICH_SYNCED = 10 + private const val LAST_SCREEN_ON_TIME = 11 + private const val SERVER_MESSAGE = 12 + private const val CUSTOM_SERVER_URL = 13 + + val TYPES = listOf( + ConfigurationItemType.OwnDeviceId, + ConfigurationItemType.UserListVersion, + ConfigurationItemType.DeviceListVersion, + ConfigurationItemType.NextSyncSequenceNumber, + ConfigurationItemType.DeviceAuthToken, + ConfigurationItemType.FullVersionUntil, + ConfigurationItemType.ShownHints, + ConfigurationItemType.WasDeviceLocked, + ConfigurationItemType.LastAppVersionWhichSynced, + ConfigurationItemType.LastScreenOnTime, + ConfigurationItemType.ServerMessage, + ConfigurationItemType.CustomServerUrl + ) + + fun serialize(value: ConfigurationItemType) = when(value) { + ConfigurationItemType.OwnDeviceId -> OWN_DEVICE_ID + ConfigurationItemType.UserListVersion -> USER_LIST_VERSION + ConfigurationItemType.DeviceListVersion -> DEVICE_LIST_VERSION + ConfigurationItemType.NextSyncSequenceNumber -> NEXT_SYNC_SEQUENCE_NUMBER + ConfigurationItemType.DeviceAuthToken -> DEVICE_AUTH_TOKEN + ConfigurationItemType.FullVersionUntil -> FULL_VERSION_UNTIL + ConfigurationItemType.ShownHints -> SHOWN_HINTS + ConfigurationItemType.WasDeviceLocked -> WAS_DEVICE_LOCKED + ConfigurationItemType.LastAppVersionWhichSynced -> LAST_APP_VERSION_WHICH_SYNCED + ConfigurationItemType.LastScreenOnTime -> LAST_SCREEN_ON_TIME + ConfigurationItemType.ServerMessage -> SERVER_MESSAGE + ConfigurationItemType.CustomServerUrl -> CUSTOM_SERVER_URL + } + + fun parse(value: Int) = when(value) { + OWN_DEVICE_ID -> ConfigurationItemType.OwnDeviceId + USER_LIST_VERSION -> ConfigurationItemType.UserListVersion + DEVICE_LIST_VERSION -> ConfigurationItemType.DeviceListVersion + NEXT_SYNC_SEQUENCE_NUMBER -> ConfigurationItemType.NextSyncSequenceNumber + DEVICE_AUTH_TOKEN -> ConfigurationItemType.DeviceAuthToken + FULL_VERSION_UNTIL -> ConfigurationItemType.FullVersionUntil + SHOWN_HINTS -> ConfigurationItemType.ShownHints + WAS_DEVICE_LOCKED -> ConfigurationItemType.WasDeviceLocked + LAST_APP_VERSION_WHICH_SYNCED -> ConfigurationItemType.LastAppVersionWhichSynced + LAST_SCREEN_ON_TIME -> ConfigurationItemType.LastScreenOnTime + SERVER_MESSAGE -> ConfigurationItemType.ServerMessage + CUSTOM_SERVER_URL -> ConfigurationItemType.CustomServerUrl + else -> throw IllegalArgumentException() + } +} + +class ConfigurationItemTypeConverter { + @TypeConverter + fun toInt(value: ConfigurationItemType) = ConfigurationItemTypeUtil.serialize(value) + + @TypeConverter + fun toConfigurationItemType(value: Int) = ConfigurationItemTypeUtil.parse(value) +} + +object HintsToShow { + const val OVERVIEW_INTRODUCTION = 1L + const val DEVICE_SCREEN_INTRODUCTION = 2L + const val CATEGORIES_INTRODUCTION = 4L + const val TIME_LIMIT_RULE_INTRODUCTION = 8L +} diff --git a/app/src/main/java/io/timelimit/android/data/model/Device.kt b/app/src/main/java/io/timelimit/android/data/model/Device.kt new file mode 100644 index 0000000..f772894 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/Device.kt @@ -0,0 +1,311 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.model + +import android.util.JsonReader +import android.util.JsonWriter +import androidx.room.* +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.JsonSerializable +import io.timelimit.android.integration.platform.* + +@Entity(tableName = "device") +@TypeConverters( + NetworkTimeAdapter::class, + ProtectionLevelConverter::class, + RuntimePermissionStatusConverter::class, + NewPermissionStatusConverter::class +) +data class Device( + @PrimaryKey + @ColumnInfo(name = "id") + val id: String, + @ColumnInfo(name = "name") + val name: String, + @ColumnInfo(name = "model") + val model: String, + @ColumnInfo(name = "added_at") + val addedAt: Long, + @ColumnInfo(name = "current_user_id") + val currentUserId: String, // empty if not set + @ColumnInfo(name = "apps_version") + val installedAppsVersion: String, + @ColumnInfo(name = "network_time") + val networkTime: NetworkTime, + @ColumnInfo(name = "current_protection_level") + val currentProtectionLevel: ProtectionLevel, + @ColumnInfo(name = "highest_permission_level") + val highestProtectionLevel: ProtectionLevel, + @ColumnInfo(name = "current_usage_stats_permission") + val currentUsageStatsPermission: RuntimePermissionStatus, + @ColumnInfo(name = "highest_usage_stats_permission") + val highestUsageStatsPermission: RuntimePermissionStatus, + @ColumnInfo(name = "current_notification_access_permission") + val currentNotificationAccessPermission: NewPermissionStatus, + @ColumnInfo(name = "highest_notification_access_permission") + val highestNotificationAccessPermission: NewPermissionStatus, + @ColumnInfo(name = "current_app_version") + val currentAppVersion: Int, + @ColumnInfo(name = "highest_app_version") + val highestAppVersion: Int, + @ColumnInfo(name = "tried_disabling_device_admin") + val manipulationTriedDisablingDeviceAdmin: Boolean, + @ColumnInfo(name = "did_reboot") + val manipulationDidReboot: Boolean, + @ColumnInfo(name = "had_manipulation") + val hadManipulation: Boolean, + @ColumnInfo(name = "did_report_uninstall") + val didReportUninstall: Boolean, + @ColumnInfo(name = "is_user_kept_signed_in") + val isUserKeptSignedIn: Boolean, + @ColumnInfo(name = "show_device_connected") + val showDeviceConnected: Boolean, + @ColumnInfo(name = "default_user") + val defaultUser: String, + @ColumnInfo(name = "default_user_timeout") + val defaultUserTimeout: Int, + @ColumnInfo(name = "consider_reboot_manipulation") + val considerRebootManipulation: Boolean +): JsonSerializable { + companion object { + private const val ID = "id" + private const val NAME = "n" + private const val MODEL = "m" + private const val ADDED_AT = "aa" + private const val CURRENT_USER_ID = "u" + private const val INSTALLED_APPS_VERSION = "va" + private const val NETWORK_TIME = "t" + private const val CURRENT_PROTECTION_LEVEL = "pc" + private const val HIGHEST_PROTECTION_LEVEL = "pm" + private const val CURRENT_USAGE_STATS_PERMISSION = "uc" + private const val HIGHEST_USAGE_STATS_PERMISSION = "um" + private const val CURRENT_NOTIFICATION_ACCESS_PERMISSION = "nc" + private const val HIGHEST_NOTIFICATION_ACCESS_PERMISSION = "nm" + private const val CURRENT_APP_VERSION = "ac" + private const val HIGHEST_APP_VERSION = "am" + private const val TRIED_DISABLING_DEVICE_ADMIN = "tdda" + private const val MANIPULATION_DID_REBOOT = "mdr" + private const val HAD_MANIPULATION = "hm" + private const val DID_REPORT_UNINSTALL = "dru" + private const val IS_USER_KEPT_SIGNED_IN = "iuksi" + private const val SHOW_DEVICE_CONNECTED = "sdc" + private const val DEFAULT_USER = "du" + private const val DEFAULT_USER_TIMEOUT = "dut" + private const val CONSIDER_REBOOT_A_MANIPULATION = "cram" + + fun parse(reader: JsonReader): Device { + var id: String? = null + var name: String? = null + var model: String? = null + var addedAt: Long? = null + var currentUserId: String? = null + var installedAppsVersion: String? = null + var networkTime: NetworkTime? = null + var currentProtectionLevel: ProtectionLevel? = null + var highestProtectionLevel: ProtectionLevel? = null + var currentUsageStatsPermission: RuntimePermissionStatus? = null + var highestUsageStatsPermission: RuntimePermissionStatus? = null + var currentNotificationAccessPermission: NewPermissionStatus? = null + var highestNotificationAccessPermission: NewPermissionStatus? = null + var currentAppVersion: Int? = null + var highestAppVersion: Int? = null + var manipulationTriedDisablingDeviceAdmin: Boolean? = null + var manipulationDidReboot: Boolean = false + var hadManipulation: Boolean? = null + var didReportUninstall = false // this was added later, so it has got a default value + var isUserKeptSignedIn = false + var showDeviceConnected = false + var defaultUser = "" + var defaultUserTimeout = 0 + var considerRebootManipulation = false + + reader.beginObject() + + while (reader.hasNext()) { + when (reader.nextName()) { + ID -> id = reader.nextString() + NAME -> name = reader.nextString() + MODEL -> model = reader.nextString() + ADDED_AT -> addedAt = reader.nextLong() + CURRENT_USER_ID -> currentUserId = reader.nextString() + INSTALLED_APPS_VERSION -> installedAppsVersion = reader.nextString() + NETWORK_TIME -> networkTime = NetworkTimeJson.parse(reader.nextString()) + CURRENT_PROTECTION_LEVEL -> currentProtectionLevel = ProtectionLevelUtil.parse(reader.nextString()) + HIGHEST_PROTECTION_LEVEL -> highestProtectionLevel = ProtectionLevelUtil.parse(reader.nextString()) + CURRENT_USAGE_STATS_PERMISSION -> currentUsageStatsPermission = RuntimePermissionStatusUtil.parse(reader.nextString()) + HIGHEST_USAGE_STATS_PERMISSION -> highestUsageStatsPermission = RuntimePermissionStatusUtil.parse(reader.nextString()) + CURRENT_NOTIFICATION_ACCESS_PERMISSION -> currentNotificationAccessPermission = NewPermissionStatusUtil.parse(reader.nextString()) + HIGHEST_NOTIFICATION_ACCESS_PERMISSION -> highestNotificationAccessPermission = NewPermissionStatusUtil.parse(reader.nextString()) + CURRENT_APP_VERSION -> currentAppVersion = reader.nextInt() + HIGHEST_APP_VERSION -> highestAppVersion = reader.nextInt() + TRIED_DISABLING_DEVICE_ADMIN -> manipulationTriedDisablingDeviceAdmin = reader.nextBoolean() + MANIPULATION_DID_REBOOT -> manipulationDidReboot = reader.nextBoolean() + HAD_MANIPULATION -> hadManipulation = reader.nextBoolean() + DID_REPORT_UNINSTALL -> didReportUninstall = reader.nextBoolean() + IS_USER_KEPT_SIGNED_IN -> isUserKeptSignedIn = reader.nextBoolean() + SHOW_DEVICE_CONNECTED -> showDeviceConnected = reader.nextBoolean() + DEFAULT_USER -> defaultUser = reader.nextString() + DEFAULT_USER_TIMEOUT -> defaultUserTimeout = reader.nextInt() + CONSIDER_REBOOT_A_MANIPULATION -> considerRebootManipulation = reader.nextBoolean() + else -> reader.skipValue() + } + } + + reader.endObject() + + return Device( + id = id!!, + name = name!!, + model = model!!, + addedAt = addedAt!!, + currentUserId = currentUserId!!, + installedAppsVersion = installedAppsVersion!!, + networkTime = networkTime!!, + currentProtectionLevel = currentProtectionLevel!!, + highestProtectionLevel = highestProtectionLevel!!, + currentUsageStatsPermission = currentUsageStatsPermission!!, + highestUsageStatsPermission = highestUsageStatsPermission!!, + currentNotificationAccessPermission = currentNotificationAccessPermission!!, + highestNotificationAccessPermission = highestNotificationAccessPermission!!, + currentAppVersion = currentAppVersion!!, + highestAppVersion = highestAppVersion!!, + manipulationTriedDisablingDeviceAdmin = manipulationTriedDisablingDeviceAdmin!!, + manipulationDidReboot = manipulationDidReboot, + hadManipulation = hadManipulation!!, + didReportUninstall = didReportUninstall, + isUserKeptSignedIn = isUserKeptSignedIn, + showDeviceConnected = showDeviceConnected, + defaultUser = defaultUser, + defaultUserTimeout = defaultUserTimeout, + considerRebootManipulation = considerRebootManipulation + ) + } + } + + init { + IdGenerator.assertIdValid(id) + + if (currentUserId.isNotEmpty()) { + IdGenerator.assertIdValid(currentUserId) + } + + if (name.isEmpty()) { + throw IllegalArgumentException() + } + + if (model.isEmpty()) { + throw IllegalArgumentException() + } + + if (addedAt < 0) { + throw IllegalArgumentException() + } + + if (currentAppVersion < 0 || highestAppVersion < 0) { + throw IllegalArgumentException() + } + + if (defaultUser.isNotEmpty()) { + IdGenerator.assertIdValid(defaultUser) + } + + if (defaultUserTimeout < 0) { + throw IllegalArgumentException() + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(ID).value(id) + writer.name(NAME).value(name) + writer.name(MODEL).value(model) + writer.name(ADDED_AT).value(addedAt) + writer.name(CURRENT_USER_ID).value(currentUserId) + writer.name(INSTALLED_APPS_VERSION).value(installedAppsVersion) + writer.name(NETWORK_TIME).value(NetworkTimeJson.serialize(networkTime)) + writer.name(CURRENT_PROTECTION_LEVEL).value(ProtectionLevelUtil.serialize(currentProtectionLevel)) + writer.name(HIGHEST_PROTECTION_LEVEL).value(ProtectionLevelUtil.serialize(highestProtectionLevel)) + writer.name(CURRENT_USAGE_STATS_PERMISSION).value(RuntimePermissionStatusUtil.serialize(currentUsageStatsPermission)) + writer.name(HIGHEST_USAGE_STATS_PERMISSION).value(RuntimePermissionStatusUtil.serialize(highestUsageStatsPermission)) + writer.name(CURRENT_NOTIFICATION_ACCESS_PERMISSION).value(NewPermissionStatusUtil.serialize(currentNotificationAccessPermission)) + writer.name(HIGHEST_NOTIFICATION_ACCESS_PERMISSION).value(NewPermissionStatusUtil.serialize(highestNotificationAccessPermission)) + writer.name(CURRENT_APP_VERSION).value(currentAppVersion) + writer.name(HIGHEST_APP_VERSION).value(highestAppVersion) + writer.name(TRIED_DISABLING_DEVICE_ADMIN).value(manipulationTriedDisablingDeviceAdmin) + writer.name(MANIPULATION_DID_REBOOT).value(manipulationDidReboot) + writer.name(HAD_MANIPULATION).value(hadManipulation) + writer.name(DID_REPORT_UNINSTALL).value(didReportUninstall) + writer.name(IS_USER_KEPT_SIGNED_IN).value(isUserKeptSignedIn) + writer.name(SHOW_DEVICE_CONNECTED).value(showDeviceConnected) + writer.name(DEFAULT_USER).value(defaultUser) + writer.name(DEFAULT_USER_TIMEOUT).value(defaultUserTimeout) + writer.name(CONSIDER_REBOOT_A_MANIPULATION).value(considerRebootManipulation) + + writer.endObject() + } + + @Transient + val manipulationOfProtectionLevel = currentProtectionLevel != highestProtectionLevel + @Transient + val manipulationOfUsageStats = currentUsageStatsPermission != highestUsageStatsPermission + @Transient + val manipulationOfNotificationAccess = currentNotificationAccessPermission != highestNotificationAccessPermission + @Transient + val manipulationOfAppVersion = currentAppVersion != highestAppVersion + + @Transient + val hasActiveManipulationWarning = manipulationOfProtectionLevel || + manipulationOfUsageStats || + manipulationOfNotificationAccess || + manipulationOfAppVersion || + manipulationTriedDisablingDeviceAdmin || + manipulationDidReboot + + @Transient + val hasAnyManipulation = hasActiveManipulationWarning || hadManipulation +} + +enum class NetworkTime { + Disabled, IfPossible, Enabled +} + +object NetworkTimeJson { + private const val DISABLED = "disabled" + private const val IF_POSSIBLE = "if possible" + private const val ENABLED = "enabled" + + fun parse(value: String) = when(value) { + DISABLED -> NetworkTime.Disabled + IF_POSSIBLE -> NetworkTime.IfPossible + ENABLED -> NetworkTime.Enabled + else -> throw IllegalArgumentException() + } + + fun serialize(value: NetworkTime) = when(value) { + NetworkTime.Disabled -> DISABLED + NetworkTime.IfPossible -> IF_POSSIBLE + NetworkTime.Enabled -> ENABLED + } +} + +class NetworkTimeAdapter { + @TypeConverter + fun toString(networkTime: NetworkTime) = NetworkTimeJson.serialize(networkTime) + + @TypeConverter + fun toNetworkTime(value: String) = NetworkTimeJson.parse(value) +} diff --git a/app/src/main/java/io/timelimit/android/data/model/PendingSyncAction.kt b/app/src/main/java/io/timelimit/android/data/model/PendingSyncAction.kt new file mode 100644 index 0000000..32e5695 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/PendingSyncAction.kt @@ -0,0 +1,160 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.model + +import android.util.JsonReader +import android.util.JsonWriter +import androidx.room.* +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.JsonSerializable + +/* + * parent and child actions must be signed + * This happens with the following: + * 1. The passwords for parents are stored 2 times + * 1. encrypted with bcrypt + * 2. encrypted with bcrypt, but the clients only keep the salt, only the server stores the full hash + * 2. The full hash of the second sample (KEY) is used as a base for signing + * 3. The integrity data is SHA512asHexString(sequenceNumber.toString() + deviceId + encodedAction + KEY).substring(0, 32) + * + * The integrity for child actions is empty + */ + +@Entity(tableName = "pending_sync_action") +@TypeConverters(PendingSyncActionAdapter::class) +data class PendingSyncAction( + @ColumnInfo(name = "sequence_number") + @PrimaryKey + val sequenceNumber: Long, + @ColumnInfo(name = "action") + val encodedAction: String, + @ColumnInfo(name = "integrity") + val integrity: String, + @ColumnInfo(name = "scheduled_for_upload", index = true) + // actions can be modified/ merged if they were not yet scheduled for an upload + // this merging is made by the upload function + val scheduledForUpload: Boolean, + @ColumnInfo(name = "type") + val type: PendingSyncActionType, + @ColumnInfo(name = "user_id") + val userId: String +): JsonSerializable { + companion object { + private const val SEQUENCE_NUMBER = "n" + private const val ENCODED_ACTION = "a" + private const val INTEGRITY = "i" + private const val SCHEDULED_FOR_UPLOAD = "s" + private const val TYPE = "t" + private const val TYPE_NEW = "t2" + private const val USER_ID = "u" + + fun parse(reader: JsonReader): PendingSyncAction { + var sequenceNumber: Long? = null + var encodedAction: String? = null + var integrity: String? = null + var scheduledForUpload: Boolean? = null + var type: PendingSyncActionType? = null + var typeNew: PendingSyncActionType? = null + var userId: String? = null + + reader.beginObject() + + while (reader.hasNext()) { + when (reader.nextName()) { + SEQUENCE_NUMBER -> sequenceNumber = reader.nextLong() + ENCODED_ACTION -> encodedAction = reader.nextString() + INTEGRITY -> integrity = reader.nextString() + SCHEDULED_FOR_UPLOAD -> scheduledForUpload = reader.nextBoolean() + TYPE -> type = PendingSyncActionTypeConverter.parse(reader.nextString()) + TYPE_NEW -> typeNew = PendingSyncActionTypeConverter.parse(reader.nextString()) + USER_ID -> userId = reader.nextString() + else -> reader.skipValue() + } + } + + reader.endObject() + + return PendingSyncAction( + sequenceNumber = sequenceNumber!!, + encodedAction = encodedAction!!, + integrity = integrity!!, + scheduledForUpload = scheduledForUpload!!, + type = (typeNew ?: type)!!, + userId = userId!! + ) + } + } + + init { + if (userId.isNotEmpty()) { + IdGenerator.assertIdValid(userId) + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(SEQUENCE_NUMBER).value(sequenceNumber) + writer.name(ENCODED_ACTION).value(encodedAction) + writer.name(INTEGRITY).value(integrity) + writer.name(SCHEDULED_FOR_UPLOAD).value(scheduledForUpload) + writer.name(TYPE).value( + PendingSyncActionTypeConverter.serialize( + if (type != PendingSyncActionType.Child) { + type + } else { + // this will make the actions fail, but prevents a crash after downgrades + PendingSyncActionType.Parent + } + ) + ) + writer.name(TYPE_NEW).value(PendingSyncActionTypeConverter.serialize(type)) + writer.name(USER_ID).value(userId) + + writer.endObject() + } +} + +enum class PendingSyncActionType { + Parent, AppLogic, Child +} + +object PendingSyncActionTypeConverter { + private const val APP_LOGIC = "appLogic" + private const val PARENT = "parent" + private const val CHILD = "child" + + fun serialize(type: PendingSyncActionType) = when(type) { + PendingSyncActionType.Parent -> PARENT + PendingSyncActionType.AppLogic -> APP_LOGIC + PendingSyncActionType.Child -> CHILD + } + + fun parse(value: String) = when(value) { + PARENT -> PendingSyncActionType.Parent + APP_LOGIC -> PendingSyncActionType.AppLogic + CHILD -> PendingSyncActionType.Child + else -> throw IllegalStateException() + } +} + +class PendingSyncActionAdapter { + @TypeConverter + fun toString(value: PendingSyncActionType) = PendingSyncActionTypeConverter.serialize(value) + + @TypeConverter + fun toPendingSyncActionType(value: String) = PendingSyncActionTypeConverter.parse(value) +} diff --git a/app/src/main/java/io/timelimit/android/data/model/TemporarilyAllowedApp.kt b/app/src/main/java/io/timelimit/android/data/model/TemporarilyAllowedApp.kt new file mode 100644 index 0000000..1277b45 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/TemporarilyAllowedApp.kt @@ -0,0 +1,32 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.model + +import androidx.room.ColumnInfo +import androidx.room.Entity +import io.timelimit.android.data.IdGenerator + +@Entity(tableName = "temporarily_allowed_app", primaryKeys = ["device_id", "package_name"]) +data class TemporarilyAllowedApp( + @ColumnInfo(name = "device_id") + val deviceId: String, + @ColumnInfo(name = "package_name") + val packageName: String +) { + init { + IdGenerator.assertIdValid(deviceId) + } +} diff --git a/app/src/main/java/io/timelimit/android/data/model/TimeLimitRule.kt b/app/src/main/java/io/timelimit/android/data/model/TimeLimitRule.kt new file mode 100644 index 0000000..900bbdb --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/TimeLimitRule.kt @@ -0,0 +1,109 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.model + +import android.os.Parcelable +import android.util.JsonReader +import android.util.JsonWriter +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey +import androidx.room.TypeConverters +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.JsonSerializable +import io.timelimit.android.data.customtypes.ImmutableBitmaskAdapter +import kotlinx.android.parcel.Parcelize + +@Entity(tableName = "time_limit_rule") +@TypeConverters(ImmutableBitmaskAdapter::class) +@Parcelize +data class TimeLimitRule( + @PrimaryKey + @ColumnInfo(name = "id") + val id: String, + @ColumnInfo(name = "category_id") + val categoryId: String, + @ColumnInfo(name = "apply_to_extra_time_usage") + val applyToExtraTimeUsage: Boolean, + @ColumnInfo(name = "day_mask") + val dayMask: Byte, + @ColumnInfo(name = "max_time") + val maximumTimeInMillis: Int +): Parcelable, JsonSerializable { + companion object { + private const val RULE_ID = "ruleId" + private const val CATEGORY_ID = "categoryId" + private const val MAX_TIME_IN_MILLIS = "time" + private const val DAY_MASK = "days" + private const val APPLY_TO_EXTRA_TIME_USAGE = "extraTime" + + fun parse(reader: JsonReader): TimeLimitRule { + var id: String? = null + var categoryId: String? = null + var applyToExtraTimeUsage: Boolean? = null + var dayMask: Byte? = null + var maximumTimeInMillis: Int? = null + + reader.beginObject() + + while (reader.hasNext()) { + when (reader.nextName()) { + RULE_ID -> id = reader.nextString() + CATEGORY_ID -> categoryId = reader.nextString() + MAX_TIME_IN_MILLIS -> maximumTimeInMillis = reader.nextInt() + DAY_MASK -> dayMask = reader.nextInt().toByte() + APPLY_TO_EXTRA_TIME_USAGE -> applyToExtraTimeUsage = reader.nextBoolean() + else -> reader.skipValue() + } + } + + reader.endObject() + + return TimeLimitRule( + id = id!!, + categoryId = categoryId!!, + applyToExtraTimeUsage = applyToExtraTimeUsage!!, + dayMask = dayMask!!, + maximumTimeInMillis = maximumTimeInMillis!! + ) + } + } + + init { + IdGenerator.assertIdValid(id) + IdGenerator.assertIdValid(categoryId) + + if (maximumTimeInMillis < 0) { + throw IllegalArgumentException("maximumTimeInMillis $maximumTimeInMillis < 0") + } + + if (dayMask < 0 || dayMask > (1 or 2 or 4 or 8 or 16 or 32 or 64)) { + throw IllegalArgumentException() + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(RULE_ID).value(id) + writer.name(CATEGORY_ID).value(categoryId) + writer.name(MAX_TIME_IN_MILLIS).value(maximumTimeInMillis) + writer.name(DAY_MASK).value(dayMask) + writer.name(APPLY_TO_EXTRA_TIME_USAGE).value(applyToExtraTimeUsage) + + writer.endObject() + } +} diff --git a/app/src/main/java/io/timelimit/android/data/model/UsedTimeItem.kt b/app/src/main/java/io/timelimit/android/data/model/UsedTimeItem.kt new file mode 100644 index 0000000..ddb117e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/UsedTimeItem.kt @@ -0,0 +1,86 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.model + +import android.util.JsonReader +import android.util.JsonWriter +import androidx.room.ColumnInfo +import androidx.room.Entity +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.JsonSerializable + +@Entity(primaryKeys = ["category_id", "day_of_epoch"], tableName = "used_time") +data class UsedTimeItem( + @ColumnInfo(name = "day_of_epoch") + val dayOfEpoch: Int, + @ColumnInfo(name = "used_time") + val usedMillis: Long, + @ColumnInfo(name = "category_id") + val categoryId: String +): JsonSerializable { + companion object { + private const val DAY_OF_EPOCH = "day" + private const val USED_TIME_MILLIS = "time" + private const val CATEGORY_ID = "category" + + fun parse(reader: JsonReader): UsedTimeItem { + reader.beginObject() + + var dayOfEpoch: Int? = null + var usedMillis: Long? = null + var categoryId: String? = null + + while (reader.hasNext()) { + when (reader.nextName()) { + DAY_OF_EPOCH -> dayOfEpoch = reader.nextInt() + USED_TIME_MILLIS -> usedMillis = reader.nextLong() + CATEGORY_ID -> categoryId = reader.nextString() + else -> reader.skipValue() + } + } + + reader.endObject() + + return UsedTimeItem( + dayOfEpoch = dayOfEpoch!!, + usedMillis = usedMillis!!, + categoryId = categoryId!! + ) + } + } + + init { + IdGenerator.assertIdValid(categoryId) + + if (dayOfEpoch < 0) { + throw IllegalArgumentException() + } + + if (usedMillis < 0) { + throw IllegalArgumentException() + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(DAY_OF_EPOCH).value(dayOfEpoch) + writer.name(USED_TIME_MILLIS).value(usedMillis) + writer.name(CATEGORY_ID).value(categoryId) + + writer.endObject() + } +} diff --git a/app/src/main/java/io/timelimit/android/data/model/User.kt b/app/src/main/java/io/timelimit/android/data/model/User.kt new file mode 100644 index 0000000..1a1a22a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/User.kt @@ -0,0 +1,195 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.data.model + +import android.util.JsonReader +import android.util.JsonWriter +import androidx.room.* +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.JsonSerializable +import io.timelimit.android.util.parseJsonArray + +@Entity(tableName = "user") +@TypeConverters(UserTypeConverter::class) +data class User( + @PrimaryKey + @ColumnInfo(name = "id") + val id: String, + @ColumnInfo(name = "name") + val name: String, + @ColumnInfo(name = "password") + val password: String, // protected using bcrypt, can be empty if not configured + @ColumnInfo(name = "second_password_salt") + val secondPasswordSalt: String, + @ColumnInfo(name = "type") + val type: UserType, + @ColumnInfo(name = "timezone") + val timeZone: String, + // 0 = time limits enabled + @ColumnInfo(name = "disable_limits_until") + val disableLimitsUntil: Long, + @ColumnInfo(name = "mail") + val mail: String, + // empty = unset; can contain an invalid device id or the id of an device which is not used by this user + // in this case, it should be treated like unset + @ColumnInfo(name = "current_device") + val currentDevice: String, + @ColumnInfo(name = "category_for_not_assigned_apps") + // empty or invalid = no category + val categoryForNotAssignedApps: String, + @ColumnInfo(name = "relax_primary_device") + val relaxPrimaryDevice: Boolean, + @ColumnInfo(name = "mail_notification_flags") + val mailNotificationFlags: Int +): JsonSerializable { + companion object { + private const val ID = "id" + private const val NAME = "name" + private const val PASSWORD = "password" + private const val SECOND_PASSWORD_SALT = "secondPasswordSalt" + private const val TYPE = "type" + private const val TIMEZONE = "timeZone" + private const val DISABLE_LIMITS_UNTIL = "disableLimitsUntil" + private const val MAIL = "mail" + private const val CURRENT_DEVICE = "currentDevice" + private const val CATEGORY_FOR_NOT_ASSIGNED_APPS = "categoryForNotAssignedApps" + private const val RELAX_PRIMARY_DEVICE = "relaxPrimaryDevice" + private const val MAIL_NOTIFICATION_FLAGS = "mailNotificationFlags" + + fun parse(reader: JsonReader): User { + var id: String? = null + var name: String? = null + var password: String? = null + var secondPasswordSalt: String? = null + var type: UserType? = null + var timeZone: String? = null + var disableLimitsUntil: Long? = null + var mail: String? = null + var currentDevice: String? = null + var categoryForNotAssignedApps = "" + var relaxPrimaryDevice = false + var mailNotificationFlags = 0 + + reader.beginObject() + while (reader.hasNext()) { + when(reader.nextName()) { + ID -> id = reader.nextString() + NAME -> name = reader.nextString() + PASSWORD -> password = reader.nextString() + SECOND_PASSWORD_SALT -> secondPasswordSalt = reader.nextString() + TYPE -> type = UserTypeJson.parse(reader.nextString()) + TIMEZONE -> timeZone = reader.nextString() + DISABLE_LIMITS_UNTIL -> disableLimitsUntil = reader.nextLong() + MAIL -> mail = reader.nextString() + CURRENT_DEVICE -> currentDevice = reader.nextString() + CATEGORY_FOR_NOT_ASSIGNED_APPS -> categoryForNotAssignedApps = reader.nextString() + RELAX_PRIMARY_DEVICE -> relaxPrimaryDevice = reader.nextBoolean() + MAIL_NOTIFICATION_FLAGS -> mailNotificationFlags = reader.nextInt() + else -> reader.skipValue() + } + } + reader.endObject() + + return User( + id = id!!, + name = name!!, + password = password!!, + secondPasswordSalt = secondPasswordSalt!!, + type = type!!, + timeZone = timeZone!!, + disableLimitsUntil = disableLimitsUntil!!, + mail = mail!!, + currentDevice = currentDevice!!, + categoryForNotAssignedApps = categoryForNotAssignedApps, + relaxPrimaryDevice = relaxPrimaryDevice, + mailNotificationFlags = mailNotificationFlags + ) + } + + fun parseList(reader: JsonReader) = parseJsonArray(reader) { parse(reader) } + } + + init { + IdGenerator.assertIdValid(id) + + if (disableLimitsUntil < 0) { + throw IllegalArgumentException() + } + + if (name.isEmpty()) { + throw IllegalArgumentException() + } + + if (timeZone.isEmpty()) { + throw IllegalArgumentException() + } + + if (currentDevice.isNotEmpty()) { + IdGenerator.assertIdValid(currentDevice) + } + + if (categoryForNotAssignedApps.isNotEmpty()) { + IdGenerator.assertIdValid(categoryForNotAssignedApps) + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(ID).value(id) + writer.name(NAME).value(name) + writer.name(PASSWORD).value(password) + writer.name(SECOND_PASSWORD_SALT).value(secondPasswordSalt) + writer.name(TYPE).value(UserTypeJson.serialize(type)) + writer.name(TIMEZONE).value(timeZone) + writer.name(DISABLE_LIMITS_UNTIL).value(disableLimitsUntil) + writer.name(MAIL).value(mail) + writer.name(CURRENT_DEVICE).value(currentDevice) + writer.name(CATEGORY_FOR_NOT_ASSIGNED_APPS).value(categoryForNotAssignedApps) + writer.name(RELAX_PRIMARY_DEVICE).value(relaxPrimaryDevice) + writer.name(MAIL_NOTIFICATION_FLAGS).value(mailNotificationFlags) + + writer.endObject() + } +} + +enum class UserType { + Parent, Child +} + +object UserTypeJson { + private const val PARENT = "parent" + private const val CHILD = "child" + + fun parse(value: String) = when(value) { + PARENT -> UserType.Parent + CHILD -> UserType.Child + else -> throw IllegalArgumentException() + } + + fun serialize(value: UserType) = when(value) { + UserType.Parent -> PARENT + UserType.Child -> CHILD + } +} + +class UserTypeConverter { + @TypeConverter + fun toUserType(value: String) = UserTypeJson.parse(value) + + @TypeConverter + fun toString(value: UserType) = UserTypeJson.serialize(value) +} diff --git a/app/src/main/java/io/timelimit/android/date/CalendarCache.kt b/app/src/main/java/io/timelimit/android/date/CalendarCache.kt new file mode 100644 index 0000000..6f3efe7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/date/CalendarCache.kt @@ -0,0 +1,38 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.date + +import java.util.* + +object CalendarCache { + private val cache = Collections.synchronizedMap(HashMap()) + + fun getCalendar(): Calendar { + val threadId = Thread.currentThread().id + + val item = cache[threadId] + + if (item != null) { + return item + } else { + val newItem = GregorianCalendar() + + cache[threadId] = newItem + + return newItem + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/date/DateInTimezone.kt b/app/src/main/java/io/timelimit/android/date/DateInTimezone.kt new file mode 100644 index 0000000..4e7f737 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/date/DateInTimezone.kt @@ -0,0 +1,56 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.date + +import org.threeten.bp.LocalDate +import org.threeten.bp.temporal.ChronoUnit +import java.util.* + +data class DateInTimezone(val dayOfWeek: Int, val dayOfEpoch: Int) { + companion object { + fun convertDayOfWeek(dayOfWeek: Int) = when(dayOfWeek) { + Calendar.MONDAY -> 0 + Calendar.TUESDAY -> 1 + Calendar.WEDNESDAY -> 2 + Calendar.THURSDAY -> 3 + Calendar.FRIDAY -> 4 + Calendar.SATURDAY -> 5 + Calendar.SUNDAY -> 6 + else -> throw IllegalStateException() + } + + fun newInstance(timeInMillis: Long, timeZone: TimeZone): DateInTimezone { + val calendar = CalendarCache.getCalendar() + + calendar.firstDayOfWeek = Calendar.MONDAY + + calendar.timeZone = timeZone + calendar.timeInMillis = timeInMillis + + val dayOfWeek = convertDayOfWeek(calendar.get(Calendar.DAY_OF_WEEK)) + + val localDate = LocalDate.of( + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH) + ) + + val dayOfEpoch = ChronoUnit.DAYS.between(LocalDate.ofEpochDay(0), localDate).toInt() + + return DateInTimezone(dayOfWeek, dayOfEpoch) + } + } +} diff --git a/app/src/main/java/io/timelimit/android/date/DayOfWeek.kt b/app/src/main/java/io/timelimit/android/date/DayOfWeek.kt new file mode 100644 index 0000000..ce6c0f7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/date/DayOfWeek.kt @@ -0,0 +1,22 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.date + +import java.util.* + +fun getDayOfWeek(calendar: Calendar): Int { + return DateInTimezone.convertDayOfWeek(calendar.get(Calendar.DAY_OF_WEEK)) +} diff --git a/app/src/main/java/io/timelimit/android/date/MinuteOfWeek.kt b/app/src/main/java/io/timelimit/android/date/MinuteOfWeek.kt new file mode 100644 index 0000000..625f290 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/date/MinuteOfWeek.kt @@ -0,0 +1,33 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.date + +import java.util.* + +fun getMinuteOfWeek(timeInMillis: Long, timeZone: TimeZone): Int { + val calendar = CalendarCache.getCalendar() + + calendar.firstDayOfWeek = Calendar.MONDAY + + calendar.timeZone = timeZone + calendar.timeInMillis = timeInMillis + + val dayOfWeek = getDayOfWeek(calendar) + val hourOfDay = calendar.get(Calendar.HOUR_OF_DAY) + val minuteOfHour = calendar.get(Calendar.MINUTE) + + return minuteOfHour + 60 * (hourOfDay + 24 * dayOfWeek) +} diff --git a/app/src/main/java/io/timelimit/android/extensions/Checkout.kt b/app/src/main/java/io/timelimit/android/extensions/Checkout.kt new file mode 100644 index 0000000..8828c22 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/extensions/Checkout.kt @@ -0,0 +1,120 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.extensions + +import org.solovyev.android.checkout.BillingRequests +import org.solovyev.android.checkout.Checkout +import org.solovyev.android.checkout.RequestListener +import org.solovyev.android.checkout.Skus +import java.io.Closeable +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException +import kotlin.coroutines.suspendCoroutine + +suspend fun Checkout.startAsync(): CheckoutStartResponse { + val checkout = this + var resumed = false + + return suspendCoroutine { + continuation -> + + checkout.start(object: Checkout.EmptyListener() { + override fun onReady(requests: BillingRequests, product: String, billingSupported: Boolean) { + if (!resumed) { + resumed = true + + continuation.resume(CheckoutStartResponse( + requests = requests, + product = product, + billingSupported = billingSupported, + checkout = checkout + )) + } + } + }) + } +} + +suspend fun Checkout.waitUntilReady(): CheckoutStartResponse { + val checkout = this + var resumed = false + + return suspendCoroutine { + continuation -> + + checkout.whenReady(object: Checkout.EmptyListener() { + override fun onReady(requests: BillingRequests, product: String, billingSupported: Boolean) { + if (!resumed) { + resumed = true + + continuation.resume(CheckoutStartResponse( + requests = requests, + product = product, + billingSupported = billingSupported, + checkout = checkout + )) + } + } + }) + } +} + +suspend fun BillingRequests.getSkusAsync(product: String, skus: List): Skus { + val requests = this + + return suspendCoroutine { + continuation -> + + requests.getSkus(product, skus, object: RequestListener { + override fun onError(response: Int, e: Exception) { + continuation.resumeWithException(e) + } + + override fun onSuccess(result: Skus) { + continuation.resume(result) + } + }) + } +} + +suspend fun BillingRequests.consumeAsync(token: String) { + val requests = this + + suspendCoroutine { + continuation -> + + requests.consume(token, object: RequestListener { + override fun onError(response: Int, e: java.lang.Exception) { + continuation.resumeWithException(e) + } + + override fun onSuccess(result: Any) { + continuation.resume(result) + } + }) + } +} + +class CheckoutStartResponse ( + val requests: BillingRequests, + val product: String, + val billingSupported: Boolean, + private val checkout: Checkout +): Closeable { + override fun close() { + checkout.stop() + } +} diff --git a/app/src/main/java/io/timelimit/android/extensions/DialogFragment.kt b/app/src/main/java/io/timelimit/android/extensions/DialogFragment.kt new file mode 100644 index 0000000..9cd3769 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/extensions/DialogFragment.kt @@ -0,0 +1,25 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.extensions + +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager + +fun DialogFragment.showSafe(fragmentManager: FragmentManager, tag: String) { + if (!fragmentManager.isStateSaved) { + show(fragmentManager, tag) + } +} diff --git a/app/src/main/java/io/timelimit/android/extensions/EditText.kt b/app/src/main/java/io/timelimit/android/extensions/EditText.kt new file mode 100644 index 0000000..9b47130 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/extensions/EditText.kt @@ -0,0 +1,43 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.extensions + +import android.view.KeyEvent +import android.view.inputmethod.EditorInfo +import android.widget.EditText + +// TODO: use this everywhere +fun EditText.setOnEnterListenr(listener: () -> Unit) { + this.setOnEditorActionListener { _, actionId, _ -> + if (actionId == EditorInfo.IME_ACTION_GO) { + listener() + + true + } else { + false + } + } + + this.setOnKeyListener { _, keyCode, keyEvent -> + if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) { + listener() + + true + } else { + false + } + } +} diff --git a/app/src/main/java/io/timelimit/android/extensions/Navigation.kt b/app/src/main/java/io/timelimit/android/extensions/Navigation.kt new file mode 100644 index 0000000..c7ad5b6 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/extensions/Navigation.kt @@ -0,0 +1,25 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.extensions + +import androidx.navigation.NavController +import androidx.navigation.NavDirections + +fun NavController.safeNavigate(directions: NavDirections, currentScreen: Int) { + if (this.currentDestination?.id == currentScreen) { + navigate(directions) + } +} diff --git a/app/src/main/java/io/timelimit/android/extensions/Set.kt b/app/src/main/java/io/timelimit/android/extensions/Set.kt new file mode 100644 index 0000000..c7e5fa3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/extensions/Set.kt @@ -0,0 +1,24 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.extensions + +fun MutableSet.toggle(item: T) { + synchronized(this) { + if (!this.remove(item)) { + this.add(item) + } + } +} diff --git a/app/src/main/java/io/timelimit/android/extensions/TimeZone.kt b/app/src/main/java/io/timelimit/android/extensions/TimeZone.kt new file mode 100644 index 0000000..9b66875 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/extensions/TimeZone.kt @@ -0,0 +1,20 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.extensions + +import java.util.* + +fun TimeZone.readableName() = "${this.displayName} (${this.id})" \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/integration/platform/PlatformIntegration.kt b/app/src/main/java/io/timelimit/android/integration/platform/PlatformIntegration.kt new file mode 100644 index 0000000..fabf82c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/PlatformIntegration.kt @@ -0,0 +1,174 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform + +import android.graphics.drawable.Drawable +import android.os.Parcelable +import androidx.room.TypeConverter +import io.timelimit.android.data.model.App +import kotlinx.android.parcel.Parcelize + +abstract class PlatformIntegration( + val maximumProtectionLevel: ProtectionLevel +) { + abstract fun getLocalApps(deviceId: String): Collection + abstract fun getLocalAppTitle(packageName: String): String? + abstract fun getAppIcon(packageName: String): Drawable? + abstract fun getCurrentProtectionLevel(): ProtectionLevel + abstract fun getForegroundAppPermissionStatus(): RuntimePermissionStatus + abstract fun getDrawOverOtherAppsPermissionStatus(): RuntimePermissionStatus + abstract fun getNotificationAccessPermissionStatus(): NewPermissionStatus + abstract fun disableDeviceAdmin() + abstract fun trySetLockScreenPassword(password: String): Boolean + // this must have a fallback if the permission is not granted + abstract fun showOverlayMessage(text: String) + + abstract fun showAppLockScreen(currentPackageName: String) + // this should throw an SecurityException if the permission is missing + abstract suspend fun getForegroundAppPackageName(): String? + abstract fun setAppStatusMessage(message: AppStatusMessage?) + abstract fun isScreenOn(): Boolean + abstract fun setShowNotificationToRevokeTemporarilyAllowedApps(show: Boolean) + abstract fun showRemoteResetNotification() + // returns package names for which it was set + abstract fun setSuspendedApps(packageNames: List, suspend: Boolean): List + abstract fun stopSuspendingForAllApps() + + // returns true on success + abstract fun setEnableSystemLockdown(enableLockdown: Boolean): Boolean + // returns true on success + abstract fun setLockTaskPackages(packageNames: List): Boolean + + var installedAppsChangeListener: Runnable? = null +} + +enum class ProtectionLevel { + None, SimpleDeviceAdmin, PasswordDeviceAdmin, DeviceOwner +} + +object ProtectionLevelUtil { + private const val NONE = "none" + private const val SIMPLE_DEVICE_ADMIN = "simple device admin" + private const val PASSWORD_DEVICE_ADMIN = "password device admin" + private const val DEVICE_OWNER = "device owner" + + fun serialize(level: ProtectionLevel) = when(level) { + ProtectionLevel.None -> NONE + ProtectionLevel.SimpleDeviceAdmin -> SIMPLE_DEVICE_ADMIN + ProtectionLevel.PasswordDeviceAdmin -> PASSWORD_DEVICE_ADMIN + ProtectionLevel.DeviceOwner -> DEVICE_OWNER + } + + fun parse(level: String) = when(level) { + NONE -> ProtectionLevel.None + SIMPLE_DEVICE_ADMIN -> ProtectionLevel.SimpleDeviceAdmin + PASSWORD_DEVICE_ADMIN -> ProtectionLevel.PasswordDeviceAdmin + DEVICE_OWNER -> ProtectionLevel.DeviceOwner + else -> throw IllegalArgumentException() + } + + fun toInt(level: ProtectionLevel) = when(level) { + ProtectionLevel.None -> 0 + ProtectionLevel.SimpleDeviceAdmin -> 1 + ProtectionLevel.PasswordDeviceAdmin -> 2 + ProtectionLevel.DeviceOwner -> 3 + } +} + +class ProtectionLevelConverter { + @TypeConverter + fun fromString(value: String) = ProtectionLevelUtil.parse(value) + + @TypeConverter + fun toString(value: ProtectionLevel) = ProtectionLevelUtil.serialize(value) +} + +enum class RuntimePermissionStatus { + NotRequired, Granted, NotGranted +} + +object RuntimePermissionStatusUtil { + private const val NOT_REQUIRED = "not required" + private const val GRANTED = "granted" + private const val NOT_GRANTED = "not granted" + + fun serialize(value: RuntimePermissionStatus) = when(value) { + RuntimePermissionStatus.NotRequired -> NOT_REQUIRED + RuntimePermissionStatus.Granted -> GRANTED + RuntimePermissionStatus.NotGranted -> NOT_GRANTED + } + + fun parse(value: String) = when(value) { + NOT_REQUIRED -> RuntimePermissionStatus.NotRequired + GRANTED -> RuntimePermissionStatus.Granted + NOT_GRANTED -> RuntimePermissionStatus.NotGranted + else -> throw IllegalArgumentException() + } + + fun toInt(value: RuntimePermissionStatus) = when(value) { + RuntimePermissionStatus.NotGranted -> 0 + RuntimePermissionStatus.NotRequired -> 1 + RuntimePermissionStatus.Granted -> 2 + } +} + +class RuntimePermissionStatusConverter { + @TypeConverter + fun fromString(value: String) = RuntimePermissionStatusUtil.parse(value) + + @TypeConverter + fun toString(value: RuntimePermissionStatus) = RuntimePermissionStatusUtil.serialize(value) +} + +enum class NewPermissionStatus { + NotSupported, Granted, NotGranted +} + +object NewPermissionStatusUtil { + private const val NOT_SUPPORTED = "not supported" + private const val GRANTED = "granted" + private const val NOT_GRANTED = "not granted" + + fun serialize(value: NewPermissionStatus) = when(value) { + NewPermissionStatus.NotSupported -> NOT_SUPPORTED + NewPermissionStatus.Granted -> GRANTED + NewPermissionStatus.NotGranted -> NOT_GRANTED + } + + fun parse(value: String) = when(value) { + NOT_SUPPORTED -> NewPermissionStatus.NotSupported + GRANTED -> NewPermissionStatus.Granted + NOT_GRANTED -> NewPermissionStatus.NotGranted + else -> throw IllegalArgumentException() + } + + fun toInt(value: NewPermissionStatus) = when(value) { + NewPermissionStatus.NotGranted -> 0 + NewPermissionStatus.NotSupported -> 1 + NewPermissionStatus.Granted -> 2 + } +} + +class NewPermissionStatusConverter { + @TypeConverter + fun fromString(value: String) = NewPermissionStatusUtil.parse(value) + + @TypeConverter + fun toString(value: NewPermissionStatus) = NewPermissionStatusUtil.serialize(value) +} + +@Parcelize +data class AppStatusMessage(val title: String, val text: String): Parcelable diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/AdminReceiver.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/AdminReceiver.kt new file mode 100644 index 0000000..8a53ecf --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/AdminReceiver.kt @@ -0,0 +1,68 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android + +import android.app.admin.DeviceAdminReceiver +import android.content.Context +import android.content.Intent +import android.os.UserHandle +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.TriedDisablingDeviceAdminAction +import io.timelimit.android.sync.actions.apply.ApplyActionUtil + +class AdminReceiver: DeviceAdminReceiver() { + override fun onEnabled(context: Context, intent: Intent?) { + super.onEnabled(context, intent) + + DefaultAppLogic.with(context).backgroundTaskLogic.syncDeviceStatusAsync() + } + + override fun onDisabled(context: Context, intent: Intent?) { + super.onDisabled(context, intent) + + DefaultAppLogic.with(context).backgroundTaskLogic.syncDeviceStatusAsync() + } + + override fun onDisableRequested(context: Context, intent: Intent?): CharSequence { + runAsync { + val logic = DefaultAppLogic.with(context) + + if (logic.database.config().getOwnDeviceId().waitForNullableValue() != null) { + ApplyActionUtil.applyAppLogicAction( + TriedDisablingDeviceAdminAction, + logic + ) + } + } + + return context.getString(R.string.admin_disable_warning) + } + + override fun onPasswordSucceeded(context: Context, intent: Intent?) { + super.onPasswordSucceeded(context, intent) + + DefaultAppLogic.with(context).manipulationLogic.reportManualUnlock() + } + + override fun onPasswordSucceeded(context: Context, intent: Intent?, user: UserHandle?) { + super.onPasswordSucceeded(context, intent, user) + + DefaultAppLogic.with(context).manipulationLogic.reportManualUnlock() + } +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/AdminStatus.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/AdminStatus.kt new file mode 100644 index 0000000..8de583b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/AdminStatus.kt @@ -0,0 +1,53 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android + +import android.app.admin.DevicePolicyManager +import android.content.ComponentName +import android.content.Context +import android.os.Build +import io.timelimit.android.BuildConfig +import io.timelimit.android.integration.platform.ProtectionLevel + +object AdminStatus { + fun getAdminStatus(context: Context, policyManager: DevicePolicyManager): ProtectionLevel { + val component = ComponentName(context, AdminReceiver::class.java) + + return if (BuildConfig.storeCompilant) { + if (policyManager.isAdminActive(component)) { + ProtectionLevel.SimpleDeviceAdmin + } else { + ProtectionLevel.None + } + } else { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (policyManager.isDeviceOwnerApp(context.packageName)) { + ProtectionLevel.DeviceOwner + } else if (policyManager.isAdminActive(component)) { + ProtectionLevel.SimpleDeviceAdmin + } else { + ProtectionLevel.None + } + } else /* if below Lollipop */ { + if (policyManager.isAdminActive(component)) { + ProtectionLevel.PasswordDeviceAdmin + } else { + ProtectionLevel.None + } + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/AndroidIntegration.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/AndroidIntegration.kt new file mode 100644 index 0000000..04678b1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/AndroidIntegration.kt @@ -0,0 +1,338 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android + +import android.annotation.TargetApi +import android.app.ActivityManager +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.admin.DevicePolicyManager +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.pm.ApplicationInfo +import android.content.pm.PackageManager +import android.graphics.drawable.Drawable +import android.os.Build +import android.os.PowerManager +import android.os.UserManager +import android.provider.Settings +import android.util.Log +import android.widget.Toast +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.data.model.App +import io.timelimit.android.integration.platform.* +import io.timelimit.android.integration.platform.android.foregroundapp.ForegroundAppHelper +import io.timelimit.android.ui.lock.LockActivity + + +class AndroidIntegration(context: Context): PlatformIntegration(maximumProtectionLevel) { + companion object { + private const val LOG_TAG = "AndroidIntegration" + + val maximumProtectionLevel: ProtectionLevel + + init { + if (BuildConfig.storeCompilant) { + maximumProtectionLevel = ProtectionLevel.SimpleDeviceAdmin + } else { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + maximumProtectionLevel = ProtectionLevel.DeviceOwner + } else { + maximumProtectionLevel = ProtectionLevel.PasswordDeviceAdmin + } + } + } + } + + private val context = context.applicationContext + private val policyManager = this.context.getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager + private val foregroundAppHelper = ForegroundAppHelper.with(this.context) + private val powerManager = this.context.getSystemService(Context.POWER_SERVICE) as PowerManager + private val activityManager = this.context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager + private val notificationManager = this.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + private val deviceAdmin = ComponentName(context.applicationContext, AdminReceiver::class.java) + + init { + AppsChangeListener.registerBroadcastReceiver(this.context, object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + installedAppsChangeListener?.run() + } + }) + } + + override fun getLocalApps(deviceId: String): Collection { + return AndroidIntegrationApps.getLocalApps(deviceId, context) + } + + override fun getLocalAppTitle(packageName: String): String? { + return AndroidIntegrationApps.getAppTitle(packageName, context) + } + + override fun getAppIcon(packageName: String): Drawable? { + return AndroidIntegrationApps.getAppIcon(packageName, context) + } + + override fun getCurrentProtectionLevel(): ProtectionLevel { + return AdminStatus.getAdminStatus(context, policyManager) + } + + override suspend fun getForegroundAppPackageName(): String? { + return foregroundAppHelper.getForegroundAppPackage() + } + + override fun getForegroundAppPermissionStatus(): RuntimePermissionStatus { + return foregroundAppHelper.getPermissionStatus() + } + + override fun showOverlayMessage(text: String) { + Toast.makeText(context, text, Toast.LENGTH_SHORT).show() + } + + override fun getDrawOverOtherAppsPermissionStatus(): RuntimePermissionStatus { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (Settings.canDrawOverlays(context)) { + return RuntimePermissionStatus.Granted + } else { + return RuntimePermissionStatus.NotGranted + } + } else { + return RuntimePermissionStatus.NotRequired + } + } + + override fun getNotificationAccessPermissionStatus(): NewPermissionStatus { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (activityManager.isLowRamDevice) { + return NewPermissionStatus.NotSupported + } else if (NotificationManagerCompat.getEnabledListenerPackages(context).contains(context.packageName)) { + return NewPermissionStatus.Granted + } else { + return NewPermissionStatus.NotGranted + } + } else { + return NewPermissionStatus.NotSupported + } + } + + override fun trySetLockScreenPassword(password: String): Boolean { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "set password") + } + + if (!BuildConfig.storeCompilant) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { + try { + if (password.isBlank()) { + return policyManager.resetPassword("", 0) + } else if (policyManager.resetPassword(password, DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY)) { + policyManager.lockNow() + + return true + } + } catch (ex: SecurityException) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "error setting password", ex) + } + } + } + } + + return false + } + + private var lastAppStatusMessage: AppStatusMessage? = null + + override fun setAppStatusMessage(message: AppStatusMessage?) { + if (lastAppStatusMessage != message) { + lastAppStatusMessage = message + + BackgroundService.setStatusMessage(message, context) + } + } + + override fun showAppLockScreen(currentPackageName: String) { + LockActivity.start(context, currentPackageName) + } + + override fun isScreenOn(): Boolean { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { + return powerManager.isInteractive + } else { + return powerManager.isScreenOn + } + } + + override fun setShowNotificationToRevokeTemporarilyAllowedApps(show: Boolean) { + if (show) { + NotificationChannels.createAppStatusChannel(notificationManager, context) + + val actionIntent = PendingIntent.getService( + context, + PendingIntentIds.REVOKE_TEMPORARILY_ALLOWED, + BackgroundService.prepareRevokeTemporarilyAllowed(context), + PendingIntent.FLAG_UPDATE_CURRENT + ) + + val notification = NotificationCompat.Builder(context, NotificationChannels.APP_STATUS) + .setSmallIcon(R.drawable.ic_stat_check) + .setContentTitle(context.getString(R.string.background_logic_temporarily_allowed_title)) + .setContentText(context.getString(R.string.background_logic_temporarily_allowed_text)) + .setContentIntent(actionIntent) + .setWhen(0) + .setShowWhen(false) + .setSound(null) + .setOnlyAlertOnce(true) + .setLocalOnly(true) + .setAutoCancel(false) + .setOngoing(true) + .setPriority(NotificationCompat.PRIORITY_LOW) + .build() + + notificationManager.notify(NotificationIds.REVOKE_TEMPORARILY_ALLOWED_APPS, notification) + } else { + notificationManager.cancel(NotificationIds.REVOKE_TEMPORARILY_ALLOWED_APPS) + } + } + + override fun showRemoteResetNotification() { + NotificationChannels.createAppStatusChannel(notificationManager, context) + + notificationManager.notify( + NotificationIds.APP_RESET, + NotificationCompat.Builder(context, NotificationChannels.APP_STATUS) + .setSmallIcon(R.drawable.ic_stat_timelapse) + .setContentTitle(context.getString(R.string.remote_reset_notification_title)) + .setContentText(context.getString(R.string.remote_reset_notification_text)) + .setWhen(System.currentTimeMillis()) + .setShowWhen(true) + .setSound(null) + .setOnlyAlertOnce(true) + .setLocalOnly(true) + .setAutoCancel(false) + .setOngoing(false) + .setPriority(NotificationCompat.PRIORITY_LOW) + .build() + ) + } + + override fun disableDeviceAdmin() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (policyManager.isDeviceOwnerApp(context.packageName)) { + setEnableSystemLockdown(false) + policyManager.clearDeviceOwnerApp(context.packageName) + } + } + + policyManager.removeActiveAdmin(deviceAdmin) + } + + @TargetApi(Build.VERSION_CODES.N) + override fun setSuspendedApps(packageNames: List, suspend: Boolean): List { + if ( + (getCurrentProtectionLevel() == ProtectionLevel.DeviceOwner) && + (!BuildConfig.storeCompilant) && + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) + ) { + val failedApps = policyManager.setPackagesSuspended( + deviceAdmin, + packageNames.toTypedArray(), + suspend + ) + + return packageNames.filterNot { failedApps.contains(it) } + } else { + return emptyList() + } + } + + override fun setEnableSystemLockdown(enableLockdown: Boolean): Boolean { + return if ( + Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && + policyManager.isDeviceOwnerApp(context.packageName) && + (!BuildConfig.storeCompilant) + ) { + if (enableLockdown) { + // disable problematic features + policyManager.addUserRestriction(deviceAdmin, UserManager.DISALLOW_ADD_USER) + policyManager.addUserRestriction(deviceAdmin, UserManager.DISALLOW_FACTORY_RESET) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + policyManager.addUserRestriction(deviceAdmin, UserManager.DISALLOW_SAFE_BOOT) + } + } else /* disable lockdown */ { + // enable problematic features + policyManager.clearUserRestriction(deviceAdmin, UserManager.DISALLOW_ADD_USER) + policyManager.clearUserRestriction(deviceAdmin, UserManager.DISALLOW_FACTORY_RESET) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + policyManager.clearUserRestriction(deviceAdmin, UserManager.DISALLOW_SAFE_BOOT) + } + + enableSystemApps() + stopSuspendingForAllApps() + } + + true + } else { + false + } + } + + private fun enableSystemApps() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { + return + } + + // disabled system apps (all apps - enabled apps) + val allApps = context.packageManager.getInstalledApplications( + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) + PackageManager.GET_UNINSTALLED_PACKAGES + else + PackageManager.MATCH_UNINSTALLED_PACKAGES + ) + val enabledAppsPackages = context.packageManager.getInstalledApplications(0).map { it.packageName }.toSet() + + allApps + .asSequence() + .filterNot { enabledAppsPackages.contains(it.packageName) } + .filter { it.flags and ApplicationInfo.FLAG_SYSTEM != 0 } + .map { it.packageName } + .forEach { policyManager.enableSystemApp(deviceAdmin, it) } + } + + override fun stopSuspendingForAllApps() { + setSuspendedApps(context.packageManager.getInstalledApplications(0).map { it.packageName }, false) + } + + override fun setLockTaskPackages(packageNames: List): Boolean { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (policyManager.isDeviceOwnerApp(context.packageName)) { + policyManager.setLockTaskPackages(deviceAdmin, packageNames.toTypedArray()) + + true + } else { + false + } + } else { + false + } + } +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/Apps.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/Apps.kt new file mode 100644 index 0000000..b8514dc --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/Apps.kt @@ -0,0 +1,165 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android + +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ResolveInfo +import android.graphics.drawable.Drawable +import android.os.Build +import android.provider.ContactsContract +import android.provider.Settings +import android.provider.Telephony +import io.timelimit.android.BuildConfig +import io.timelimit.android.data.model.App +import io.timelimit.android.data.model.AppRecommendation + +object AndroidIntegrationApps { + private val mainIntent = Intent(Intent.ACTION_MAIN) + .addCategory(Intent.CATEGORY_LAUNCHER) + + private val launcherIntent = Intent(Intent.ACTION_MAIN) + .addCategory(Intent.CATEGORY_DEFAULT) + .addCategory(Intent.CATEGORY_HOME) + + val ignoredApps = HashSet() + init { + ignoredApps.add("com.android.systemui") + ignoredApps.add("android") + ignoredApps.add("com.android.packageinstaller") + ignoredApps.add("com.google.android.packageinstaller") + ignoredApps.add("com.android.bluetooth") + ignoredApps.add("com.android.nfc") + } + + fun getLocalApps(deviceId: String, context: Context): Collection { + val packageManager = context.packageManager + + val result = HashMap() + + // WHITELIST + // add launcher + add(map = result, resolveInfoList = packageManager.queryIntentActivities(launcherIntent, 0), deviceId = deviceId, recommendation = AppRecommendation.Whitelist, context = context) + // add settings + add(map = result, packageName = Intent(Settings.ACTION_SETTINGS).resolveActivity(packageManager)?.packageName, deviceId = deviceId, recommendation = AppRecommendation.Whitelist, context = context) + // add dialer + add(map = result, packageName = Intent(Intent.ACTION_DIAL).resolveActivity(packageManager)?.packageName, deviceId = deviceId, recommendation = AppRecommendation.Whitelist, context = context) + // add SMS + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { + val smsApp: String? = Telephony.Sms.getDefaultSmsPackage(context) + + if (smsApp != null) { + add(map = result, packageName = smsApp, deviceId = deviceId, recommendation = AppRecommendation.Whitelist, context = context) + } + } else { + add(map = result, packageName = Intent(android.content.Intent.ACTION_VIEW).setType("vnd.android-dir/mms-sms").resolveActivity(packageManager)?.packageName, deviceId = deviceId, recommendation = AppRecommendation.Whitelist, context = context) + } + // add contacts + add(map = result, packageName = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI).resolveActivity(packageManager)?.packageName, deviceId = deviceId, recommendation = AppRecommendation.Whitelist, context = context) + // add google play + if (BuildConfig.storeCompilant) { + add(map = result, packageName = "com.android.vending", deviceId = deviceId, recommendation = AppRecommendation.Whitelist, context = context) + } + // add all apps with launcher icon + add(map = result, resolveInfoList = packageManager.queryIntentActivities(mainIntent, 0), deviceId = deviceId, recommendation = AppRecommendation.None, context = context) + + val installedPackages = packageManager.getInstalledApplications(0) + + for (applicationInfo in installedPackages) { + val packageName = applicationInfo.packageName + + if (!result.containsKey(packageName) && !ignoredApps.contains(packageName)) { + result[packageName] = App( + deviceId = deviceId, + packageName = packageName, + title = applicationInfo.loadLabel(packageManager).toString(), + isLaunchable = false, + recommendation = AppRecommendation.None + ) + } + } + + return result.values + } + + private fun add(map: MutableMap, resolveInfoList: List, deviceId: String, recommendation: AppRecommendation, context: Context) { + val packageManager = context.packageManager + + for (info in resolveInfoList) { + val packageName = info.activityInfo.applicationInfo.packageName + if (ignoredApps.contains(packageName)) { + continue + } + + if (!map.containsKey(packageName)) { + map[packageName] = App( + deviceId = deviceId, + packageName = packageName, + title = info.activityInfo.applicationInfo.loadLabel(packageManager).toString(), + isLaunchable = true, + recommendation = recommendation + ) + } + } + } + + private fun add(map: MutableMap, packageName: String?, deviceId: String, recommendation: AppRecommendation, context: Context) { + val packageManager = context.packageManager + + if (packageName == null) { + return + } + + if (ignoredApps.contains(packageName)) { + return + } + + if (map.containsKey(packageName)) { + return + } + + try { + val packageInfo = context.packageManager.getApplicationInfo(packageName, 0) + + map[packageName] = App( + deviceId = deviceId, + packageName = packageName, + title = packageInfo.loadLabel(packageManager).toString(), + isLaunchable = true, + recommendation = recommendation + ) + } catch (ex: PackageManager.NameNotFoundException) { + // ignore + } + } + + fun getAppTitle(packageName: String, context: Context): String? { + try { + return context.packageManager.getApplicationInfo(packageName, 0).loadLabel(context.packageManager).toString() + } catch (ex: PackageManager.NameNotFoundException) { + return null + } + } + + fun getAppIcon(packageName: String, context: Context): Drawable? { + try { + return context.packageManager.getApplicationIcon(packageName) + } catch (ex: PackageManager.NameNotFoundException) { + return null + } + } +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/AppsChangeListener.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/AppsChangeListener.kt new file mode 100644 index 0000000..414abcf --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/AppsChangeListener.kt @@ -0,0 +1,41 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter + +object AppsChangeListener { + private val changeFilter = IntentFilter() + private val externalFilter = IntentFilter() + + init { + changeFilter.addAction(Intent.ACTION_PACKAGE_ADDED) + changeFilter.addAction(Intent.ACTION_PACKAGE_CHANGED) + changeFilter.addAction(Intent.ACTION_PACKAGE_REMOVED) + changeFilter.addDataScheme("package") + + externalFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE) + externalFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE) + } + + fun registerBroadcastReceiver(context: Context, listener: BroadcastReceiver) { + context.registerReceiver(listener, changeFilter) + context.registerReceiver(listener, externalFilter) + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/BackgroundService.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/BackgroundService.kt new file mode 100644 index 0000000..99d2a1f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/BackgroundService.kt @@ -0,0 +1,129 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android + +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.os.IBinder +import androidx.core.app.NotificationCompat +import androidx.core.content.ContextCompat +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.integration.platform.AppStatusMessage +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.MainActivity + +class BackgroundService: Service() { + companion object { + private const val ACTION = "a" + private const val ACTION_SET_NOTIFICATION = "a" + private const val ACTION_REVOKE_TEMPORARILY_ALLOWED_APPS = "b" + private const val EXTRA_NOTIFICATION = "b" + + fun setStatusMessage(status: AppStatusMessage?, context: Context) { + val intent = Intent(context, BackgroundService::class.java) + + if (status != null) { + ContextCompat.startForegroundService( + context, + intent + .putExtra(ACTION, ACTION_SET_NOTIFICATION) + .putExtra(EXTRA_NOTIFICATION, status) + ) + } else { + context.stopService(intent) + } + } + + fun prepareRevokeTemporarilyAllowed(context: Context) = Intent(context, BackgroundService::class.java) + .putExtra(ACTION, ACTION_REVOKE_TEMPORARILY_ALLOWED_APPS) + } + + private val notificationManager: NotificationManager by lazy { + getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + } + + private var didPostNotification = false + + override fun onCreate() { + super.onCreate() + + // init the app logic if not yet done + DefaultAppLogic.with(this) + + // create the channel + NotificationChannels.createAppStatusChannel(notificationManager, this) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent != null) { + val action = intent.getStringExtra(ACTION) + + if (action == ACTION_SET_NOTIFICATION) { + val appStatusMessage = intent.getParcelableExtra(EXTRA_NOTIFICATION) + + val openAppIntent = PendingIntent.getActivity( + this, + PendingIntentIds.OPEN_MAIN_APP, + Intent(this, MainActivity::class.java), + PendingIntent.FLAG_UPDATE_CURRENT + ) + + val notification = NotificationCompat.Builder(this, NotificationChannels.APP_STATUS) + .setSmallIcon(R.drawable.ic_stat_timelapse) + .setContentTitle(appStatusMessage.title) + .setContentText(appStatusMessage.text) + .setContentIntent(openAppIntent) + .setWhen(0) + .setShowWhen(false) + .setSound(null) + .setOnlyAlertOnce(true) + .setLocalOnly(true) + .setAutoCancel(false) + .setOngoing(true) + .setPriority(NotificationCompat.PRIORITY_LOW) + .build() + + if (didPostNotification) { + notificationManager.notify(NotificationIds.APP_STATUS, notification) + } else { + startForeground(NotificationIds.APP_STATUS, notification) + didPostNotification = true + } + } else if (action == ACTION_REVOKE_TEMPORARILY_ALLOWED_APPS) { + runAsync { + DefaultAppLogic.with(this@BackgroundService).backgroundTaskLogic.resetTemporarilyAllowedApps() + } + } + } + + return START_REDELIVER_INTENT + } + + override fun onDestroy() { + stopForeground(true) + didPostNotification = false + + super.onDestroy() + } + + override fun onBind(intent: Intent?): IBinder { + throw NotImplementedError() + } +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/Notification.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/Notification.kt new file mode 100644 index 0000000..7113558 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/Notification.kt @@ -0,0 +1,71 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.content.Context +import android.os.Build +import io.timelimit.android.R + +object NotificationIds { + const val APP_STATUS = 1 + const val NOTIFICATION_BLOCKED = 2 + const val REVOKE_TEMPORARILY_ALLOWED_APPS = 3 + const val APP_RESET = 4 +} + +object NotificationChannels { + const val APP_STATUS = "app status" + const val BLOCKED_NOTIFICATIONS_NOTIFICATION = "notification blocked notification" + + fun createAppStatusChannel(notificationManager: NotificationManager, context: Context) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + notificationManager.createNotificationChannel( + NotificationChannel( + APP_STATUS, + context.getString(R.string.notification_channel_app_status_title), + NotificationManager.IMPORTANCE_LOW + ).apply { + description = context.getString(R.string.notification_channel_app_status_description) + enableLights(false) + setSound(null, null) + enableVibration(false) + setShowBadge(false) + } + ) + } + } + + fun createBlockedNotificationChannel(notificationManager: NotificationManager, context: Context) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + notificationManager.createNotificationChannel( + NotificationChannel( + NotificationChannels.BLOCKED_NOTIFICATIONS_NOTIFICATION, + context.getString(R.string.notification_channel_blocked_notification_title), + NotificationManager.IMPORTANCE_DEFAULT + ).apply { + description = context.getString(R.string.notification_channel_blocked_notification_text) + } + ) + } + } +} + +object PendingIntentIds { + const val OPEN_MAIN_APP = 1 + const val REVOKE_TEMPORARILY_ALLOWED = 2 +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/NotificationListener.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/NotificationListener.kt new file mode 100644 index 0000000..43906e6 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/NotificationListener.kt @@ -0,0 +1,144 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android + +import android.annotation.TargetApi +import android.app.NotificationManager +import android.content.Context +import android.content.pm.ApplicationInfo +import android.content.pm.PackageManager +import android.os.Build +import android.service.notification.NotificationListenerService +import android.service.notification.StatusBarNotification +import android.util.Log +import androidx.core.app.NotificationCompat +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.livedata.waitForNonNullValue +import io.timelimit.android.logic.* + +@TargetApi(Build.VERSION_CODES.LOLLIPOP) +class NotificationListener: NotificationListenerService() { + companion object { + private const val LOG_TAG = "NotificationListenerLog" + } + + private val appLogic: AppLogic by lazy { DefaultAppLogic.with(this) } + private val blockingReasonUtil: BlockingReasonUtil by lazy { BlockingReasonUtil(appLogic) } + private val notificationManager: NotificationManager by lazy { getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager } + private val queryAppTitleCache: QueryAppTitleCache by lazy { QueryAppTitleCache(appLogic.platformIntegration) } + + override fun onCreate() { + super.onCreate() + + NotificationChannels.createBlockedNotificationChannel(notificationManager, this) + } + + override fun onNotificationPosted(sbn: StatusBarNotification) { + super.onNotificationPosted(sbn) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, sbn.packageName) + } + + runAsync { + val reason = shouldRemoveNotification(sbn) + + if (reason != BlockingReason.None) { + val success = try { + cancelNotification(sbn.key) + + true + } catch (ex: SecurityException) { + // this occurs when the notification access is revoked + // while this function is running + + false + } + + notificationManager.notify( + sbn.packageName, + NotificationIds.NOTIFICATION_BLOCKED, + NotificationCompat.Builder(this@NotificationListener, NotificationChannels.BLOCKED_NOTIFICATIONS_NOTIFICATION) + .setDefaults(NotificationCompat.DEFAULT_ALL) + .setSmallIcon(R.drawable.ic_stat_block) + .setContentTitle( + if (success) + getString(R.string.notification_filter_not_blocked_title) + else + getString(R.string.notification_filter_blocking_failed_title) + ) + .setContentText( + queryAppTitleCache.query(sbn.packageName) + + " - " + + when (reason) { + BlockingReason.NotPartOfAnCategory -> getString(R.string.lock_reason_short_no_category) + BlockingReason.TemporarilyBlocked -> getString(R.string.lock_reason_short_temporarily_blocked) + BlockingReason.TimeOver -> getString(R.string.lock_reason_short_time_over) + BlockingReason.TimeOverExtraTimeCanBeUsedLater -> getString(R.string.lock_reason_short_time_over) + BlockingReason.BlockedAtThisTime -> getString(R.string.lock_reason_short_blocked_time_area) + BlockingReason.MissingNetworkTime -> getString(R.string.lock_reason_short_missing_network_time) + BlockingReason.RequiresCurrentDevice -> getString(R.string.lock_reason_short_requires_current_device) + BlockingReason.None -> throw IllegalStateException() + } + ) + .setLocalOnly(true) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) + .build() + ) + } + } + } + + override fun onNotificationRemoved(sbn: StatusBarNotification) { + super.onNotificationRemoved(sbn) + + // not interesting but required for old android versions + } + + private suspend fun shouldRemoveNotification(sbn: StatusBarNotification): BlockingReason { + if (sbn.packageName == packageName || sbn.isOngoing) { + return BlockingReason.None + } + + val blockingReason = blockingReasonUtil.getBlockingReason(sbn.packageName).waitForNonNullValue() + + if (blockingReason == BlockingReason.None) { + return BlockingReason.None + } + + if (isSystemApp(sbn.packageName) && blockingReason == BlockingReason.NotPartOfAnCategory) { + return BlockingReason.None + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "blocking notification of ${sbn.packageName} because $blockingReason") + } + + return blockingReason + } + + private fun isSystemApp(packageName: String): Boolean { + try { + val appInfo = packageManager.getApplicationInfo(packageName, 0) + + return appInfo.flags and ApplicationInfo.FLAG_SYSTEM == ApplicationInfo.FLAG_SYSTEM + } catch (ex: PackageManager.NameNotFoundException) { + return false + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/CompatForegroundAppHelper.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/CompatForegroundAppHelper.kt new file mode 100644 index 0000000..47fce59 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/CompatForegroundAppHelper.kt @@ -0,0 +1,36 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android.foregroundapp + +import android.app.ActivityManager +import android.content.Context +import io.timelimit.android.integration.platform.RuntimePermissionStatus + +class CompatForegroundAppHelper(context: Context) : ForegroundAppHelper() { + private val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager + + override suspend fun getForegroundAppPackage(): String? { + return try { + activityManager.getRunningTasks(1)[0].topActivity.packageName + } catch (ex: NullPointerException) { + null + } + } + + override fun getPermissionStatus(): RuntimePermissionStatus { + return RuntimePermissionStatus.NotRequired + } +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/ForegroundAppHelper.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/ForegroundAppHelper.kt new file mode 100644 index 0000000..5b21d40 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/ForegroundAppHelper.kt @@ -0,0 +1,46 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android.foregroundapp + +import android.content.Context +import android.os.Build +import io.timelimit.android.integration.platform.RuntimePermissionStatus + +abstract class ForegroundAppHelper { + abstract suspend fun getForegroundAppPackage(): String? + abstract fun getPermissionStatus(): RuntimePermissionStatus + + companion object { + private val lock = Any() + private var instance: ForegroundAppHelper? = null + + fun with(context: Context): ForegroundAppHelper { + if (instance == null) { + synchronized(lock) { + if (instance == null) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + instance = LollipopForegroundAppHelper(context.applicationContext) + } else { + instance = CompatForegroundAppHelper(context.applicationContext) + } + } + } + } + + return instance!! + } + } +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/LollipopForegroundAppHelper.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/LollipopForegroundAppHelper.kt new file mode 100644 index 0000000..cf0bd26 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/LollipopForegroundAppHelper.kt @@ -0,0 +1,99 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android.foregroundapp + +import android.annotation.TargetApi +import android.app.AppOpsManager +import android.app.usage.UsageEvents +import android.app.usage.UsageStatsManager +import android.content.Context +import android.os.Build +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.integration.platform.RuntimePermissionStatus +import java.util.concurrent.Executor +import java.util.concurrent.Executors + +@TargetApi(Build.VERSION_CODES.LOLLIPOP) +class LollipopForegroundAppHelper(private val context: Context) : ForegroundAppHelper() { + companion object { + private val foregroundAppThread: Executor by lazy { Executors.newSingleThreadExecutor() } + } + + private val usageStatsManager = context.getSystemService(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) Context.USAGE_STATS_SERVICE else "usagestats") as UsageStatsManager + private val appOpsManager = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager + + private var lastQueryTime: Long = 0 + private var lastPackage: String? = null + private var lastPackageTime: Long = 0 + private val event = UsageEvents.Event() + + @Throws(SecurityException::class) + override suspend fun getForegroundAppPackage(): String? { + if (getPermissionStatus() == RuntimePermissionStatus.NotGranted) { + throw SecurityException() + } + + return foregroundAppThread.executeAndWait { + val now = System.currentTimeMillis() + + if (lastQueryTime > now) { + // if the time went backwards, forget everything + lastQueryTime = 0 + lastPackage = null + lastPackageTime = 0 + } + + val queryStartTime = if (lastQueryTime == 0L) { + // query data for last 7 days + now - 1000 * 60 * 60 * 24 * 7 + } else { + // query data since last query + // note: when the duration is too small, Android returns no data + // due to that, 1 second more than required is queried + // which seems to provide all data + // update: with 1 second, some App switching events were missed + // it seems to always work with 1.5 seconds + lastQueryTime - 1500 + } + + usageStatsManager.queryEvents(queryStartTime, now)?.let { usageEvents -> + while (usageEvents.hasNextEvent()) { + usageEvents.getNextEvent(event) + + if (event.eventType == UsageEvents.Event.MOVE_TO_FOREGROUND) { + if (event.timeStamp > lastPackageTime) { + lastPackageTime = event.timeStamp + lastPackage = event.packageName + } + } + } + } + + lastQueryTime = now + + lastPackage + } + } + + override fun getPermissionStatus(): RuntimePermissionStatus { + if(appOpsManager.checkOpNoThrow("android:get_usage_stats", + android.os.Process.myUid(), context.packageName) == AppOpsManager.MODE_ALLOWED) { + return RuntimePermissionStatus.Granted + } else { + return RuntimePermissionStatus.NotGranted + } + } +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/receiver/BootReceiver.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/receiver/BootReceiver.kt new file mode 100644 index 0000000..19688fb --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/receiver/BootReceiver.kt @@ -0,0 +1,30 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android.receiver + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import io.timelimit.android.logic.DefaultAppLogic + +class BootReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent?) { + if (intent?.action == Intent.ACTION_BOOT_COMPLETED) { + // this starts the logic (if not yet done) + DefaultAppLogic.with(context).backgroundTaskLogic.reportDeviceReboot() + } + } +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/android/receiver/UpdateReceiver.kt b/app/src/main/java/io/timelimit/android/integration/platform/android/receiver/UpdateReceiver.kt new file mode 100644 index 0000000..de1ff91 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/receiver/UpdateReceiver.kt @@ -0,0 +1,30 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.android.receiver + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import io.timelimit.android.logic.DefaultAppLogic + +class UpdateReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent?) { + if (intent?.action == Intent.ACTION_MY_PACKAGE_REPLACED) { + // this starts the logic (if not yet done) + DefaultAppLogic.with(context) + } + } +} diff --git a/app/src/main/java/io/timelimit/android/integration/platform/dummy/DummyApps.kt b/app/src/main/java/io/timelimit/android/integration/platform/dummy/DummyApps.kt new file mode 100644 index 0000000..5e6faee --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/dummy/DummyApps.kt @@ -0,0 +1,55 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.dummy + +import io.timelimit.android.data.model.App +import io.timelimit.android.data.model.AppRecommendation + +object DummyApps { + val taskmanagerLocalApp = App( + deviceId = "", + packageName = "com.demo.taskkiller", + title = "Task-Killer", + isLaunchable = true, + recommendation = AppRecommendation.Blacklist + ) + + val launcherLocalApp = App( + deviceId = "", + packageName = "com.demo.home", + title = "Launcher", + isLaunchable = true, + recommendation = AppRecommendation.Whitelist + ) + + val messagingLocalApp = App( + deviceId = "", + packageName = "com.demo.messaging", + title = "Messaging", + isLaunchable = true, + recommendation = AppRecommendation.None + ) + + val gameLocalApp = App( + deviceId = "", + packageName = "com.demo.game", + title = "Game", + isLaunchable = true, + recommendation = AppRecommendation.None + ) + + val all = listOf(taskmanagerLocalApp, launcherLocalApp, messagingLocalApp, gameLocalApp) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/integration/platform/dummy/DummyIntegration.kt b/app/src/main/java/io/timelimit/android/integration/platform/dummy/DummyIntegration.kt new file mode 100644 index 0000000..215b1f7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/dummy/DummyIntegration.kt @@ -0,0 +1,128 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.platform.dummy + +import android.graphics.drawable.Drawable +import io.timelimit.android.data.model.App +import io.timelimit.android.integration.platform.* + +class DummyIntegration( + maximumProtectionLevel: ProtectionLevel +): PlatformIntegration(maximumProtectionLevel) { + val localApps = ArrayList(DummyApps.all) + var protectionLevel = ProtectionLevel.None + var foregroundAppPermission: RuntimePermissionStatus = RuntimePermissionStatus.NotRequired + var drawOverOtherApps: RuntimePermissionStatus = RuntimePermissionStatus.NotRequired + var notificationAccess: NewPermissionStatus = NewPermissionStatus.NotSupported + var foregroundApp: String? = null + var screenOn = false + var lastAppStatusMessage: AppStatusMessage? = null + var launchLockScreenForPackage: String? = null + var showRevokeTemporarilyAllowedNotification = false + + override fun getLocalApps(deviceId: String): Collection { + return localApps.map{ it.copy(deviceId = deviceId) } + } + + override fun getLocalAppTitle(packageName: String): String? { + return localApps.find { it.packageName == packageName }?.title + } + + override fun getAppIcon(packageName: String): Drawable? { + return null + } + + override fun getCurrentProtectionLevel(): ProtectionLevel { + return protectionLevel + } + + override fun getForegroundAppPermissionStatus(): RuntimePermissionStatus { + return foregroundAppPermission + } + + override fun getDrawOverOtherAppsPermissionStatus(): RuntimePermissionStatus { + return drawOverOtherApps + } + + override fun getNotificationAccessPermissionStatus(): NewPermissionStatus { + return notificationAccess + } + + override fun trySetLockScreenPassword(password: String): Boolean { + return false // it failed + } + override fun showOverlayMessage(text: String) { + // do nothing + } + + override fun showAppLockScreen(currentPackageName: String) { + launchLockScreenForPackage = currentPackageName + } + + fun getAndResetShowAppLockScreen(): String? { + try { + return launchLockScreenForPackage + } finally { + launchLockScreenForPackage = null + } + } + + override suspend fun getForegroundAppPackageName(): String? { + if (foregroundAppPermission == RuntimePermissionStatus.NotGranted) { + throw SecurityException() + } + + return foregroundApp + } + + override fun setAppStatusMessage(message: AppStatusMessage?) { + lastAppStatusMessage = message + } + + fun getAppStatusMessage(): AppStatusMessage? { + return lastAppStatusMessage + } + + fun notifyLocalAppsChanged() { + installedAppsChangeListener?.run() + } + + override fun isScreenOn(): Boolean { + return screenOn + } + + override fun setShowNotificationToRevokeTemporarilyAllowedApps(show: Boolean) { + showRevokeTemporarilyAllowedNotification = show + } + + override fun showRemoteResetNotification() { + // nothing to do + } + + override fun disableDeviceAdmin() { + // nothing to do + } + + override fun setSuspendedApps(packageNames: List, suspend: Boolean) = emptyList() + + override fun stopSuspendingForAllApps() { + // nothing to do + } + + override fun setEnableSystemLockdown(enableLockdown: Boolean) = false + + override fun setLockTaskPackages(packageNames: List) = false +} diff --git a/app/src/main/java/io/timelimit/android/integration/time/DummyTimeApi.kt b/app/src/main/java/io/timelimit/android/integration/time/DummyTimeApi.kt new file mode 100644 index 0000000..43922c9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/time/DummyTimeApi.kt @@ -0,0 +1,91 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.time + +import java.util.* +import kotlin.collections.ArrayList + +class DummyTimeApi(var timeStepSizeInMillis: Long): TimeApi() { + private var currentTime: Long = System.currentTimeMillis() + private var currentUptime: Long = 0 + private var scheduledActions = Collections.synchronizedList(ArrayList()) + var timeZone = TimeZone.getDefault() + + override fun getCurrentTimeInMillis(): Long { + return currentTime + } + + fun setCurrentTimeInMillis(time: Long) { + this.currentTime = time + } + + override fun getCurrentUptimeInMillis(): Long { + return currentUptime + } + + override fun getSystemTimeZone() = timeZone + + override fun runDelayed(runnable: Runnable, delayInMillis: Long) { + scheduledActions.add(ScheduledAction(currentUptime + delayInMillis, runnable)) + } + + override fun cancelScheduledAction(runnable: Runnable) { + scheduledActions.removeAll { it.action === runnable } + } + + private fun emulateTimeAtOnce(timeInMillis: Long) { + if (timeInMillis <= 0) { + throw IllegalStateException() + } + + currentTime += timeInMillis + currentUptime += timeInMillis + + synchronized(scheduledActions) { + val iterator = scheduledActions.iterator() + + while (iterator.hasNext()) { + val action = iterator.next() + + if (action.uptime <= currentUptime) { + action.action.run() + iterator.remove() + } + } + } + } + + fun emulateTimePassing(timeInMillis: Long) { + var emulatedTime: Long = 0 + + while (emulatedTime < timeInMillis) { + val missingTime = timeInMillis - emulatedTime + + if (missingTime >= timeStepSizeInMillis) { + emulateTimeAtOnce(timeStepSizeInMillis) + emulatedTime += timeStepSizeInMillis + } else { + emulateTimeAtOnce(missingTime) + emulatedTime += missingTime + } + } + } + + private class ScheduledAction ( + val uptime: Long, + val action: Runnable + ) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/integration/time/RealTimeApi.kt b/app/src/main/java/io/timelimit/android/integration/time/RealTimeApi.kt new file mode 100644 index 0000000..af0ce2f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/time/RealTimeApi.kt @@ -0,0 +1,43 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.time + +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import java.util.* + +object RealTimeApi: TimeApi() { + private val handler = Handler(Looper.getMainLooper()) + + override fun getCurrentTimeInMillis(): Long { + return System.currentTimeMillis() + } + + override fun getCurrentUptimeInMillis(): Long { + return SystemClock.elapsedRealtime() + } + + override fun runDelayed(runnable: Runnable, delayInMillis: Long) { + handler.postDelayed(runnable, delayInMillis) + } + + override fun cancelScheduledAction(runnable: Runnable) { + handler.removeCallbacks(runnable) + } + + override fun getSystemTimeZone() = TimeZone.getDefault() +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/integration/time/TimeApi.kt b/app/src/main/java/io/timelimit/android/integration/time/TimeApi.kt new file mode 100644 index 0000000..10b69b3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/time/TimeApi.kt @@ -0,0 +1,36 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.integration.time + +import java.util.* +import kotlin.coroutines.resume +import kotlin.coroutines.suspendCoroutine + +abstract class TimeApi { + // normal clock - can be modified by the user at any time + abstract fun getCurrentTimeInMillis(): Long + // clock which starts at 0 at boot + abstract fun getCurrentUptimeInMillis(): Long + // function to run something delayed at the UI Thread + abstract fun runDelayed(runnable: Runnable, delayInMillis: Long) + abstract fun cancelScheduledAction(runnable: Runnable) + suspend fun sleep(timeInMillis: Long) = suspendCoroutine { + runDelayed(Runnable { + it.resume(null) + }, timeInMillis) + } + abstract fun getSystemTimeZone(): TimeZone +} diff --git a/app/src/main/java/io/timelimit/android/livedata/BooleanConnections.kt b/app/src/main/java/io/timelimit/android/livedata/BooleanConnections.kt new file mode 100644 index 0000000..5e6620c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/BooleanConnections.kt @@ -0,0 +1,36 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import androidx.lifecycle.LiveData + +fun LiveData.or(other: LiveData): LiveData { + return this.switchMap { v1 -> + other.map { v2 -> + v1 || v2 + } + } +} + +fun LiveData.and(other: LiveData): LiveData { + return this.switchMap { v1 -> + other.map { v2 -> + v1 && v2 + } + } +} + +fun LiveData.invert(): LiveData = this.map { !it } diff --git a/app/src/main/java/io/timelimit/android/livedata/CastDown.kt b/app/src/main/java/io/timelimit/android/livedata/CastDown.kt new file mode 100644 index 0000000..06ab017 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/CastDown.kt @@ -0,0 +1,20 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import androidx.lifecycle.LiveData + +fun LiveData.castDown(): LiveData = this diff --git a/app/src/main/java/io/timelimit/android/livedata/FromValue.kt b/app/src/main/java/io/timelimit/android/livedata/FromValue.kt new file mode 100644 index 0000000..7dbd878 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/FromValue.kt @@ -0,0 +1,26 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import androidx.lifecycle.LiveData +import androidx.lifecycle.MediatorLiveData + +fun liveDataFromValue(value: T): LiveData { + val result = MediatorLiveData() + result.value = value + + return result +} diff --git a/app/src/main/java/io/timelimit/android/livedata/FromView.kt b/app/src/main/java/io/timelimit/android/livedata/FromView.kt new file mode 100644 index 0000000..5ad9f62 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/FromView.kt @@ -0,0 +1,44 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import android.text.Editable +import android.text.TextWatcher +import android.widget.TextView +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData + +fun TextView.getTextLive(): LiveData { + val result = MutableLiveData() + + result.value = this.text.toString() + + this.addTextChangedListener(object: TextWatcher { + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { + // ignore + } + + override fun afterTextChanged(s: Editable?) { + result.value = s.toString() + } + + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { + // ignore + } + }) + + return result +} diff --git a/app/src/main/java/io/timelimit/android/livedata/GetValue.kt b/app/src/main/java/io/timelimit/android/livedata/GetValue.kt new file mode 100644 index 0000000..ce00616 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/GetValue.kt @@ -0,0 +1,55 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlin.coroutines.resume + +suspend fun LiveData.waitUntilValueMatches(check: (T?) -> Boolean): T? { + val liveData = this + var observer: Observer? = null + + fun removeObserver() { + val currentObserver = observer + + if (currentObserver != null) { + liveData.removeObserver(currentObserver) + } + } + + return suspendCancellableCoroutine { continuation -> + continuation.invokeOnCancellation { removeObserver() } + + observer = Observer { t -> + if (check(t)) { + removeObserver() + continuation.resume(t) + } + } + + liveData.observeForever(observer!!) + } +} + +suspend fun LiveData.waitForNullableValue(): T? { + return waitUntilValueMatches { true } +} + +suspend fun LiveData.waitForNonNullValue(): T { + return waitUntilValueMatches { it != null }!! +} diff --git a/app/src/main/java/io/timelimit/android/livedata/IgnoreUnchanged.kt b/app/src/main/java/io/timelimit/android/livedata/IgnoreUnchanged.kt new file mode 100644 index 0000000..1e0b52e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/IgnoreUnchanged.kt @@ -0,0 +1,33 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import androidx.lifecycle.LiveData +import androidx.lifecycle.MediatorLiveData + +fun LiveData.ignoreUnchanged(): LiveData { + val result = MediatorLiveData() + var hadValue = false + + result.addSource(this) { + if (it != result.value || !hadValue) { + hadValue = true + result.value = it + } + } + + return result +} diff --git a/app/src/main/java/io/timelimit/android/livedata/LiveDataFromFunction.kt b/app/src/main/java/io/timelimit/android/livedata/LiveDataFromFunction.kt new file mode 100644 index 0000000..9344528 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/LiveDataFromFunction.kt @@ -0,0 +1,43 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import androidx.lifecycle.LiveData +import io.timelimit.android.async.Threads + +fun liveDataFromFunction(pollInterval: Long = 1000L, function: () -> X): LiveData = object: LiveData() { + val refresh = Runnable { + refresh() + } + + fun refresh() { + value = function() + + Threads.mainThreadHandler.postDelayed(refresh, pollInterval) + } + + override fun onActive() { + super.onActive() + + refresh() + } + + override fun onInactive() { + super.onInactive() + + Threads.mainThreadHandler.removeCallbacks(refresh) + } +}.ignoreUnchanged() diff --git a/app/src/main/java/io/timelimit/android/livedata/Map.kt b/app/src/main/java/io/timelimit/android/livedata/Map.kt new file mode 100644 index 0000000..fb6c317 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/Map.kt @@ -0,0 +1,36 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import androidx.arch.core.util.Function +import androidx.lifecycle.LiveData +import androidx.lifecycle.Transformations + +fun LiveData.map(function: Function): LiveData { + return Transformations.map(this, function) +} + +fun LiveData.map(function: (X) -> Y): LiveData { + return Transformations.map(this, function) +} + +fun LiveData.switchMap(function: Function>): LiveData { + return Transformations.switchMap(this, function) +} + +fun LiveData.switchMap(function: (X) -> LiveData): LiveData { + return Transformations.switchMap(this, function) +} diff --git a/app/src/main/java/io/timelimit/android/livedata/MergeLiveData.kt b/app/src/main/java/io/timelimit/android/livedata/MergeLiveData.kt new file mode 100644 index 0000000..4bb7d5c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/MergeLiveData.kt @@ -0,0 +1,140 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import androidx.lifecycle.LiveData +import androidx.lifecycle.MediatorLiveData + +fun mergeLiveData(d1: LiveData, d2: LiveData): LiveData> { + val result = MediatorLiveData>() + result.value = Pair(null, null) + + result.addSource(d1) { + result.value = result.value!!.copy(first = it) + } + + result.addSource(d2) { + result.value = result.value!!.copy(second = it) + } + + return result +} + +fun mergeLiveData(d1: LiveData, d2: LiveData, d3: LiveData): LiveData> { + val result = MediatorLiveData>() + result.value = Triple(null, null, null) + + result.addSource(d1) { + result.value = result.value!!.copy(first = it) + } + + result.addSource(d2) { + result.value = result.value!!.copy(second = it) + } + + result.addSource(d3) { + result.value = result.value!!.copy(third = it) + } + + return result +} + +fun mergeLiveData(d1: LiveData, d2: LiveData, d3: LiveData, d4: LiveData): LiveData> { + val result = MediatorLiveData>() + result.value = FourTuple(null, null, null, null) + + result.addSource(d1) { + result.value = result.value!!.copy(first = it) + } + + result.addSource(d2) { + result.value = result.value!!.copy(second = it) + } + + result.addSource(d3) { + result.value = result.value!!.copy(third = it) + } + + result.addSource(d4) { + result.value = result.value!!.copy(forth = it) + } + + return result +} + +data class FourTuple(val first: A, val second: B, val third: C, val forth: D) + +fun mergeLiveData(d1: LiveData, d2: LiveData, d3: LiveData, d4: LiveData, d5: LiveData): LiveData> { + val result = MediatorLiveData>() + result.value = FiveTuple(null, null, null, null, null) + + result.addSource(d1) { + result.value = result.value!!.copy(first = it) + } + + result.addSource(d2) { + result.value = result.value!!.copy(second = it) + } + + result.addSource(d3) { + result.value = result.value!!.copy(third = it) + } + + result.addSource(d4) { + result.value = result.value!!.copy(forth = it) + } + + result.addSource(d5) { + result.value = result.value!!.copy(fifth = it) + } + + return result +} + +data class FiveTuple(val first: A, val second: B, val third: C, val forth: D, val fifth: E) + +fun mergeLiveData(d1: LiveData, d2: LiveData, d3: LiveData, d4: LiveData, d5: LiveData, d6: LiveData): LiveData> { + val result = MediatorLiveData>() + result.value = SixTuple(null, null, null, null, null, null) + + result.addSource(d1) { + result.value = result.value!!.copy(first = it) + } + + result.addSource(d2) { + result.value = result.value!!.copy(second = it) + } + + result.addSource(d3) { + result.value = result.value!!.copy(third = it) + } + + result.addSource(d4) { + result.value = result.value!!.copy(forth = it) + } + + result.addSource(d5) { + result.value = result.value!!.copy(fifth = it) + } + + result.addSource(d6) { + result.value = result.value!!.copy(sixth = it) + } + + return result +} + +data class SixTuple(val first: A, val second: B, val third: C, val forth: D, val fifth: E, val sixth: F) diff --git a/app/src/main/java/io/timelimit/android/livedata/MultiKeyLiveDataCache.kt b/app/src/main/java/io/timelimit/android/livedata/MultiKeyLiveDataCache.kt new file mode 100644 index 0000000..a62ce28 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/MultiKeyLiveDataCache.kt @@ -0,0 +1,153 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import java.util.concurrent.ConcurrentHashMap + +abstract class LiveDataCache { + abstract fun reportLoopDone() + abstract fun removeAllItems() +} + +class SingleItemLiveDataCache(private val liveData: LiveData): LiveDataCache() { + private val dummyObserver = Observer { + // do nothing + } + + private var isObserving = false + private var wasUsed = false + + fun read(): LiveData { + if (!isObserving) { + liveData.observeForever(dummyObserver) + isObserving = true + } + + wasUsed = true + + return liveData + } + + override fun removeAllItems() { + if (isObserving) { + liveData.removeObserver(dummyObserver) + isObserving = false + } + } + + override fun reportLoopDone() { + if (isObserving && !wasUsed) { + removeAllItems() + } + + wasUsed = false + } +} + +class SingleItemLiveDataCacheWithRequery(private val liveDataCreator: () -> LiveData): LiveDataCache() { + private val dummyObserver = Observer { + // do nothing + } + + private var wasUsed = false + private var instance: LiveData? = null + + fun read(): LiveData { + if (instance == null) { + instance = liveDataCreator() + instance!!.observeForever(dummyObserver) + } + + wasUsed = true + + return instance!! + } + + override fun removeAllItems() { + if (instance != null) { + instance!!.removeObserver(dummyObserver) + instance = null + } + } + + override fun reportLoopDone() { + if (instance != null && !wasUsed) { + removeAllItems() + } + + wasUsed = false + } +} + +abstract class MultiKeyLiveDataCache: LiveDataCache() { + class ItemWrapper(val value: LiveData, var used: Boolean) + + private val items = ConcurrentHashMap>() + + private val dummyObserver = Observer { + // do nothing + } + + protected abstract fun createValue(key: K): LiveData + + fun get(key: K): LiveData { + val oldItem = items[key] + + if (oldItem != null) { + oldItem.used = true + + return oldItem.value + } else { + val newItem = ItemWrapper(createValue(key), true) + newItem.value.observeForever(dummyObserver) + + items[key] = newItem + + return newItem.value + } + } + + override fun reportLoopDone() { + items.forEach { + if (it.value.used) { + it.value.used = false + } else { + it.value.value.removeObserver(dummyObserver) + items.remove(it.key) + } + } + } + + override fun removeAllItems() { + items.forEach { + it.value.value.removeObserver(dummyObserver) + } + + items.clear() + } +} + +class LiveDataCaches(private val caches: Array) { + fun reportLoopDone() { + caches.forEach { it.reportLoopDone() } + } + + fun removeAllItems() { + caches.forEach { it.removeAllItems() } + } +} diff --git a/app/src/main/java/io/timelimit/android/livedata/SetTemporarily.kt b/app/src/main/java/io/timelimit/android/livedata/SetTemporarily.kt new file mode 100644 index 0000000..6970ce0 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/SetTemporarily.kt @@ -0,0 +1,36 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.livedata + +import androidx.lifecycle.MutableLiveData +import java.io.Closeable +import java.util.concurrent.atomic.AtomicBoolean + +fun MutableLiveData.setTemporarily(newValue: T): Closeable { + val data = this + val oldValue = data.value + val closed = AtomicBoolean(false) + + this.value = newValue + + return object: Closeable { + override fun close() { + if (closed.compareAndSet(false, true)) { + data.value = oldValue + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/AndroidAppLogic.kt b/app/src/main/java/io/timelimit/android/logic/AndroidAppLogic.kt new file mode 100644 index 0000000..5c3aeae --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/AndroidAppLogic.kt @@ -0,0 +1,85 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.content.Context +import android.os.Handler +import android.os.Looper +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.RoomDatabase +import io.timelimit.android.data.backup.DatabaseBackup +import io.timelimit.android.integration.platform.android.AndroidIntegration +import io.timelimit.android.integration.time.RealTimeApi +import io.timelimit.android.sync.network.api.HttpServerApi +import io.timelimit.android.sync.websocket.NetworkStatusUtil +import io.timelimit.android.sync.websocket.SocketIoWebsocketClient +import java.util.concurrent.CountDownLatch + +object AndroidAppLogic { + private var instance: AppLogic? = null + private val handler = Handler(Looper.getMainLooper()) + + fun with(context: Context): AppLogic { + val safeContext = context.applicationContext + + if (Looper.getMainLooper() == Looper.myLooper()) { + // at the UI thread + if (instance == null) { + val isInitialized = MutableLiveData().apply { value = false } + + instance = AppLogic( + platformIntegration = AndroidIntegration(safeContext), + timeApi = RealTimeApi, + database = RoomDatabase.with(safeContext), + serverCreator = { url -> + HttpServerApi.createInstance( + if (url.isEmpty()) { + BuildConfig.serverUrl + } else { + url + } + ) + }, + networkStatus = NetworkStatusUtil.getSystemNetworkStatusLive(safeContext), + websocketClientCreator = SocketIoWebsocketClient.creator, + context = safeContext, + isInitialized = isInitialized + ) + + runAsync { + DatabaseBackup.with(safeContext).tryRestoreDatabaseBackupAsyncAndWait() + isInitialized.value = true + } + } + } else { + // at a background thread + if (instance == null) { + val latch = CountDownLatch(1) + + handler.post { + with(context) + latch.countDown() + } + + latch.await() + } + } + + return instance!! + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/AppAffectedByPrimaryDeviceUtil.kt b/app/src/main/java/io/timelimit/android/logic/AppAffectedByPrimaryDeviceUtil.kt new file mode 100644 index 0000000..861cfa7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/AppAffectedByPrimaryDeviceUtil.kt @@ -0,0 +1,82 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.waitForNonNullValue +import io.timelimit.android.livedata.waitForNullableValue + +object AppAffectedByPrimaryDeviceUtil { + suspend fun isCurrentAppAffectedByPrimaryDevice( + logic: AppLogic + ): Boolean { + val user = logic.deviceUserEntry.waitForNullableValue() + ?: throw NullPointerException("no user is signed in") + + if (user.type != UserType.Child) { + throw IllegalStateException("no child is signed in") + } + + if (user.relaxPrimaryDevice) { + if (logic.fullVersion.shouldProvideFullVersionFunctions.waitForNonNullValue() == true) { + return false + } + } + + val currentApp = try { + logic.platformIntegration.getForegroundAppPackageName() + } catch (ex: SecurityException) { + null + } + + if (currentApp == null) { + return false + } + + val categories = logic.database.category().getCategoriesByChildId(user.id).waitForNonNullValue() + val categoryId = logic.database.categoryApp().getCategoryApp( + categoryIds = categories.map { it.id }, + packageName = currentApp + ).waitForNullableValue()?.categoryId ?: user.categoryForNotAssignedApps + + val category = categories.find { it.id == categoryId } + val parentCategory = categories.find { it.id == category?.parentCategoryId } + + if (category == null) { + return false + } + + // check blocked time areas + if ( + (category.blockedMinutesInWeek.dataNotToModify.isEmpty == false) || + (parentCategory?.blockedMinutesInWeek?.dataNotToModify?.isEmpty == false) + ) { + return true + } + + // check time limit rules + val rules = logic.database.timeLimitRules().getTimeLimitRulesByCategories( + categoryIds = listOf(categoryId) + + (if (parentCategory != null) listOf(parentCategory.id) else emptyList()) + ).waitForNonNullValue() + + if (rules.isNotEmpty()) { + return true + } + + return false + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/logic/AppLogic.kt b/app/src/main/java/io/timelimit/android/logic/AppLogic.kt new file mode 100644 index 0000000..acb51f6 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/AppLogic.kt @@ -0,0 +1,102 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.content.Context +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Transformations +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.User +import io.timelimit.android.integration.platform.PlatformIntegration +import io.timelimit.android.integration.time.TimeApi +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.sync.SyncUtil +import io.timelimit.android.sync.network.api.ServerApi +import io.timelimit.android.sync.websocket.NetworkStatus +import io.timelimit.android.sync.websocket.WebsocketClientCreator + +class AppLogic( + val platformIntegration: PlatformIntegration, + val timeApi: TimeApi, + val database: Database, + val serverCreator: (serverUrl: String) -> ServerApi, + val networkStatus: LiveData, + websocketClientCreator: WebsocketClientCreator, + val context: Context, + val isInitialized: LiveData +) { + val enable = MutableLiveData().apply { value = true } + + val deviceId = database.config().getOwnDeviceId() + + val deviceEntry = Transformations.switchMap (deviceId) { + if (it == null) { + liveDataFromValue(null) + } else { + database.device().getDeviceById(it) + } + }.ignoreUnchanged() + + val deviceEntryIfEnabled = enable.switchMap { + if (it == null || it == false) { + liveDataFromValue(null as Device?) + } else { + deviceEntry + } + } + + val deviceUserId: LiveData = Transformations.map(deviceEntry) { it?.currentUserId ?: "" } + + val deviceUserEntry = deviceUserId.switchMap { + if (it == "") { + liveDataFromValue(null as User?) + } else { + database.user().getUserByIdLive(it) + } + }.ignoreUnchanged() + + val serverLogic = ServerLogic(this) + val defaultUserLogic = DefaultUserLogic(this) + val realTimeLogic = RealTimeLogic(this) + val fullVersion = FullVersionLogic(this) + val currentDeviceLogic = CurrentDeviceLogic(this) + val backgroundTaskLogic = BackgroundTaskLogic(this) + val appSetupLogic = AppSetupLogic(this) + + private val isConnectedInternal = MutableLiveData().apply { value = false } + val isConnected = isConnectedInternal.castDown() + val syncUtil = SyncUtil(this) + val websocket = WebsocketClientLogic( + appLogic = this, + isConnectedInternal = isConnectedInternal, + websocketClientCreator = websocketClientCreator + ) + + init { + SyncInstalledAppsLogic(this) + } + + val manipulationLogic = ManipulationLogic(this) + + fun shutdown() { + enable.value = false + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/AppSetupLogic.kt b/app/src/main/java/io/timelimit/android/logic/AppSetupLogic.kt new file mode 100644 index 0000000..ab2fbcc --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/AppSetupLogic.kt @@ -0,0 +1,225 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.content.Context +import com.jaredrummler.android.device.DeviceName +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.crypto.PasswordHashing +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.backup.DatabaseBackup +import io.timelimit.android.data.customtypes.ImmutableBitmask +import io.timelimit.android.data.model.* +import io.timelimit.android.integration.platform.NewPermissionStatus +import io.timelimit.android.integration.platform.ProtectionLevel +import io.timelimit.android.integration.platform.RuntimePermissionStatus +import io.timelimit.android.ui.user.create.DefaultCategories +import java.util.* + +class AppSetupLogic(private val appLogic: AppLogic) { + suspend fun setupForLocalUse(parentPassword: String, networkTimeVerification: NetworkTime, context: Context) { + Threads.database.executeAndWait(Runnable { + run { + // assert that the device is not yet configured + val oldDeviceId = appLogic.database.config().getOwnDeviceIdSync() + + if (oldDeviceId != null) { + throw IllegalStateException("already configured") + } + } + + val ownDeviceId = IdGenerator.generateId() + val parentUserId = IdGenerator.generateId() + val childUserId = IdGenerator.generateId() + val allowedAppsCategoryId = IdGenerator.generateId() + val allowedGamesCategoryId = IdGenerator.generateId() + + appLogic.database.beginTransaction() + try { + run { + val customServerUrl = appLogic.database.config().getCustomServerUrlSync() + + // just for safety: delete everything except the custom server url + appLogic.database.deleteAllData() + + appLogic.database.config().setCustomServerUrlSync(customServerUrl) + } + + run { + // set device id + appLogic.database.config().setOwnDeviceIdSync(ownDeviceId) + } + + val timeZone = appLogic.timeApi.getSystemTimeZone().id + + run { + // add device + val deviceName = DeviceName.getDeviceName() + + val device = Device( + id = ownDeviceId, + name = deviceName, + model = deviceName, + addedAt = appLogic.timeApi.getCurrentTimeInMillis(), + currentUserId = childUserId, + installedAppsVersion = "", + networkTime = networkTimeVerification, + currentProtectionLevel = ProtectionLevel.None, + highestProtectionLevel = ProtectionLevel.None, + currentNotificationAccessPermission = NewPermissionStatus.NotGranted, + highestNotificationAccessPermission = NewPermissionStatus.NotGranted, + currentUsageStatsPermission = RuntimePermissionStatus.NotGranted, + highestUsageStatsPermission = RuntimePermissionStatus.NotGranted, + currentAppVersion = 0, + highestAppVersion = 0, + manipulationTriedDisablingDeviceAdmin = false, + manipulationDidReboot = false, + hadManipulation = false, + didReportUninstall = false, + isUserKeptSignedIn = false, + showDeviceConnected = false, + defaultUser = "", + defaultUserTimeout = 0, + considerRebootManipulation = false + ) + + appLogic.database.device().addDeviceSync(device) + } + + run { + // add child + + val child = User( + id = childUserId, + name = context.getString(R.string.setup_username_child), + password = "", + secondPasswordSalt = "", + type = UserType.Child, + timeZone = timeZone, + disableLimitsUntil = 0, + mail = "", + currentDevice = "", + categoryForNotAssignedApps = "", + relaxPrimaryDevice = false, + mailNotificationFlags = 0 + ) + + appLogic.database.user().addUserSync(child) + } + + run { + // add parent + + val parent = User( + id = parentUserId, + name = context.getString(R.string.setup_username_parent), + password = PasswordHashing.hashSync(parentPassword), + secondPasswordSalt = PasswordHashing.generateSalt(), + type = UserType.Parent, + timeZone = timeZone, + disableLimitsUntil = 0, + mail = "", + currentDevice = "", + categoryForNotAssignedApps = "", + relaxPrimaryDevice = false, + mailNotificationFlags = 0 + ) + + appLogic.database.user().addUserSync(parent) + } + + val installedApps = appLogic.platformIntegration.getLocalApps(ownDeviceId) + + // add installed apps + appLogic.database.app().addAppsSync(installedApps) + + val defaultCategories = DefaultCategories.with(context) + + // NOTE: the default config is created at the AddUserModel and at the AppSetupLogic + run { + // add starter categories + appLogic.database.category().addCategory(Category( + id = allowedAppsCategoryId, + childId = childUserId, + title = defaultCategories.allowedAppsTitle, + blockedMinutesInWeek = ImmutableBitmask((BitSet())), + extraTimeInMillis = 0, + temporarilyBlocked = false, + baseVersion = "", + assignedAppsVersion = "", + timeLimitRulesVersion = "", + usedTimesVersion = "", + parentCategoryId = "" + )) + + appLogic.database.category().addCategory(Category( + id = allowedGamesCategoryId, + childId = childUserId, + title = defaultCategories.allowedGamesTitle, + blockedMinutesInWeek = defaultCategories.allowedGamesBlockedTimes, + extraTimeInMillis = 0, + temporarilyBlocked = false, + baseVersion = "", + assignedAppsVersion = "", + timeLimitRulesVersion = "", + usedTimesVersion = "", + parentCategoryId = "" + )) + + // add default allowed apps + appLogic.database.categoryApp().addCategoryAppsSync( + installedApps + .filter { it.recommendation == AppRecommendation.Whitelist } + .map { + CategoryApp( + categoryId = allowedAppsCategoryId, + packageName = it.packageName + ) + } + ) + + // add default time limit rules + defaultCategories.generateGamesTimeLimitRules(allowedGamesCategoryId).forEach { rule -> + appLogic.database.timeLimitRules().addTimeLimitRule(rule) + } + } + + appLogic.database.setTransactionSuccessful() + } finally { + appLogic.database.endTransaction() + } + }) + + DatabaseBackup.with(appLogic.context).tryCreateDatabaseBackupAsync() + } + + suspend fun dangerousResetApp() { + Threads.database.executeAndWait(Runnable { + // this is already wrapped in a transaction + appLogic.database.deleteAllData() + }) + + // delete the old config + DatabaseBackup.with(appLogic.context).tryCreateDatabaseBackupAsync() + } + + suspend fun dangerousRemoteReset() { + appLogic.platformIntegration.showRemoteResetNotification() + dangerousResetApp() + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/BackgroundTaskLogic.kt b/app/src/main/java/io/timelimit/android/logic/BackgroundTaskLogic.kt new file mode 100644 index 0000000..350c99d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/BackgroundTaskLogic.kt @@ -0,0 +1,574 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.util.Log +import android.util.SparseArray +import android.util.SparseLongArray +import androidx.lifecycle.LiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.coroutines.runAsyncExpectForever +import io.timelimit.android.data.backup.DatabaseBackup +import io.timelimit.android.data.model.* +import io.timelimit.android.date.DateInTimezone +import io.timelimit.android.date.getMinuteOfWeek +import io.timelimit.android.integration.platform.AppStatusMessage +import io.timelimit.android.integration.platform.ProtectionLevel +import io.timelimit.android.integration.platform.android.AndroidIntegrationApps +import io.timelimit.android.livedata.* +import io.timelimit.android.sync.actions.UpdateDeviceStatusAction +import io.timelimit.android.sync.actions.apply.ApplyActionUtil +import io.timelimit.android.ui.IsAppInForeground +import io.timelimit.android.util.TimeTextUtil +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.util.* + +class BackgroundTaskLogic(val appLogic: AppLogic) { + companion object { + private const val CHECK_PERMISSION_INTERVAL = 10 * 1000L // all 10 seconds + private const val BACKGROUND_SERVICE_INTERVAL = 100L // all 100 ms + private const val MAX_USED_TIME_PER_ROUND = 1000 // 1 second + private const val LOG_TAG = "BackgroundTaskLogic" + } + + private val temporarilyAllowedApps = appLogic.deviceId.switchMap { + if (it != null) { + appLogic.database.temporarilyAllowedApp().getTemporarilyAllowedApps(it) + } else { + liveDataFromValue(Collections.emptyList()) + } + } + + init { + runAsyncExpectForever { backgroundServiceLoop() } + runAsyncExpectForever { syncDeviceStatusLoop() } + runAsyncExpectForever { backupDatabaseLoop() } + runAsync { + // this is effective after an reboot + + if (appLogic.deviceEntryIfEnabled.waitForNullableValue() != null) { + appLogic.platformIntegration.setEnableSystemLockdown(true) + } + } + + appLogic.deviceEntryIfEnabled + .map { it?.id } + .ignoreUnchanged() + .observeForever { + _ -> + + runAsync { + syncInstalledAppVersion() + } + } + + temporarilyAllowedApps.map { it.isNotEmpty() }.ignoreUnchanged().observeForever { + appLogic.platformIntegration.setShowNotificationToRevokeTemporarilyAllowedApps(it!!) + } + } + + private val deviceUserEntryLive = SingleItemLiveDataCache(appLogic.deviceUserEntry.ignoreUnchanged()) + private val isThisDeviceTheCurrentDeviceLive = SingleItemLiveDataCache(appLogic.currentDeviceLogic.isThisDeviceTheCurrentDevice) + private val childCategories = object: MultiKeyLiveDataCache, String?>() { + // key = child id + override fun createValue(key: String?): LiveData> { + if (key == null) { + // this should rarely happen + return liveDataFromValue(Collections.emptyList()) + } else { + return appLogic.database.category().getCategoriesByChildId(key).ignoreUnchanged() + } + } + } + private val appCategories = object: MultiKeyLiveDataCache>>() { + // key = package name, category ids + override fun createValue(key: Pair>): LiveData { + return appLogic.database.categoryApp().getCategoryApp(key.second, key.first) + } + } + private val timeLimitRules = object: MultiKeyLiveDataCache, String>() { + override fun createValue(key: String): LiveData> { + return appLogic.database.timeLimitRules().getTimeLimitRulesByCategory(key) + } + } + private val usedTimesOfCategoryAndWeekByFirstDayOfWeek = object: MultiKeyLiveDataCache, Pair>() { + override fun createValue(key: Pair): LiveData> { + return appLogic.database.usedTimes().getUsedTimesOfWeek(key.first, key.second) + } + } + private val shouldDoAutomaticSignOut = SingleItemLiveDataCacheWithRequery { -> appLogic.defaultUserLogic.hasAutomaticSignOut()} + + private val liveDataCaches = LiveDataCaches(arrayOf( + deviceUserEntryLive, + childCategories, + appCategories, + timeLimitRules, + usedTimesOfCategoryAndWeekByFirstDayOfWeek, + shouldDoAutomaticSignOut + )) + + private var usedTimeUpdateHelper: UsedTimeItemBatchUpdateHelper? = null + private var previousMainLogicExecutionTime = 0 + private var previousMainLoopEndTime = 0L + + private val appTitleCache = QueryAppTitleCache(appLogic.platformIntegration) + + private suspend fun backgroundServiceLoop() { + val realTime = RealTime.newInstance() + + while (true) { + // app must be enabled + if (!appLogic.enable.waitForNonNullValue()) { + usedTimeUpdateHelper?.commit(appLogic) + liveDataCaches.removeAllItems() + appLogic.platformIntegration.setAppStatusMessage(null) + appLogic.enable.waitUntilValueMatches { it == true } + + continue + } + + // device must be used by a child + val deviceUserEntry = deviceUserEntryLive.read().waitForNullableValue() + + if (deviceUserEntry == null || deviceUserEntry.type != UserType.Child) { + usedTimeUpdateHelper?.commit(appLogic) + val shouldDoAutomaticSignOut = shouldDoAutomaticSignOut.read() + + if (shouldDoAutomaticSignOut.waitForNonNullValue()) { + appLogic.defaultUserLogic.reportScreenOn(appLogic.platformIntegration.isScreenOn()) + + appLogic.platformIntegration.setAppStatusMessage( + if (IsAppInForeground.isRunning()) + null + else + AppStatusMessage( + title = appLogic.context.getString(R.string.background_logic_timeout_title), + text = appLogic.context.getString(R.string.background_logic_timeout_text) + ) + ) + + liveDataCaches.reportLoopDone() + appLogic.timeApi.sleep(BACKGROUND_SERVICE_INTERVAL) + } else { + liveDataCaches.removeAllItems() + appLogic.platformIntegration.setAppStatusMessage(null) + + val isChildSignedIn = deviceUserEntryLive.read().map { it != null && it.type == UserType.Child } + + isChildSignedIn.or(shouldDoAutomaticSignOut).waitUntilValueMatches { it == true } + } + + continue + } + + // loop logic + try { + // get the current time + appLogic.realTimeLogic.getRealTime(realTime) + + // get the categories + val categories = childCategories.get(deviceUserEntry.id).waitForNonNullValue() + val temporarilyAllowedApps = temporarilyAllowedApps.waitForNonNullValue() + + // get the current status + val isScreenOn = appLogic.platformIntegration.isScreenOn() + + appLogic.defaultUserLogic.reportScreenOn(isScreenOn) + + if (!isScreenOn) { + if (temporarilyAllowedApps.isNotEmpty()) { + resetTemporarilyAllowedApps() + } + } + + val foregroundAppPackageName = appLogic.platformIntegration.getForegroundAppPackageName() + // the following is not executed if the permission is missing + + if (foregroundAppPackageName == BuildConfig.APPLICATION_ID) { + // this app itself runs now -> no need for an status message + usedTimeUpdateHelper?.commit(appLogic) + appLogic.platformIntegration.setAppStatusMessage(null) + } else if (foregroundAppPackageName != null && AndroidIntegrationApps.ignoredApps.contains(foregroundAppPackageName)) { + usedTimeUpdateHelper?.commit(appLogic) + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + appTitleCache.query(foregroundAppPackageName), + appLogic.context.getString(R.string.background_logic_whitelisted) + )) + } else if (foregroundAppPackageName != null && temporarilyAllowedApps.contains(foregroundAppPackageName)) { + usedTimeUpdateHelper?.commit(appLogic) + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + appTitleCache.query(foregroundAppPackageName), + appLogic.context.getString(R.string.background_logic_temporarily_allowed) + )) + } else if (foregroundAppPackageName != null) { + val appCategory = appCategories.get(Pair(foregroundAppPackageName, categories.map { it.id })).waitForNullableValue() + val category = categories.find { it.id == appCategory?.categoryId } + ?: categories.find { it.id == deviceUserEntry.categoryForNotAssignedApps } + val parentCategory = categories.find { it.id == category?.parentCategoryId } + + if (category == null) { + usedTimeUpdateHelper?.commit(appLogic) + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + title = appTitleCache.query(foregroundAppPackageName), + text = appLogic.context.getString(R.string.background_logic_opening_lockscreen) + )) + appLogic.platformIntegration.setSuspendedApps(listOf(foregroundAppPackageName), true) + appLogic.platformIntegration.showAppLockScreen(foregroundAppPackageName) + } else if (category.temporarilyBlocked or (parentCategory?.temporarilyBlocked == true)) { + usedTimeUpdateHelper?.commit(appLogic) + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + title = appTitleCache.query(foregroundAppPackageName), + text = appLogic.context.getString(R.string.background_logic_opening_lockscreen) + )) + appLogic.platformIntegration.showAppLockScreen(foregroundAppPackageName) + } else { + val nowTimestamp = realTime.timeInMillis + val nowTimezone = TimeZone.getTimeZone(deviceUserEntry.timeZone) + + val nowDate = DateInTimezone.newInstance(nowTimestamp, nowTimezone) + val minuteOfWeek = getMinuteOfWeek(nowTimestamp, nowTimezone) + + // disable time limits temporarily feature + if (realTime.shouldTrustTimeTemporarily && nowTimestamp < deviceUserEntry.disableLimitsUntil) { + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + title = appTitleCache.query(foregroundAppPackageName), + text = appLogic.context.getString(R.string.background_logic_limits_disabled) + )) + } else if ( + // check blocked time areas + // directly blocked + (category.blockedMinutesInWeek.read(minuteOfWeek)) or + (parentCategory?.blockedMinutesInWeek?.read(minuteOfWeek) == true) or + // or no safe time + ( + ( + (category.blockedMinutesInWeek.dataNotToModify.isEmpty == false) or + (parentCategory?.blockedMinutesInWeek?.dataNotToModify?.isEmpty == false) + ) && + (!realTime.shouldTrustTimeTemporarily) + ) + ) { + usedTimeUpdateHelper?.commit(appLogic) + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + title = appTitleCache.query(foregroundAppPackageName), + text = appLogic.context.getString(R.string.background_logic_opening_lockscreen) + )) + appLogic.platformIntegration.showAppLockScreen(foregroundAppPackageName) + } else { + // check time limits + val rules = timeLimitRules.get(category.id).waitForNonNullValue() + val parentRules = parentCategory?.let { + timeLimitRules.get(it.id).waitForNonNullValue() + } ?: emptyList() + + if (rules.isEmpty() and parentRules.isEmpty()) { + // unlimited + usedTimeUpdateHelper?.commit(appLogic) + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + category.title + " - " + appTitleCache.query(foregroundAppPackageName), + appLogic.context.getString(R.string.background_logic_no_timelimit) + )) + } else { + val isCurrentDevice = isThisDeviceTheCurrentDeviceLive.read().waitForNonNullValue() + + if (!isCurrentDevice) { + usedTimeUpdateHelper?.commit(appLogic) + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + title = appTitleCache.query(foregroundAppPackageName), + text = appLogic.context.getString(R.string.background_logic_opening_lockscreen) + )) + appLogic.platformIntegration.showAppLockScreen(foregroundAppPackageName) + } else if (realTime.shouldTrustTimeTemporarily) { + val usedTimes = usedTimesOfCategoryAndWeekByFirstDayOfWeek.get(Pair(category.id, nowDate.dayOfEpoch - nowDate.dayOfWeek)).waitForNonNullValue() + val parentUsedTimes = parentCategory?.let { + usedTimesOfCategoryAndWeekByFirstDayOfWeek.get(Pair(it.id, nowDate.dayOfEpoch - nowDate.dayOfWeek)).waitForNonNullValue() + } ?: SparseArray() + + val newUsedTimeItemBatchUpdateHelper = UsedTimeItemBatchUpdateHelper.eventuallyUpdateInstance( + date = nowDate, + childCategoryId = category.id, + parentCategoryId = parentCategory?.id, + oldInstance = usedTimeUpdateHelper, + usedTimeItemForDayChild = usedTimes.get(nowDate.dayOfWeek), + usedTimeItemForDayParent = parentUsedTimes.get(nowDate.dayOfWeek), + logic = appLogic + ) + usedTimeUpdateHelper = newUsedTimeItemBatchUpdateHelper + + fun buildUsedTimesSparseArray(items: SparseArray, isParentCategory: Boolean): SparseLongArray { + val result = SparseLongArray() + + for (i in 0..6) { + val usedTimesItem = items[i]?.usedMillis + + if (newUsedTimeItemBatchUpdateHelper.date.dayOfWeek == i) { + result.put( + i, + if (isParentCategory) + newUsedTimeItemBatchUpdateHelper.getTotalUsedTimeParent() + else + newUsedTimeItemBatchUpdateHelper.getTotalUsedTimeChild() + ) + } else { + result.put(i, usedTimesItem ?: 0) + } + } + + return result + } + + val remainingChild = RemainingTime.getRemainingTime( + nowDate.dayOfWeek, + buildUsedTimesSparseArray(usedTimes, isParentCategory = false), + rules, + Math.max(0, category.extraTimeInMillis - newUsedTimeItemBatchUpdateHelper.getCachedExtraTimeToSubtract()) + ) + + val remainingParent = parentCategory?.let { + RemainingTime.getRemainingTime( + nowDate.dayOfWeek, + buildUsedTimesSparseArray(parentUsedTimes, isParentCategory = true), + parentRules, + Math.max(0, parentCategory.extraTimeInMillis - newUsedTimeItemBatchUpdateHelper.getCachedExtraTimeToSubtract()) + ) + } + + val remaining = RemainingTime.min(remainingChild, remainingParent) + + if (remaining == null) { + // unlimited + + usedTimeUpdateHelper?.commit(appLogic) + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + category.title + " - " + appTitleCache.query(foregroundAppPackageName), + appLogic.context.getString(R.string.background_logic_no_timelimit) + )) + } else { + // time limited + if (remaining.includingExtraTime > 0) { + if (remaining.default == 0L) { + // using extra time + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + category.title + " - " + appTitleCache.query(foregroundAppPackageName), + appLogic.context.getString(R.string.background_logic_using_extra_time, TimeTextUtil.remaining(remaining.includingExtraTime.toInt(), appLogic.context)) + )) + + if (isScreenOn) { + newUsedTimeItemBatchUpdateHelper.addUsedTime( + Math.min(previousMainLogicExecutionTime, MAX_USED_TIME_PER_ROUND), // never save more than a second of used time + true, + appLogic + ) + } + } else { + // using normal contingent + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + category.title + " - " + appTitleCache.query(foregroundAppPackageName), + TimeTextUtil.remaining(remaining.default.toInt(), appLogic.context) + )) + + if (isScreenOn) { + newUsedTimeItemBatchUpdateHelper.addUsedTime( + Math.min(previousMainLogicExecutionTime, MAX_USED_TIME_PER_ROUND), // never save more than a second of used time + false, + appLogic + ) + } + } + } else { + // there is not time anymore + + newUsedTimeItemBatchUpdateHelper.commit(appLogic) + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + title = appTitleCache.query(foregroundAppPackageName), + text = appLogic.context.getString(R.string.background_logic_opening_lockscreen) + )) + appLogic.platformIntegration.showAppLockScreen(foregroundAppPackageName) + } + } + } else { + // if should not trust the time temporarily + + usedTimeUpdateHelper?.commit(appLogic) + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + title = appTitleCache.query(foregroundAppPackageName), + text = appLogic.context.getString(R.string.background_logic_opening_lockscreen) + )) + appLogic.platformIntegration.showAppLockScreen(foregroundAppPackageName) + } + } + } + } + } else { + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + appLogic.context.getString(R.string.background_logic_idle_title), + appLogic.context.getString(R.string.background_logic_idle_text) + )) + } + } catch (ex: SecurityException) { + // this is handled by an other main loop (with a delay) + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + appLogic.context.getString(R.string.background_logic_error), + appLogic.context.getString(R.string.background_logic_error_permission) + )) + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "exception during running main loop", ex) + } + + appLogic.platformIntegration.setAppStatusMessage(AppStatusMessage( + appLogic.context.getString(R.string.background_logic_error), + appLogic.context.getString(R.string.background_logic_error_internal) + )) + } + + liveDataCaches.reportLoopDone() + + // delay before running next time + val endTime = appLogic.timeApi.getCurrentUptimeInMillis() + previousMainLogicExecutionTime = (endTime - previousMainLoopEndTime).toInt() + previousMainLoopEndTime = endTime + + val timeToWait = Math.max(10, BACKGROUND_SERVICE_INTERVAL - previousMainLogicExecutionTime) + appLogic.timeApi.sleep(timeToWait) + } + } + + private suspend fun syncInstalledAppVersion() { + val currentAppVersion = BuildConfig.VERSION_CODE + val deviceEntry = appLogic.deviceEntry.waitForNullableValue() + + if (deviceEntry != null) { + if (deviceEntry.currentAppVersion != currentAppVersion) { + ApplyActionUtil.applyAppLogicAction( + UpdateDeviceStatusAction.empty.copy( + newAppVersion = currentAppVersion + ), + appLogic + ) + } + } + } + + fun syncDeviceStatusAsync() { + runAsync { + syncDeviceStatus() + } + } + + private suspend fun syncDeviceStatusLoop() { + while (true) { + appLogic.deviceEntryIfEnabled.waitUntilValueMatches { it != null } + + syncDeviceStatus() + + appLogic.timeApi.sleep(CHECK_PERMISSION_INTERVAL) + } + } + + private val syncDeviceStatusLock = Mutex() + + fun reportDeviceReboot() { + runAsync { + val deviceEntry = appLogic.deviceEntry.waitForNullableValue() + + if (deviceEntry?.considerRebootManipulation == true) { + ApplyActionUtil.applyAppLogicAction( + UpdateDeviceStatusAction.empty.copy( + didReboot = true + ), + appLogic + ) + } + } + } + + private suspend fun syncDeviceStatus() { + syncDeviceStatusLock.withLock { + val deviceEntry = appLogic.deviceEntry.waitForNullableValue() + + if (deviceEntry != null) { + val protectionLevel = appLogic.platformIntegration.getCurrentProtectionLevel() + val usageStatsPermission = appLogic.platformIntegration.getForegroundAppPermissionStatus() + val notificationAccess = appLogic.platformIntegration.getNotificationAccessPermissionStatus() + + var changes = UpdateDeviceStatusAction.empty + + if (protectionLevel != deviceEntry.currentProtectionLevel) { + changes = changes.copy( + newProtectionLevel = protectionLevel + ) + + if (protectionLevel == ProtectionLevel.DeviceOwner) { + appLogic.platformIntegration.setEnableSystemLockdown(true) + } + } + + if (usageStatsPermission != deviceEntry.currentUsageStatsPermission) { + changes = changes.copy( + newUsageStatsPermissionStatus = usageStatsPermission + ) + } + + if (notificationAccess != deviceEntry.currentNotificationAccessPermission) { + changes = changes.copy( + newNotificationAccessPermission = notificationAccess + ) + } + + if (changes != UpdateDeviceStatusAction.empty) { + ApplyActionUtil.applyAppLogicAction(changes, appLogic) + } + } + } + } + + suspend fun resetTemporarilyAllowedApps() { + val deviceId = appLogic.deviceId.waitForNullableValue() + + if (deviceId != null) { + Threads.database.executeAndWait(Runnable { + appLogic.database.temporarilyAllowedApp().removeAllTemporarilyAllowedAppsSync(deviceId) + }) + } + } + + private suspend fun backupDatabaseLoop() { + appLogic.timeApi.sleep(1000 * 60 * 5 /* 5 minutes */) + + while (true) { + DatabaseBackup.with(appLogic.context).tryCreateDatabaseBackupAsync() + + appLogic.timeApi.sleep(1000 * 60 * 60 * 3 /* 3 hours */) + } + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/BlockingReason.kt b/app/src/main/java/io/timelimit/android/logic/BlockingReason.kt new file mode 100644 index 0000000..216d72f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/BlockingReason.kt @@ -0,0 +1,382 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.util.Log +import android.util.SparseLongArray +import androidx.lifecycle.LiveData +import androidx.lifecycle.Transformations +import io.timelimit.android.BuildConfig +import io.timelimit.android.data.model.Category +import io.timelimit.android.data.model.TimeLimitRule +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.date.DateInTimezone +import io.timelimit.android.date.getMinuteOfWeek +import io.timelimit.android.integration.platform.android.AndroidIntegrationApps +import io.timelimit.android.integration.time.TimeApi +import io.timelimit.android.livedata.* +import java.util.* + +enum class BlockingReason { + None, + NotPartOfAnCategory, + TemporarilyBlocked, + BlockedAtThisTime, + TimeOver, + TimeOverExtraTimeCanBeUsedLater, + MissingNetworkTime, + RequiresCurrentDevice +} + +class BlockingReasonUtil(private val appLogic: AppLogic) { + companion object { + private const val LOG_TAG = "BlockingReason" + } + + fun getBlockingReason(packageName: String): LiveData { + // check precondition that the app is running + + return appLogic.enable.switchMap { + enabled -> + + if (enabled == null || enabled == false) { + liveDataFromValue(BlockingReason.None) + } else { + appLogic.deviceUserEntry.switchMap { + user -> + + if (user == null || user.type != UserType.Child) { + liveDataFromValue(BlockingReason.None) + } else { + getBlockingReasonStep2(packageName, user, TimeZone.getTimeZone(user.timeZone)) + } + } + } + } + } + + private fun getBlockingReasonStep2(packageName: String, child: User, timeZone: TimeZone): LiveData { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "step 2") + } + + // check internal whitelist + if (packageName == BuildConfig.APPLICATION_ID) { + return liveDataFromValue(BlockingReason.None) + } else if (AndroidIntegrationApps.ignoredApps.contains(packageName)) { + return liveDataFromValue(BlockingReason.None) + } else { + return getBlockingReasonStep3(packageName, child, timeZone) + } + } + + private fun getBlockingReasonStep3(packageName: String, child: User, timeZone: TimeZone): LiveData { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "step 3") + } + + // check temporarily allowed Apps + return appLogic.deviceId.switchMap { + if (it != null) { + appLogic.database.temporarilyAllowedApp().getTemporarilyAllowedApps(deviceId = it) + } else { + liveDataFromValue(Collections.emptyList()) + } + }.switchMap { + temporarilyAllowedApps -> + + if (temporarilyAllowedApps.contains(packageName)) { + liveDataFromValue(BlockingReason.None) + } else { + getBlockingReasonStep4(packageName, child, timeZone) + } + } + } + + private fun getBlockingReasonStep4(packageName: String, child: User, timeZone: TimeZone): LiveData { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "step 4") + } + + return appLogic.database.category().getCategoriesByChildId(child.id).switchMap { + childCategories -> + + Transformations.map(appLogic.database.categoryApp().getCategoryApp(childCategories.map { it.id }, packageName)) { + categoryApp -> + + if (categoryApp == null) { + null + } else { + childCategories.find { it.id == categoryApp.categoryId } + } + } + }.switchMap { + categoryEntry -> + + if (categoryEntry == null) { + val defaultCategory = if (child.categoryForNotAssignedApps.isEmpty()) + liveDataFromValue(null as Category?) + else + appLogic.database.category().getCategoryByChildIdAndId(child.id, child.categoryForNotAssignedApps) + + defaultCategory.switchMap { categoryEntry2 -> + if (categoryEntry2 == null) { + liveDataFromValue(BlockingReason.NotPartOfAnCategory) + } else { + getBlockingReasonStep4Point5(categoryEntry2, child, timeZone, false) + } + } + } else { + getBlockingReasonStep4Point5(categoryEntry, child, timeZone, false) + } + } + } + + private fun getBlockingReasonStep4Point5(category: Category, child: User, timeZone: TimeZone, isParentCategory: Boolean): LiveData { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "step 4.5") + } + + if (category.temporarilyBlocked) { + return liveDataFromValue(BlockingReason.TemporarilyBlocked) + } + + val areLimitsDisabled: LiveData + + if (child.disableLimitsUntil == 0L) { + areLimitsDisabled = liveDataFromValue(false) + } else { + areLimitsDisabled = getTemporarilyTrustedTimeInMillis().map { + trustedTimeInMillis -> + + trustedTimeInMillis != null && child.disableLimitsUntil > trustedTimeInMillis + } + } + + return areLimitsDisabled.switchMap { + limitsDisabled -> + + if (limitsDisabled) { + liveDataFromValue(BlockingReason.None) + } else { + getBlockingReasonStep5(category, timeZone) + } + }.switchMap { result -> + if (result == BlockingReason.None && (!isParentCategory) && category.parentCategoryId.isNotEmpty()) { + appLogic.database.category().getCategoryByChildIdAndId(child.id, category.parentCategoryId).switchMap { parentCategory -> + if (parentCategory == null) { + liveDataFromValue(BlockingReason.None) + } else { + getBlockingReasonStep4Point5(parentCategory, child, timeZone, true) + } + } + } else { + liveDataFromValue(result) + } + } + } + + private fun getBlockingReasonStep5(category: Category, timeZone: TimeZone): LiveData { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "step 5") + } + + return Transformations.switchMap(getTrustedMinuteOfWeekLive(appLogic.timeApi, timeZone)) { + trustedMinuteOfWeek -> + + if (category.blockedMinutesInWeek.dataNotToModify.isEmpty) { + getBlockingReasonStep6(category, timeZone) + } else if (trustedMinuteOfWeek == null) { + liveDataFromValue(BlockingReason.MissingNetworkTime) + } else if (category.blockedMinutesInWeek.read(trustedMinuteOfWeek)) { + liveDataFromValue(BlockingReason.BlockedAtThisTime) + } else { + getBlockingReasonStep6(category, timeZone) + } + } + } + + private fun getBlockingReasonStep6(category: Category, timeZone: TimeZone): LiveData { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "step 6") + } + + return getTrustedDateLive(appLogic.timeApi, timeZone).switchMap { + nowTrustedDate -> + + appLogic.database.timeLimitRules().getTimeLimitRulesByCategory(category.id).switchMap { + rules -> + + if (rules.isEmpty()) { + liveDataFromValue(BlockingReason.None) + } else if (nowTrustedDate == null) { + liveDataFromValue(BlockingReason.MissingNetworkTime) + } else { + getBlockingReasonStep6(category, nowTrustedDate, rules) + } + } + } + } + + private fun getBlockingReasonStep6(category: Category, nowTrustedDate: DateInTimezone, rules: List): LiveData { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "step 6 - 2") + } + + return appLogic.currentDeviceLogic.isThisDeviceTheCurrentDevice.switchMap { isCurrentDevice -> + if (isCurrentDevice) { + getBlockingReasonStep7(category, nowTrustedDate, rules) + } else { + liveDataFromValue(BlockingReason.RequiresCurrentDevice) + } + } + } + + private fun getBlockingReasonStep7(category: Category, nowTrustedDate: DateInTimezone, rules: List): LiveData { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "step 7") + } + + return appLogic.database.usedTimes().getUsedTimesOfWeek(category.id, nowTrustedDate.dayOfEpoch - nowTrustedDate.dayOfWeek).map { + usedTimes -> + val usedTimesSparseArray = SparseLongArray() + + for (i in 0..6) { + val usedTimesItem = usedTimes[i]?.usedMillis + usedTimesSparseArray.put(i, (if (usedTimesItem != null) usedTimesItem else 0)) + } + + val remaining = RemainingTime.getRemainingTime(nowTrustedDate.dayOfWeek, usedTimesSparseArray, rules, category.extraTimeInMillis) + + if (remaining == null || remaining.includingExtraTime > 0) { + BlockingReason.None + } else { + if (category.extraTimeInMillis > 0) { + BlockingReason.TimeOverExtraTimeCanBeUsedLater + } else { + BlockingReason.TimeOver + } + } + } + } + + private fun getTemporarilyTrustedTimeInMillis(): LiveData { + val realTime = RealTime.newInstance() + + return liveDataFromFunction { + appLogic.realTimeLogic.getRealTime(realTime) + + if (realTime.shouldTrustTimeTemporarily) { + realTime.timeInMillis + } else { + null + } + } + } + + private fun getTrustedMinuteOfWeekLive(api: TimeApi, timeZone: TimeZone): LiveData { + val realTime = RealTime.newInstance() + + return object: LiveData() { + fun update() { + appLogic.realTimeLogic.getRealTime(realTime) + + if (realTime.shouldTrustTimeTemporarily) { + value = getMinuteOfWeek(realTime.timeInMillis, timeZone) + } else { + value = null + } + } + + init { + update() + } + + val scheduledUpdateRunnable = Runnable { + update() + scheduleUpdate() + } + + fun scheduleUpdate() { + api.runDelayed(scheduledUpdateRunnable, 1000L /* every second */) + } + + fun cancelScheduledUpdate() { + api.cancelScheduledAction(scheduledUpdateRunnable) + } + + override fun onActive() { + super.onActive() + + update() + scheduleUpdate() + } + + override fun onInactive() { + super.onInactive() + + cancelScheduledUpdate() + } + }.ignoreUnchanged() + } + + private fun getTrustedDateLive(api: TimeApi, timeZone: TimeZone): LiveData { + val realTime = RealTime.newInstance() + + return object: LiveData() { + fun update() { + appLogic.realTimeLogic.getRealTime(realTime) + + if (realTime.shouldTrustTimeTemporarily) { + value = DateInTimezone.newInstance(realTime.timeInMillis, timeZone) + } else { + value = null + } + } + + init { + update() + } + + val scheduledUpdateRunnable = Runnable { + update() + scheduleUpdate() + } + + fun scheduleUpdate() { + api.runDelayed(scheduledUpdateRunnable, 1000L /* every second */) + } + + fun cancelScheduledUpdate() { + api.cancelScheduledAction(scheduledUpdateRunnable) + } + + override fun onActive() { + super.onActive() + + update() + scheduleUpdate() + } + + override fun onInactive() { + super.onInactive() + + cancelScheduledUpdate() + } + }.ignoreUnchanged() + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/CurrentDeviceLogic.kt b/app/src/main/java/io/timelimit/android/logic/CurrentDeviceLogic.kt new file mode 100644 index 0000000..006be11 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/CurrentDeviceLogic.kt @@ -0,0 +1,66 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import io.timelimit.android.data.model.Device +import io.timelimit.android.livedata.* + +class CurrentDeviceLogic(private val appLogic: AppLogic) { + private val disabledPrimaryDeviceCheck = appLogic.deviceUserEntry.switchMap { userEntry -> + if (userEntry?.relaxPrimaryDevice == true) { + appLogic.fullVersion.shouldProvideFullVersionFunctions + } else { + liveDataFromValue(false) + } + } + + private val userDeviceEntries = appLogic.deviceUserId.switchMap { deviceUserId -> + if (deviceUserId == "") { + liveDataFromValue(emptyList()) + } else { + appLogic.database.device().getDevicesByUserId(deviceUserId) + } + } + + private val otherUserDeviceEntries = appLogic.deviceEntry.switchMap { ownDeviceEntry -> + userDeviceEntries.map { devices -> + devices.filterNot { device -> device.id == ownDeviceEntry?.id } + } + } + + private val isThisDeviceMarkedAsCurrentDevice = appLogic.deviceEntry + .map { it?.id } + .switchMap { ownDeviceId -> + appLogic.deviceUserEntry.map { userEntry -> + userEntry?.currentDevice == ownDeviceId + } + } + + val isThisDeviceTheCurrentDevice = appLogic.fullVersion.isLocalMode + .or(isThisDeviceMarkedAsCurrentDevice) + .or(disabledPrimaryDeviceCheck) + .ignoreUnchanged() + + val otherAssignedDevice = appLogic.deviceUserEntry.switchMap { userEntry -> + if (userEntry?.currentDevice == null) { + liveDataFromValue(null as Device?) + } else { + otherUserDeviceEntries.map { otherDeviceEntries -> + otherDeviceEntries.find { it.id == userEntry.currentDevice } + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/DefaultAppLogic.kt b/app/src/main/java/io/timelimit/android/logic/DefaultAppLogic.kt new file mode 100644 index 0000000..12e6d50 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/DefaultAppLogic.kt @@ -0,0 +1,30 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.content.Context + +object DefaultAppLogic { + private var instance: AppLogic? = null + + fun with(context: Context): AppLogic { + if (instance == null) { + instance = AndroidAppLogic.with(context) + } + + return instance!! + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/logic/DefaultUserLogic.kt b/app/src/main/java/io/timelimit/android/logic/DefaultUserLogic.kt new file mode 100644 index 0000000..bece407 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/DefaultUserLogic.kt @@ -0,0 +1,186 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.util.Log +import io.timelimit.android.BuildConfig +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.User +import io.timelimit.android.livedata.* +import io.timelimit.android.sync.actions.SignOutAtDeviceAction +import io.timelimit.android.sync.actions.apply.ApplyActionUtil +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +class DefaultUserLogic(private val appLogic: AppLogic) { + companion object { + private const val LOG_TAG = "DefaultUserLogic" + } + + private fun defaultUserEntry() = appLogic.deviceEntry.map { device -> + device?.defaultUser + }.ignoreUnchanged().switchMap { + if (it != null) + appLogic.database.user().getUserByIdLive(it) + else + liveDataFromValue(null as User?) + } + private fun hasDefaultUser() = defaultUserEntry().map { it != null }.ignoreUnchanged() + private fun defaultUserTimeout() = appLogic.deviceEntry.map { it?.defaultUserTimeout ?: 0 }.ignoreUnchanged() + private fun hasDefaultUserTimeout() = defaultUserTimeout().map { it != 0 }.ignoreUnchanged() + fun hasAutomaticSignOut() = hasDefaultUser().and(hasDefaultUserTimeout()) + + private val logoutLock = Mutex() + + private var lastScreenOnStatus = false + private var lastScreenDisableTime = 0L + private var lastScreenOnSaveTime = 0L + private var restoredLastScreenOnTime: Long? = null + private var didRestoreLastDisabledTime = false + + fun reportScreenOn(isScreenOn: Boolean) { + if (isScreenOn) { + val now = appLogic.timeApi.getCurrentTimeInMillis() + + if (lastScreenOnSaveTime + 1000 * 30 < now) { + lastScreenOnSaveTime = now + + Threads.database.submit { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "save last screen on time") + } + + if (restoredLastScreenOnTime == null) { + restoredLastScreenOnTime = appLogic.database.config().getLastScreenOnTime() + } + + appLogic.database.config().setLastScreenOnTime(now) + } + } + } + + if (isScreenOn != lastScreenOnStatus) { + lastScreenOnStatus = isScreenOn + + if (isScreenOn) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "screen was enabled") + } + + runAsync { + logoutLock.withLock { + if (lastScreenDisableTime == 0L) { + if (!didRestoreLastDisabledTime) { + didRestoreLastDisabledTime = true + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "screen disabling time is not known - try to restore time") + } + + val nowTime = appLogic.timeApi.getCurrentTimeInMillis() + val nowUptime = appLogic.timeApi.getCurrentUptimeInMillis() + val savedLastScreenOnTime = restoredLastScreenOnTime ?: kotlin.run { + Threads.database.executeAndWait { + restoredLastScreenOnTime = appLogic.database.config().getLastScreenOnTime() + } + + restoredLastScreenOnTime!! + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "now: $nowTime; uptime: $nowUptime; last screen on time: $savedLastScreenOnTime") + } + + if (savedLastScreenOnTime == 0L) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "no saved value - can not restore") + } + } else if (savedLastScreenOnTime > nowTime) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "saved last screen on time is in the future - can not restore") + } + } else { + val diffToNow = nowTime - savedLastScreenOnTime + val theoreticallyUptimeValue = nowUptime - diffToNow + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "restored last screen on time: diff to now: ${diffToNow / 1000} s; theoretically uptime: ${theoreticallyUptimeValue / 1000} s") + } + + lastScreenDisableTime = theoreticallyUptimeValue + } + } + } + + if (lastScreenDisableTime != 0L) { + val now = appLogic.timeApi.getCurrentUptimeInMillis() + val diff = now - lastScreenDisableTime + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "screen was disabled for ${diff / 1000} seconds") + } + + val defaultUser = defaultUserEntry().waitForNullableValue() + + if (defaultUser != null) { + if (appLogic.deviceEntry.waitForNullableValue()?.currentUserId == defaultUser.id) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "default user already signed in") + } + } else { + val timeout = defaultUserTimeout().waitForNonNullValue() + + if (diff >= timeout && timeout != 0) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "much time - log out") + } + + if (appLogic.fullVersion.shouldProvideFullVersionFunctions.waitForNonNullValue()) { + ApplyActionUtil.applyAppLogicAction( + appLogic = appLogic, + action = SignOutAtDeviceAction + ) + } else { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "has not full version - cancel") + } + } + } else { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "no reason to log out") + } + } + } + } else { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "has no default user") + } + } + } + } + } + } else { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "screen was disabled") + } + + lastScreenDisableTime = appLogic.timeApi.getCurrentUptimeInMillis() + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/logic/FullVersionLogic.kt b/app/src/main/java/io/timelimit/android/logic/FullVersionLogic.kt new file mode 100644 index 0000000..901b17f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/FullVersionLogic.kt @@ -0,0 +1,27 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.or + +class FullVersionLogic(logic: AppLogic) { + private val hasFullVersion = logic.database.config().getFullVersionUntilAsync().map { it != 0L }.ignoreUnchanged() + val isLocalMode = logic.database.config().getDeviceAuthTokenAsync().map { it == "" } + + val shouldProvideFullVersionFunctions = hasFullVersion.or(isLocalMode) +} diff --git a/app/src/main/java/io/timelimit/android/logic/ManipulationLogic.kt b/app/src/main/java/io/timelimit/android/logic/ManipulationLogic.kt new file mode 100644 index 0000000..6cc4191 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/ManipulationLogic.kt @@ -0,0 +1,99 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.content.Intent +import android.os.Build +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.transaction +import io.timelimit.android.ui.MainActivity +import io.timelimit.android.ui.manipulation.UnlockAfterManipulationActivity + +class ManipulationLogic(val appLogic: AppLogic) { + companion object { + private const val LOG_TAG = "ManipulationLogic" + } + + init { + runAsync { + Threads.database.executeAndWait { + if (appLogic.database.config().wasDeviceLockedSync()) { + showManipulationScreen() + } + } + } + } + + fun lockDeviceSync() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + if (appLogic.platformIntegration.setLockTaskPackages(listOf(appLogic.context.packageName))) { + appLogic.database.config().setWasDeviceLockedSync(true) + + showManipulationScreen() + } + } else { + if (lockDeviceSync("12timelimit34")) { + appLogic.database.config().setWasDeviceLockedSync(true) + + showManipulationScreen() + } + } + } + + private fun lockDeviceSync(password: String) = appLogic.platformIntegration.trySetLockScreenPassword(password) + + private fun showManipulationScreen() { + appLogic.context.startActivity( + Intent(appLogic.context, UnlockAfterManipulationActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } + + fun showManipulationUnlockedScreen() { + appLogic.context.startActivity( + Intent(appLogic.context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } + + fun unlockDeviceSync() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + appLogic.database.config().setWasDeviceLockedSync(false) + } else { + if (lockDeviceSync("")) { + appLogic.database.config().setWasDeviceLockedSync(false) + } + } + } + + fun reportManualUnlock() { + Threads.database.execute { + appLogic.database.transaction().use { transaction -> + if (appLogic.database.config().getOwnDeviceIdSync() != null) { + if (appLogic.database.config().wasDeviceLockedSync()) { + appLogic.database.config().setWasDeviceLockedSync(false) + + showManipulationUnlockedScreen() + } + + transaction.setSuccess() + } + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/QueryAppTitleCache.kt b/app/src/main/java/io/timelimit/android/logic/QueryAppTitleCache.kt new file mode 100644 index 0000000..685d500 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/QueryAppTitleCache.kt @@ -0,0 +1,39 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import io.timelimit.android.integration.platform.PlatformIntegration + +class QueryAppTitleCache(val platformIntegration: PlatformIntegration) { + private var lastPackageName: String? = null + private var lastAppTitle: String? = null + + fun query(packageName: String): String { + if (packageName == lastPackageName) { + return lastAppTitle!! + } else { + val title = platformIntegration.getLocalAppTitle(packageName) + + lastAppTitle = when { + title != null -> title + else -> packageName + } + lastPackageName = packageName + + return lastAppTitle!! + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/logic/RealTimeLogic.kt b/app/src/main/java/io/timelimit/android/logic/RealTimeLogic.kt new file mode 100644 index 0000000..107e6cd --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/RealTimeLogic.kt @@ -0,0 +1,207 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.util.Log +import io.timelimit.android.BuildConfig +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.NetworkTime +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.map +import kotlinx.coroutines.sync.Mutex +import java.io.IOException + +class RealTimeLogic(private val appLogic: AppLogic) { + companion object { + private const val LOG_TAG = "RealTimeLogic" + } + + private val deviceEntry = appLogic.deviceEntryIfEnabled + val shouldQueryTime = deviceEntry.map { + it != null && + (it.networkTime == NetworkTime.Enabled || it.networkTime == NetworkTime.IfPossible) + }.ignoreUnchanged() + + init { + deviceEntry.ignoreUnchanged().observeForever { + // this keeps the value fresh + } + + shouldQueryTime.observeForever { + if (it != null && it) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "shouldQueryTime = true") + } + + requireRemoteTimeUptime = appLogic.timeApi.getCurrentUptimeInMillis() + tryQueryTime() + } else { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "shouldQueryTime = false") + } + + appLogic.timeApi.cancelScheduledAction(tryQueryTime) + } + } + } + + private var lastSuccessfullyTimeRequestUptime: Long? = null + private var uptimeRealTimeOffset: Long? = null + private var requireRemoteTimeUptime: Long = 0 + private var confirmedUptimeSystemTimeOffset: Long? = null + + private val queryTimeLock = Mutex() + private val tryQueryTime = Runnable { tryQueryTime() } + + fun tryQueryTime() { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "tryQueryTime") + } + + runAsync { + val owner = Object() + + if (queryTimeLock.tryLock(owner)) { + appLogic.timeApi.cancelScheduledAction(tryQueryTime) + + try { + val server = appLogic.serverLogic.getServerConfigCoroutine() + + if (!server.isAppEnabled) { + throw IOException("app during setup - time queries disabled") + } + + val uptimeBefore = appLogic.timeApi.getCurrentUptimeInMillis() + val serverTime = server.api.getTimeInMillis() + val uptime = appLogic.timeApi.getCurrentUptimeInMillis() + + val uptimeOffset = uptime - uptimeBefore + + if (uptimeOffset > 30 * 1000 /* 30 seconds */) { + throw IOException("time request took too long") + } + + uptimeRealTimeOffset = serverTime - uptime + lastSuccessfullyTimeRequestUptime = uptime + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "tryQueryTime was successfully in $uptimeOffset ms") + } + + // schedule refresh in 2 hours + appLogic.timeApi.runDelayed(tryQueryTime, 1000 * 60 * 60 * 2) + } catch (ex: Exception) { + if (uptimeRealTimeOffset == null) { + // schedule next attempt in 10 seconds + appLogic.timeApi.runDelayed(tryQueryTime, 1000 * 10) + } else { + // schedule next attempt in 10 minutes + appLogic.timeApi.runDelayed(tryQueryTime, 1000 * 60 * 10) + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "tryQueryTime failed") + } + } finally { + queryTimeLock.unlock(owner) + } + } + } + } + + fun confirmLocalTime() { + val uptime = appLogic.timeApi.getCurrentUptimeInMillis() + val systemTime = appLogic.timeApi.getCurrentTimeInMillis() + + confirmedUptimeSystemTimeOffset = systemTime - uptime + } + + fun getRealTime(time: RealTime) { + val systemUptime = appLogic.timeApi.getCurrentUptimeInMillis() + val systemTime = appLogic.timeApi.getCurrentTimeInMillis() + + val uptimeRealTimeOffset = uptimeRealTimeOffset + val confirmedUptimeSystemTimeOffset = confirmedUptimeSystemTimeOffset + + val deviceConfig = deviceEntry.value + + if (deviceConfig == null) { + time.timeInMillis = systemTime + time.shouldTrustTimeTemporarily = true + time.shouldTrustTimePermanently = false + } else if (deviceConfig.networkTime == NetworkTime.Disabled) { + time.timeInMillis = systemTime + time.shouldTrustTimeTemporarily = true + time.shouldTrustTimePermanently = true + } else if (deviceConfig.networkTime == NetworkTime.IfPossible) { + if (uptimeRealTimeOffset != null) { + time.timeInMillis = systemUptime + uptimeRealTimeOffset + time.shouldTrustTimeTemporarily = true + time.shouldTrustTimePermanently = true + } else { + time.timeInMillis = systemTime + time.shouldTrustTimeTemporarily = true + time.shouldTrustTimePermanently = true + } + } else if (deviceConfig.networkTime == NetworkTime.Enabled) { + if (uptimeRealTimeOffset != null) { + time.timeInMillis = systemUptime + uptimeRealTimeOffset + time.shouldTrustTimeTemporarily = true + time.shouldTrustTimePermanently = true + } else if (confirmedUptimeSystemTimeOffset != null) { + time.timeInMillis = systemUptime + confirmedUptimeSystemTimeOffset + time.shouldTrustTimeTemporarily = true + time.shouldTrustTimePermanently = false + } else { + time.timeInMillis = systemTime + // 5 seconds grace period + time.shouldTrustTimeTemporarily = requireRemoteTimeUptime + 5000 > systemUptime + time.shouldTrustTimePermanently = false + } + } else { + throw IllegalStateException() + } + } + + private val temp = RealTime.newInstance() + + fun getCurrentTimeInMillis(): Long { + getRealTime(temp) + + return temp.timeInMillis + } + + val durationSinceLastSuccessfullyTimeSync: Long? + get() { + val now = appLogic.timeApi.getCurrentUptimeInMillis() + val last = lastSuccessfullyTimeRequestUptime + + return if (last == null) + null + else + now - last + } +} + +data class RealTime( + var timeInMillis: Long, + var shouldTrustTimeTemporarily: Boolean, + var shouldTrustTimePermanently: Boolean +) { + companion object { + fun newInstance() = RealTime(0, false, false) + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/RemainingTime.kt b/app/src/main/java/io/timelimit/android/logic/RemainingTime.kt new file mode 100644 index 0000000..1b31351 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/RemainingTime.kt @@ -0,0 +1,100 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.util.SparseLongArray +import io.timelimit.android.data.model.TimeLimitRule + +data class RemainingTime(val includingExtraTime: Long, val default: Long) { + init { + if (includingExtraTime < 0 || default < 0) { + throw IllegalStateException("time is < 0") + } + + if (includingExtraTime < default) { + throw IllegalStateException("extra time < default time") + } + } + + companion object { + fun min(a: RemainingTime?, b: RemainingTime?): RemainingTime? = if (a == null) { + b + } else if (b == null) { + a + } else { + RemainingTime( + includingExtraTime = Math.min(a.includingExtraTime, b.includingExtraTime), + default = Math.min(a.default, b.default) + ) + } + + private fun getRulesRelatedToDay(dayOfWeek: Int, rules: List): List { + return rules.filter { (it.dayMask.toInt() and (1 shl dayOfWeek)) != 0 } + } + + fun getRemainingTime(dayOfWeek: Int, usedTimes: SparseLongArray, rules: List, extraTime: Long): RemainingTime? { + if (extraTime < 0) { + throw IllegalStateException("extra time < 0") + } + + val relatedRules = getRulesRelatedToDay(dayOfWeek, rules) + val withoutExtraTime = getRemainingTime(usedTimes, relatedRules, false) + val withExtraTime = getRemainingTime(usedTimes, relatedRules, true) + + if (withoutExtraTime == null && withExtraTime == null) { + // no rules + return null + } else if (withoutExtraTime != null && withExtraTime != null) { + // with rules for extra time + val additionalTimeWithExtraTime = withExtraTime - withoutExtraTime + + if (additionalTimeWithExtraTime < 0) { + throw IllegalStateException("additional time with extra time < 0") + } + + return RemainingTime( + includingExtraTime = withoutExtraTime + Math.min(extraTime, additionalTimeWithExtraTime), + default = withoutExtraTime + ) + } else if (withoutExtraTime != null) { + // without rules for extra time + return RemainingTime( + includingExtraTime = withoutExtraTime + extraTime, + default = withoutExtraTime + ) + } else { + throw IllegalStateException() + } + } + + private fun getRemainingTime(usedTimes: SparseLongArray, relatedRules: List, assumeMaximalExtraTime: Boolean): Long? { + return relatedRules.filter { (!assumeMaximalExtraTime) || it.applyToExtraTimeUsage }.map { + var usedTime = 0L + + for (day in 0..6) { + if ((it.dayMask.toInt() and (1 shl day)) != 0) { + usedTime += usedTimes[day] + } + } + + val maxTime = it.maximumTimeInMillis + val remaining = Math.max(0, maxTime - usedTime) + + remaining + }.min() + } + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/ServerLogic.kt b/app/src/main/java/io/timelimit/android/logic/ServerLogic.kt new file mode 100644 index 0000000..c8fb4f0 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/ServerLogic.kt @@ -0,0 +1,67 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import io.timelimit.android.BuildConfig +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.sync.network.api.ServerApi + +class ServerLogic(private val appLogic: AppLogic) { + companion object { + private fun getServerUrlFromCustomServerUrl(customServerUrl: String) = customServerUrl.let { savedUrl -> + if (savedUrl.isEmpty()) { + BuildConfig.serverUrl + } else { + savedUrl + } + } + } + + fun getServerFromCustomServerUrl(customServerUrl: String) = appLogic.serverCreator(getServerUrlFromCustomServerUrl(customServerUrl)) + + suspend fun getServerConfigCoroutine(): ServerConfig { + return Threads.database.executeAndWait { + appLogic.database.beginTransaction() + + try { + val customServerUrl = appLogic.database.config().getCustomServerUrlSync() + val deviceAuthToken = appLogic.database.config().getDeviceAuthTokenSync() + val isAppEnabled = appLogic.database.config().getOwnDeviceIdSync() != null + + ServerConfig( + customServerUrl = customServerUrl, + deviceAuthToken = deviceAuthToken, + isAppEnabled = isAppEnabled, + serverLogic = this + ) + } finally { + appLogic.database.endTransaction() + } + } + } + + data class ServerConfig( + val customServerUrl: String, + val deviceAuthToken: String, + val isAppEnabled: Boolean, + private val serverLogic: ServerLogic + ) { + val hasAuthToken = deviceAuthToken != "" + val serverUrl = ServerLogic.getServerUrlFromCustomServerUrl(customServerUrl) + val api: ServerApi by lazy { serverLogic.getServerFromCustomServerUrl(serverUrl) } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/logic/SyncInstalledAppsLogic.kt b/app/src/main/java/io/timelimit/android/logic/SyncInstalledAppsLogic.kt new file mode 100644 index 0000000..91ce1d9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/SyncInstalledAppsLogic.kt @@ -0,0 +1,109 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.coroutines.runAsyncExpectForever +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.* +import io.timelimit.android.sync.actions.AddInstalledAppsAction +import io.timelimit.android.sync.actions.InstalledApp +import io.timelimit.android.sync.actions.RemoveInstalledAppsAction +import io.timelimit.android.sync.actions.apply.ApplyActionUtil +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +class SyncInstalledAppsLogic(val appLogic: AppLogic) { + private val doSyncLock = Mutex() + private var requestSync = MutableLiveData().apply { value = false } + + private fun requestSync() { + requestSync.value = true + } + + init { + appLogic.platformIntegration.installedAppsChangeListener = Runnable { requestSync() } + appLogic.deviceEntryIfEnabled.map { it?.id + it?.currentUserId }.ignoreUnchanged().observeForever { requestSync() } + + runAsyncExpectForever { syncLoop() } + } + + private suspend fun syncLoop() { + while (true) { + requestSync.waitUntilValueMatches { it == true } + requestSync.value = false + + doSyncNow() + + // maximal 1 time per 5 seconds + appLogic.timeApi.sleep(5 * 1000) + } + } + + private suspend fun doSyncNow() { + doSyncLock.withLock { + val deviceEntry = appLogic.deviceEntryIfEnabled.waitForNullableValue() + + if (deviceEntry == null) { + return + } + + val userEntry = appLogic.deviceUserEntry.waitForNullableValue() + + if (userEntry == null || userEntry.type != UserType.Child) { + return@withLock + } + + val deviceId = deviceEntry.id + + val currentlyInstalled = appLogic.platformIntegration.getLocalApps(deviceId = deviceId).associateBy { app -> app.packageName } + val currentlySaved = appLogic.database.app().getAppsByDeviceIdAsync(deviceId = deviceId).waitForNonNullValue().associateBy { app -> app.packageName } + + // skip all items for removal which are still saved locally + val itemsToRemove = HashMap(currentlySaved) + currentlyInstalled.forEach { (packageName, _) -> itemsToRemove.remove(packageName) } + + // only add items which are not the same locally + val itemsToAdd = currentlyInstalled.filter { (packageName, app) -> currentlySaved[packageName] != app } + + // save the changes + if (itemsToRemove.isNotEmpty()) { + ApplyActionUtil.applyAppLogicAction( + RemoveInstalledAppsAction(packageNames = itemsToRemove.keys.toList()), + appLogic + ) + } + + if (itemsToAdd.isNotEmpty()) { + ApplyActionUtil.applyAppLogicAction( + AddInstalledAppsAction( + apps = itemsToAdd.map { + (_, app) -> + + InstalledApp( + packageName = app.packageName, + title = app.title, + recommendation = app.recommendation, + isLaunchable = app.isLaunchable + ) + } + ), + appLogic + ) + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/logic/TestAppLogic.kt b/app/src/main/java/io/timelimit/android/logic/TestAppLogic.kt new file mode 100644 index 0000000..564f886 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/TestAppLogic.kt @@ -0,0 +1,46 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.content.Context +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.data.RoomDatabase +import io.timelimit.android.integration.platform.ProtectionLevel +import io.timelimit.android.integration.platform.dummy.DummyIntegration +import io.timelimit.android.integration.time.DummyTimeApi +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.sync.network.api.DummyServerApi +import io.timelimit.android.sync.websocket.DummyWebsocketClient +import io.timelimit.android.sync.websocket.NetworkStatus + +class TestAppLogic(maximumProtectionLevel: ProtectionLevel, context: Context) { + val platformIntegration = DummyIntegration(maximumProtectionLevel) + val timeApi = DummyTimeApi(100) + val database = RoomDatabase.createInMemoryInstance(context) + val server = DummyServerApi() + val networkStatus = MutableLiveData().apply { value = NetworkStatus.Offline } + + val logic = AppLogic( + platformIntegration = platformIntegration, + timeApi = timeApi, + database = database, + serverCreator = { _ -> server }, + networkStatus = networkStatus, + websocketClientCreator = DummyWebsocketClient.creator, + context = context, + isInitialized = liveDataFromValue(true) + ) +} diff --git a/app/src/main/java/io/timelimit/android/logic/UsedTimeItemBatchUpdateHelper.kt b/app/src/main/java/io/timelimit/android/logic/UsedTimeItemBatchUpdateHelper.kt new file mode 100644 index 0000000..a487cf4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/UsedTimeItemBatchUpdateHelper.kt @@ -0,0 +1,122 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.UsedTimeItem +import io.timelimit.android.date.DateInTimezone +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.sync.actions.AddUsedTimeAction +import io.timelimit.android.sync.actions.apply.ApplyActionUtil + +class UsedTimeItemBatchUpdateHelper( + val date: DateInTimezone, + val childCategoryId: String, + val parentCategoryId: String?, + var cachedItemChild: UsedTimeItem?, + var cachedItemParent: UsedTimeItem? +) { + companion object { + suspend fun eventuallyUpdateInstance( + date: DateInTimezone, + childCategoryId: String, + parentCategoryId: String?, + oldInstance: UsedTimeItemBatchUpdateHelper?, + usedTimeItemForDayChild: UsedTimeItem?, + usedTimeItemForDayParent: UsedTimeItem?, + logic: AppLogic + ): UsedTimeItemBatchUpdateHelper { + if ( + oldInstance != null && + oldInstance.date == date && + oldInstance.childCategoryId == childCategoryId && + oldInstance.parentCategoryId == parentCategoryId + ) { + if (oldInstance.cachedItemChild != usedTimeItemForDayChild) { + oldInstance.cachedItemChild = usedTimeItemForDayChild + } + + if (oldInstance.cachedItemParent != usedTimeItemForDayParent) { + oldInstance.cachedItemParent = usedTimeItemForDayParent + } + + return oldInstance + } else { + if (oldInstance != null) { + oldInstance.commit(logic) + } + + return UsedTimeItemBatchUpdateHelper( + date = date, + childCategoryId = childCategoryId, + parentCategoryId = parentCategoryId, + cachedItemChild = usedTimeItemForDayChild, + cachedItemParent = usedTimeItemForDayParent + ) + } + } + } + + private var timeToAdd = 0 + private var extraTimeToSubtract = 0 + + suspend fun addUsedTime(time: Int, subtractExtraTime: Boolean, appLogic: AppLogic) { + timeToAdd += time + + if (subtractExtraTime) { + extraTimeToSubtract += time + } + + if (Math.max(timeToAdd, extraTimeToSubtract) > 1000 * 10 /* 10 seconds */) { + commit(appLogic) + } + } + + fun getTotalUsedTimeChild(): Long = (cachedItemChild?.usedMillis ?: 0) + timeToAdd + fun getTotalUsedTimeParent(): Long = (cachedItemParent?.usedMillis ?: 0) + timeToAdd + + fun getCachedExtraTimeToSubtract(): Int { + return extraTimeToSubtract + } + + suspend fun queryCurrentStatusFromDatabase(database: Database) { + cachedItemChild = database.usedTimes().getUsedTimeItem(childCategoryId, date.dayOfEpoch).waitForNullableValue() + cachedItemParent = parentCategoryId?.let { + database.usedTimes().getUsedTimeItem(parentCategoryId, date.dayOfEpoch).waitForNullableValue() + } + } + + suspend fun commit(logic: AppLogic) { + if (timeToAdd == 0) { + // do nothing + } else { + ApplyActionUtil.applyAppLogicAction( + AddUsedTimeAction( + categoryId = childCategoryId, + timeToAdd = timeToAdd, + dayOfEpoch = date.dayOfEpoch, + extraTimeToSubtract = extraTimeToSubtract + ), + logic + ) + + timeToAdd = 0 + extraTimeToSubtract = 0 + + queryCurrentStatusFromDatabase(logic.database) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/logic/WebsocketClientLogic.kt b/app/src/main/java/io/timelimit/android/logic/WebsocketClientLogic.kt new file mode 100644 index 0000000..8cc5384 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/WebsocketClientLogic.kt @@ -0,0 +1,204 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.logic + +import android.util.Log +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.coroutines.runAsyncExpectForever +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.* +import io.timelimit.android.sync.websocket.NetworkStatus +import io.timelimit.android.sync.websocket.WebsocketClient +import io.timelimit.android.sync.websocket.WebsocketClientCreator +import io.timelimit.android.sync.websocket.WebsocketClientListener +import io.timelimit.android.ui.IsAppInForeground +import io.timelimit.android.ui.manage.child.primarydevice.UpdatePrimaryDeviceModel + +class WebsocketClientLogic( + private val appLogic: AppLogic, + private val isConnectedInternal: MutableLiveData, + websocketClientCreator: WebsocketClientCreator +) { + companion object { + private const val LOG_TAG = "WebsocketClientLogic" + } + + // it's not checked if the device is configured for the online mode here because this is caught below + private val shouldConnectToWebsocket = appLogic.enable.switchMap { enabled -> + + // app must be enabled + if (enabled == true) { + val okForCurrentUser = appLogic.deviceUserEntry.switchMap { + if (it?.type == UserType.Child) { + liveDataFromValue(true) + } else { + IsAppInForeground.isRunning + } + } + + val okFromNetworkStatus = appLogic.networkStatus.map { networkStatus -> + networkStatus == NetworkStatus.Online + } + + okForCurrentUser.and(okFromNetworkStatus) + } else { + liveDataFromValue(false) + } + } + + private val deviceAuthTokenToConnectFor = shouldConnectToWebsocket.switchMap { shouldConnect -> + + if (shouldConnect) { + appLogic.database.config().getDeviceAuthTokenAsync() + } else { + liveDataFromValue("") + } + } + + private val connectedDevicesInternal = MutableLiveData>().apply { value = emptySet() } + val connectedDevices = connectedDevicesInternal.ignoreUnchanged() + + init { + runAsyncExpectForever { + var previousDeviceAuthToken: String? = null + var currentWebsocketClient: WebsocketClient? = null + + while (true) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "wait for new device auth token") + } + + val deviceAuthToken = deviceAuthTokenToConnectFor.waitUntilValueMatches { it != previousDeviceAuthToken }!! + previousDeviceAuthToken = deviceAuthToken + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "got new device auth token: $deviceAuthToken") + } + + // shutdown any current connection + currentWebsocketClient?.shutdown() + currentWebsocketClient = null + + if (deviceAuthToken.isNotEmpty()) { + val serverConfig = appLogic.serverLogic.getServerConfigCoroutine() + + if (serverConfig.deviceAuthToken != deviceAuthToken) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "device auth token changed in the time between - don't connect") + } + + continue + } + + val serverUrl = serverConfig.serverUrl + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "create new websocket client for $serverUrl") + } + + lateinit var newWebsocketClient: WebsocketClient + + newWebsocketClient = websocketClientCreator.createWebsocketClient( + deviceAuthTokenToConnectFor = deviceAuthToken, + serverUrl = serverUrl, + listener = object : WebsocketClientListener { + override fun onConnectionEstablished() { + if (currentWebsocketClient !== newWebsocketClient) { + // we are not the current instance anymore + return + } + + isConnectedInternal.postValue(true) + connectedDevicesInternal.postValue(emptySet()) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "request important sync because websocket connection was established") + } + + appLogic.syncUtil.requestImportantSync() + } + + override fun onSyncRequestedByServer(important: Boolean) { + if (currentWebsocketClient !== newWebsocketClient) { + // we are not the current instance anymore + return + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "request sync because the server did it") + } + + if (important) { + appLogic.syncUtil.requestImportantSync() + } else { + appLogic.syncUtil.requestUnimportantSync() + } + } + + override fun onConnectionLost() { + if (currentWebsocketClient !== newWebsocketClient) { + // we are not the current instance anymore + return + } + + isConnectedInternal.postValue(false) + connectedDevicesInternal.postValue(emptySet()) + } + + override fun onGotConnectedDeviceList(connectedDeviceIds: Set) { + if (currentWebsocketClient !== newWebsocketClient) { + // we are not the current instance anymore + return + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "got connected device list: ${connectedDeviceIds.joinToString(", ")}") + } + + connectedDevicesInternal.postValue(connectedDeviceIds) + } + + override fun onGotSignOutRequest() { + if (currentWebsocketClient !== newWebsocketClient) { + // we are not the current instance anymore + return + } + + runAsync { + try { + if (AppAffectedByPrimaryDeviceUtil.isCurrentAppAffectedByPrimaryDevice(appLogic)) { + throw IllegalStateException("current device would be affected by primary device") + } + + UpdatePrimaryDeviceModel.unsetPrimaryDeviceInBackground(appLogic) + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "could not unset this device as current device", ex) + } + } + } + } + } + ) + + currentWebsocketClient = newWebsocketClient + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/ApplyServerDataStatus.kt b/app/src/main/java/io/timelimit/android/sync/ApplyServerDataStatus.kt new file mode 100644 index 0000000..6633990 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/ApplyServerDataStatus.kt @@ -0,0 +1,417 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync + +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.* +import io.timelimit.android.integration.platform.PlatformIntegration +import io.timelimit.android.sync.actions.DatabaseValidation +import io.timelimit.android.sync.actions.DeleteCategoryAction +import io.timelimit.android.sync.actions.RemoveUserAction +import io.timelimit.android.sync.actions.dispatch.LocalDatabaseParentActionDispatcher +import io.timelimit.android.sync.network.ServerDataStatus + +object ApplyServerDataStatus { + suspend fun applyServerDataStatusCoroutine(status: ServerDataStatus, database: Database, platformIntegration: PlatformIntegration) { + Threads.database.executeAndWait { + applyServerDataStatusSync(status, database, platformIntegration) + } + } + + fun applyServerDataStatusSync(status: ServerDataStatus, database: Database, platformIntegration: PlatformIntegration) { + database.beginTransaction() + + try { + run { + // apply ful version until and message + + database.config().setFullVersionUntilSync(status.fullVersionUntil) + database.config().setServerMessage(status.message) + } + + run { + val newUserList = status.newUserList + + if (newUserList != null) { + val oldUserList = database.user().getAllUsersSync() + + run { + // update/ create entries (first because there must be always one parent user) + + newUserList.data.forEach { + newData -> + val oldEntry = oldUserList.find { it.id == newData.id } + + if (oldEntry == null) { + // create entry + + database.user().addUserSync(newData) + } else { + // eventually update entry + + if (newData != oldEntry) { + database.user().updateUserSync(newData) + } + } + } + } + + run { + // remove old entries + val newUserIds = newUserList.data.map { it.id } + val oldUserIds = oldUserList.map { it.id } + + val oldUserIdsToRemove = ArrayList(oldUserIds) + oldUserIdsToRemove.removeAll(newUserIds) + + oldUserIdsToRemove.forEach { + oldUserId -> + + LocalDatabaseParentActionDispatcher.dispatchParentActionSync( + RemoveUserAction(userId = oldUserId, authentication = null), + database + ) + } + } + + run { + // update version + + database.config().setUserListVersionSync(newUserList.version) + } + } + } + + run { + // apply new device list + val newDeviceList = status.newDeviceList + + if (newDeviceList != null) { + val oldDeviceList = database.device().getAllDevicesSync() + + run { + // remove obsolete entries + + val newDeviceListIds = newDeviceList.data.map { it.deviceId } + val oldDeviceListIds = oldDeviceList.map { it.id } + + val removedDeviceEntryIds = ArrayList(oldDeviceListIds) + removedDeviceEntryIds.removeAll(newDeviceListIds) + + if (removedDeviceEntryIds.isNotEmpty()) { + database.device().removeDevicesById(removedDeviceEntryIds) + } + } + + run { + // add/ update entries + val thisDeviceId = database.config().getOwnDeviceIdSync()!! + + newDeviceList.data.forEach { + newDevice -> + val oldDeviceEntry = oldDeviceList.find { it.id == newDevice.deviceId } + + if (oldDeviceEntry == null) { + // create new entry + + database.device().addDeviceSync(Device( + id = newDevice.deviceId, + name = newDevice.name, + model = newDevice.model, + addedAt = newDevice.addedAt, + currentUserId = newDevice.currentUserId, + installedAppsVersion = "", + networkTime = newDevice.networkTime, + currentProtectionLevel = newDevice.currentProtectionLevel, + highestProtectionLevel = newDevice.highestProtectionLevel, + currentUsageStatsPermission = newDevice.currentUsageStatsPermission, + highestUsageStatsPermission = newDevice.highestUsageStatsPermission, + currentNotificationAccessPermission = newDevice.currentNotificationAccessPermission, + highestNotificationAccessPermission = newDevice.highestNotificationAccessPermission, + currentAppVersion = newDevice.currentAppVersion, + highestAppVersion = newDevice.highestAppVersion, + manipulationTriedDisablingDeviceAdmin = newDevice.triedDisablingAdmin, + manipulationDidReboot = newDevice.didReboot, + hadManipulation = newDevice.hadManipulation, + didReportUninstall = newDevice.didReportUninstall, + isUserKeptSignedIn = newDevice.isUserKeptSignedIn, + showDeviceConnected = newDevice.showDeviceConnected, + defaultUser = newDevice.defaultUser, + defaultUserTimeout = newDevice.defaultUserTimeout, + considerRebootManipulation = newDevice.considerRebootManipulation + )) + } else { + // eventually update old entry + + val updatedDeviceEntry = oldDeviceEntry.copy( + name = newDevice.name, + model = newDevice.model, + addedAt = newDevice.addedAt, + currentUserId = newDevice.currentUserId, + networkTime = newDevice.networkTime, + currentProtectionLevel = newDevice.currentProtectionLevel, + highestProtectionLevel = newDevice.highestProtectionLevel, + currentUsageStatsPermission = newDevice.currentUsageStatsPermission, + highestUsageStatsPermission = newDevice.highestUsageStatsPermission, + currentNotificationAccessPermission = newDevice.currentNotificationAccessPermission, + highestNotificationAccessPermission = newDevice.highestNotificationAccessPermission, + currentAppVersion = newDevice.currentAppVersion, + highestAppVersion = newDevice.highestAppVersion, + manipulationTriedDisablingDeviceAdmin = newDevice.triedDisablingAdmin, + manipulationDidReboot = newDevice.didReboot, + hadManipulation = newDevice.hadManipulation, + didReportUninstall = newDevice.didReportUninstall, + isUserKeptSignedIn = newDevice.isUserKeptSignedIn, + showDeviceConnected = newDevice.showDeviceConnected, + defaultUser = newDevice.defaultUser, + defaultUserTimeout = newDevice.defaultUserTimeout, + considerRebootManipulation = newDevice.considerRebootManipulation + ) + + if (updatedDeviceEntry != oldDeviceEntry) { + database.device().updateDeviceEntry(updatedDeviceEntry) + } + + if (updatedDeviceEntry.id == thisDeviceId) { + if (updatedDeviceEntry.currentUserId != oldDeviceEntry.currentUserId) { + runAsync { + platformIntegration.stopSuspendingForAllApps() + } + } + } + } + } + } + + database.config().setDeviceListVersionSync(newDeviceList.version) + } + } + + run { + status.newInstalledApps.forEach { + item -> + + DatabaseValidation.assertDeviceExists(database, item.deviceId) + + run { + // apply apps + database.app().deleteAllAppsByDeviceId(item.deviceId) + database.app().addAppsSync(item.apps.map { + App( + deviceId = item.deviceId, + packageName = it.packageName, + title = it.title, + isLaunchable = it.isLaunchable, + recommendation = it.recommendation + ) + }) + } + + run { + // apply changed version number + database.device().updateAppsVersion( + deviceId = item.deviceId, + appsVersion = item.version + ) + } + } + } + + run { + // apply removed categories + // there is much data related to a removed category, so we use an existing function for this + + status.removedCategories.forEach { + val categoryId = it + + if (database.category().getCategoryByIdSync(categoryId) == null) { + // category was likely deleted with the user, ignore it + } else { + LocalDatabaseParentActionDispatcher.dispatchParentActionSync( + DeleteCategoryAction( + categoryId = categoryId + ), + database + ) + } + } + } + + run { + // apply category base data + val newCategories = status.newCategoryBaseData + + if (newCategories.isNotEmpty()) { + newCategories.forEach { + val newCategory = it + val oldCategory = database.category().getCategoryByIdSync(it.categoryId) + + DatabaseValidation.assertChildExists(database, newCategory.childId) + + if (oldCategory == null) { + // create new category + + database.category().addCategory(Category( + id = newCategory.categoryId, + childId = newCategory.childId, + title = newCategory.title, + blockedMinutesInWeek = newCategory.blockedMinutesInWeek, + extraTimeInMillis = newCategory.extraTimeInMillis, + temporarilyBlocked = newCategory.temporarilyBlocked, + baseVersion = newCategory.baseDataVersion, + assignedAppsVersion = "", + timeLimitRulesVersion = "", + usedTimesVersion = "", + parentCategoryId = newCategory.parentCategoryId + )) + } else { + val updatedCategory = oldCategory.copy( + childId = newCategory.childId, + title = newCategory.title, + blockedMinutesInWeek = newCategory.blockedMinutesInWeek, + extraTimeInMillis = newCategory.extraTimeInMillis, + temporarilyBlocked = newCategory.temporarilyBlocked, + baseVersion = newCategory.baseDataVersion, + parentCategoryId = newCategory.parentCategoryId + ) + + if (updatedCategory != oldCategory) { + database.category().updateCategorySync(updatedCategory) + } + } + } + } + } + + run { + // apply used times + + val newUsedTimes = status.newCategoryUsedTimes + + newUsedTimes.forEach { + newUsedTime -> + val categoryId = newUsedTime.categoryId + + DatabaseValidation.assertCategoryExists(database, categoryId) + + // replace items + database.usedTimes().deleteUsedTimeItems(categoryId) + database.usedTimes().insertUsedTimes( + newUsedTime.usedTimeItems.map { + UsedTimeItem( + dayOfEpoch = it.dayOfEpoch, + usedMillis = it.usedMillis, + categoryId = categoryId + ) + } + ) + + // update version + database.category().updateCategoryUsedTimesVersion( + categoryId = categoryId, + usedTimesVersion = newUsedTime.version + ) + } + } + + run { + // apply assigned apps + val thisDeviceId = database.config().getOwnDeviceIdSync()!! + val thisDeviceEntry = database.device().getDeviceByIdSync(thisDeviceId)!! + val thisDeviceUserCategories = if (thisDeviceEntry.currentUserId == "") + emptyList() + else + database.category().getCategoriesByChildIdSync(thisDeviceEntry.currentUserId) + val thisDeviceUserCategoryIds = thisDeviceUserCategories.map { it.id }.toSet() + + status.newCategoryAssignedApps.forEach { + item -> + + DatabaseValidation.assertCategoryExists(database, item.categoryId) + + database.categoryApp().deleteCategoryAppsByCategoryId(item.categoryId) + database.categoryApp().addCategoryAppsSync(item.assignedApps.map { + CategoryApp( + categoryId = item.categoryId, + packageName = it + ) + }) + + database.category().updateCategoryAssignedAppsVersion( + categoryId = item.categoryId, + assignedAppsVersion = item.version + ) + + if (thisDeviceUserCategoryIds.contains(item.categoryId)) { + runAsync { + platformIntegration.setSuspendedApps(item.assignedApps, false) + } + } + } + } + + run { + // apply time limit rules + status.newCategoryTimeLimitRules.forEach { + newTimeLimitRulesItem -> + + val categoryId = newTimeLimitRulesItem.categoryId + val newRules = newTimeLimitRulesItem.rules + val oldRules = database.timeLimitRules().getTimeLimitRulesByCategorySync(categoryId) + val oldRuleIds = HashSet(oldRules.map { it.id }) + + DatabaseValidation.assertCategoryExists(database, categoryId) + + newRules.forEach { + newRule -> + val oldRule = oldRules.find { it.id == newRule.id } + + if (oldRule == null) { + // create new rule + database.timeLimitRules().addTimeLimitRule(newRule.toRealRule(categoryId)) + } else { + // eventually update rule + oldRuleIds.remove(oldRule.id) + + val newRuleEntry = newRule.toRealRule(categoryId) + + if (newRuleEntry != oldRule) { + database.timeLimitRules().updateTimeLimitRule(newRuleEntry) + } + } + } + + if (oldRuleIds.isNotEmpty()) { + database.timeLimitRules().deleteTimeLimitRulesByIdsSync(oldRuleIds.toList()) + } + + // save new version + database.category().updateCategoryRulesVersion( + categoryId = categoryId, + rulesVersion = newTimeLimitRulesItem.version + ) + } + } + + database.setTransactionSuccessful() + } finally { + database.endTransaction() + } + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/SyncUtil.kt b/app/src/main/java/io/timelimit/android/sync/SyncUtil.kt new file mode 100644 index 0000000..4895949 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/SyncUtil.kt @@ -0,0 +1,235 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync + +import android.util.Log +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.transaction +import io.timelimit.android.livedata.* +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.ServerLogic +import io.timelimit.android.sync.actions.apply.UploadActionsUtil +import io.timelimit.android.sync.network.ClientDataStatus +import io.timelimit.android.sync.network.api.UnauthorizedHttpError +import io.timelimit.android.ui.IsAppInForeground +import io.timelimit.android.work.SyncInBackgroundWorker +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import java.util.* + +class SyncUtil (private val logic: AppLogic) { + companion object { + private val random: Random by lazy { Random() } + private const val LOG_TAG = "SyncUtil" + private val appVersion = BuildConfig.VERSION_CODE.toString() + } + + private val upload = UploadActionsUtil( + database = logic.database + ) + + private val importantSyncRequested = MutableLiveData().apply { value = false } + private val unimportantSyncRequested = MutableLiveData().apply { value = false } + private val veryUnimportantSyncRequested = MutableLiveData().apply { value = false } + + val isNormalSyncRequested = importantSyncRequested.or(unimportantSyncRequested) + val isVeryUnimportantSyncRequested = veryUnimportantSyncRequested.castDown() + + private val lastSync = MutableLiveData().apply { value = 0 } + private val isSyncingLock = Mutex() + private val lastSyncLongAgo = object: LiveData() { + private val setToTrueRunnable = Runnable { + value = true + } + + init { + value = true + + lastSync.ignoreUnchanged().observeForever { + _ -> + + logic.timeApi.cancelScheduledAction(setToTrueRunnable) + logic.timeApi.runDelayed(setToTrueRunnable, 1000 * 60 * 10) // 10 minutes + + value = false + } + } + } + + private val shouldSyncBase = logic.isConnected.and(logic.enable) + private val shouldSyncImportant = importantSyncRequested + private val shouldSyncUnimportant = unimportantSyncRequested.and(IsAppInForeground.isRunning) + private val shouldSyncVeryUnimportant = veryUnimportantSyncRequested.and(lastSyncLongAgo) + + private val shouldSync = shouldSyncBase.and( + shouldSyncImportant.or(shouldSyncUnimportant).or(shouldSyncVeryUnimportant) + ) + + init { + runAsync { + wipeCacheIfUpdated() + + while (true) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "wait until sync should happen") + } + + shouldSync.waitUntilValueMatches { it == true } + + try { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "do sync now") + } + + doSync() + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "sync done - force pause") + } + + importantSyncRequested.value = false + unimportantSyncRequested.value = false + veryUnimportantSyncRequested.value = false + lastSync.value = logic.timeApi.getCurrentUptimeInMillis() + + SyncInBackgroundWorker.deschedule() + + // wait 2 to 3 seconds before any next sync (debounce) + logic.timeApi.sleep((2 * 1000 + random.nextInt(1000)).toLong()) + } catch (ex: Exception) { + // wait 10 to 15 seconds before retrying + + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "sync failed", ex) + } + + importantSyncRequested.value = true + logic.timeApi.sleep(10 * 1000 + random.nextInt(5 * 1000).toLong()) + } + } + } + } + + fun requestImportantSync(enqueueIfOffline: Boolean = false) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "request important sync") + } + + importantSyncRequested.postValue(true) + + if (enqueueIfOffline) { + SyncInBackgroundWorker.enqueueDelayed() + } + } + + fun requestUnimportantSync() { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "request unimportant sync") + } + + unimportantSyncRequested.postValue(true) + } + + suspend fun requestImportantSyncAndWait() { + withContext (Dispatchers.Main) { + importantSyncRequested.value = true + + importantSyncRequested.waitUntilValueMatches { it == false } + } + } + + fun requestVeryUnimportantSync() { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "request very unimportant sync") + } + + veryUnimportantSyncRequested.postValue(true) + } + + suspend fun doSync() { + isSyncingLock.withLock { + val server = logic.serverLogic.getServerConfigCoroutine() + + if (!server.hasAuthToken) { + // no sync enabled + + throw SyncingDisabledException() + } + + try { + pushActions(server = server) + pullStatus(server = server) + } catch (ex: UnauthorizedHttpError) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "authentication error, check if reset should happen") + } + + if (server.api.isDeviceRemoved(server.deviceAuthToken)) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "reset should happen") + } + + logic.appSetupLogic.dangerousRemoteReset() + } else { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "no reset should happen") + } + } + } + } + } + + private suspend fun pushActions(server: ServerLogic.ServerConfig) { + upload.uploadActions(server) + } + + private suspend fun pullStatus(server: ServerLogic.ServerConfig) { + val currentStatus = ClientDataStatus.getClientDataStatusAsync(logic.database) + val serverResponse = server.api.pullChanges(server.deviceAuthToken, currentStatus) + ApplyServerDataStatus.applyServerDataStatusCoroutine(serverResponse, logic.database, logic.platformIntegration) + } + + private suspend fun wipeCacheIfUpdated() { + Threads.database.executeAndWait { + logic.database.transaction().use { + if (logic.database.config().getLastAppVersionWhichSynced() != appVersion) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "app update -> wipe cache") + } + + UploadActionsUtil.deleteAllVersionNumbersSync(logic.database) + + logic.database.config().setLastAppVersionWhichSynced(appVersion) + } else { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "no app update -> keep cache") + } + } + + it.setSuccess() + } + } + } +} + +class SyncingDisabledException: RuntimeException() diff --git a/app/src/main/java/io/timelimit/android/sync/actions/Actions.kt b/app/src/main/java/io/timelimit/android/sync/actions/Actions.kt new file mode 100644 index 0000000..be213ab --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/Actions.kt @@ -0,0 +1,1279 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.actions + +import android.util.JsonReader +import android.util.JsonWriter +import io.timelimit.android.crypto.HexString +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.customtypes.ImmutableBitmask +import io.timelimit.android.data.customtypes.ImmutableBitmaskJson +import io.timelimit.android.data.model.* +import io.timelimit.android.integration.platform.* +import io.timelimit.android.sync.network.ParentPassword +import io.timelimit.android.sync.validation.ListValidation +import org.json.JSONObject +import java.util.* + +// Tip: [Ctrl] + [A] and [Ctrl] + [Shift] + [Minus] make this file easy to read + +/* + * The actions describe things that happen. + * The same actions (should) result in the same state if applied in the same order. + * This actions are used for the remote control and monitoring. + * + * When an action is executed: + * 1. It's validated (the action classes only hold the actions without any validation) + * 2. It's applied at the clients database + * (end here if in local only mode) + * 3. It's queued for uploading + * 4. The client sends all actions to the server + * 5. The client pulls the status from the server + * + * When there was no connection for a longer time, then actions can be merged (only for adding used time) + * + * ID HANDLING + * + * The client generates IDs by itself randomly. The Server uses the same IDs. + * This implies that the Server internally prefixes everything with the id of the family. + * + * CONFLICT HANDLING + * + * - the client attempts to upload his changes first + * - failed actions are ignored -> destroy version number at the client to trigger a full sync + * + * VERSION NUMBERS + * + * - are random strings + * - are kept at actions at the client + * - are modified at the client when dispatching an action failed (to trigger an query) + * - version number for + * - devices (device list + the status of the devices) - saved at the config table + * - installed apps - saved per device at the device table + * - categories (status + config of the category as it is) - saved per category in the category table + * - categories (assigned apps) - saved per category in the category table + * - categories (time limit rules) - saved per category in the category table + * - users as whole - saved at the config table + * - used time items per category - saved at the category table + * + * HANDLING LAGGY CONNECTIONS + * + * - client marks actions as once sent before sending them + * - after that no merging may occur to this actions + * - each actions gets an number (numbers are ascending) + * - server does not process actions when the device already sent one with this number + * - server still sends "new" status of this actions + * - client deletes actions when server confirmed receiving them + */ + +// actions which "implement" this are not synchronized +// interface LocalOnlyAction + +// base types +sealed class Action { + abstract fun serialize(writer: JsonWriter) +} + +sealed class AppLogicAction: Action() +sealed class ParentAction: Action() +sealed class ChildAction: Action() + +// +// now the concrete actions +// + +const val TYPE = "type" + +data class AddUsedTimeAction(val categoryId: String, val dayOfEpoch: Int, val timeToAdd: Int, val extraTimeToSubtract: Int): AppLogicAction() { + init { + IdGenerator.assertIdValid(categoryId) + + if (dayOfEpoch < 0) { + throw IllegalArgumentException() + } + + if (timeToAdd < 0) { + throw IllegalArgumentException() + } + + if (extraTimeToSubtract < 0) { + throw IllegalArgumentException() + } + } + + companion object { + const val TYPE_VALUE = "ADD_USED_TIME" + private const val CATEGORY_ID = "categoryId" + private const val DAY_OF_EPOCH = "day" + private const val TIME_TO_ADD = "timeToAdd" + private const val EXTRA_TIME_TO_SUBTRACT = "extraTimeToSubtract" + + fun parse(action: JSONObject) = AddUsedTimeAction( + categoryId = action.getString(CATEGORY_ID), + dayOfEpoch = action.getInt(DAY_OF_EPOCH), + timeToAdd = action.getInt(TIME_TO_ADD), + extraTimeToSubtract = action.getInt(EXTRA_TIME_TO_SUBTRACT) + ) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CATEGORY_ID).value(this.categoryId) + writer.name(DAY_OF_EPOCH).value(dayOfEpoch) + writer.name(TIME_TO_ADD).value(this.timeToAdd) + writer.name(EXTRA_TIME_TO_SUBTRACT).value(this.extraTimeToSubtract) + + writer.endObject() + } +} + +// data class ClearTemporarilyAllowedAppsAction(val deviceId: String): AppLogicAction(), LocalOnlyAction + +data class InstalledApp(val packageName: String, val title: String, val isLaunchable: Boolean, val recommendation: AppRecommendation) { + companion object { + private const val PACKAGE_NAME = "packageName" + private const val TITLE = "title" + private const val IS_LAUNCHABLE = "isLaunchable" + private const val RECOMMENDATION = "recommendation" + + fun parse(item: JSONObject) = InstalledApp( + packageName = item.getString(PACKAGE_NAME), + title = item.getString(TITLE), + isLaunchable = item.getBoolean(IS_LAUNCHABLE), + recommendation = AppRecommendationJson.parse(item.getString(RECOMMENDATION)) + ) + + fun parse(reader: JsonReader): InstalledApp { + var packageName: String? = null + var title: String? = null + var isLaunchable: Boolean? = null + var recommendation: AppRecommendation? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + PACKAGE_NAME -> packageName = reader.nextString() + TITLE -> title = reader.nextString() + IS_LAUNCHABLE -> isLaunchable = reader.nextBoolean() + RECOMMENDATION -> recommendation = AppRecommendationJson.parse(reader.nextString()) + else -> reader.skipValue() + } + } + reader.endObject() + + return InstalledApp( + packageName = packageName!!, + title = title!!, + isLaunchable = isLaunchable!!, + recommendation = recommendation!! + ) + } + + fun parseList(reader: JsonReader): List { + val result = ArrayList() + + reader.beginArray() + while (reader.hasNext()) { + result.add(parse(reader)) + } + reader.endArray() + + return Collections.unmodifiableList(result) + } + } + + fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(PACKAGE_NAME).value(packageName) + writer.name(TITLE).value(title) + writer.name(IS_LAUNCHABLE).value(isLaunchable) + writer.name(RECOMMENDATION).value(AppRecommendationJson.serialize(recommendation)) + + writer.endObject() + } +} +data class AddInstalledAppsAction(val apps: List): AppLogicAction() { + companion object { + const val TYPE_VALUE = "ADD_INSTALLED_APPS" + private const val APPS = "apps" + + fun parse(action: JSONObject) = AddInstalledAppsAction( + apps = ParseUtils.readObjectArray(action.getJSONArray(APPS)).map { InstalledApp.parse(it) } + ) + } + + init { + ListValidation.assertNotEmptyListWithoutDuplicates(apps.map { it.packageName }) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + + writer.name(APPS) + writer.beginArray() + apps.forEach { it.serialize(writer) } + writer.endArray() + + writer.endObject() + } +} +data class RemoveInstalledAppsAction(val packageNames: List): AppLogicAction() { + companion object { + const val TYPE_VALUE = "REMOVE_INSTALLED_APPS" + private const val PACKAGE_NAMES = "packageNames" + + fun parse(action: JSONObject) = RemoveInstalledAppsAction( + packageNames = ParseUtils.readStringArray(action.getJSONArray(PACKAGE_NAMES)) + ) + } + + init { + ListValidation.assertNotEmptyListWithoutDuplicates(packageNames) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + + writer.name(PACKAGE_NAMES) + writer.beginArray() + packageNames.forEach { writer.value(it) } + writer.endArray() + + writer.endObject() + } +} +object SignOutAtDeviceAction: AppLogicAction() { + const val TYPE_VALUE = "SIGN_OUT_AT_DEVICE" + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + + writer.endObject() + } +} + +data class AddCategoryAppsAction(val categoryId: String, val packageNames: List): ParentAction() { + companion object { + const val TYPE_VALUE = "ADD_CATEGORY_APPS" + private const val CATEGORY_ID = "categoryId" + private const val PACKAGE_NAMES = "packageNames" + + fun parse(action: JSONObject) = AddCategoryAppsAction( + categoryId = action.getString(CATEGORY_ID), + packageNames = ParseUtils.readStringArray(action.getJSONArray(PACKAGE_NAMES)) + ) + } + + init { + IdGenerator.assertIdValid(categoryId) + ListValidation.assertNotEmptyListWithoutDuplicates(packageNames) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CATEGORY_ID).value(categoryId) + + writer.name(PACKAGE_NAMES) + writer.beginArray() + packageNames.forEach { writer.value(it) } + writer.endArray() + + writer.endObject() + } +} +data class RemoveCategoryAppsAction(val categoryId: String, val packageNames: List): ParentAction() { + companion object { + const val TYPE_VALUE = "REMOVE_CATEGORY_APPS" + private const val CATEGORY_ID = "categoryId" + private const val PACKAGE_NAMES = "packageNames" + + fun parse(action: JSONObject) = RemoveCategoryAppsAction( + categoryId = action.getString(CATEGORY_ID), + packageNames = ParseUtils.readStringArray(action.getJSONArray(PACKAGE_NAMES)) + ) + } + + init { + IdGenerator.assertIdValid(categoryId) + ListValidation.assertNotEmptyListWithoutDuplicates(packageNames) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CATEGORY_ID).value(categoryId) + + writer.name(PACKAGE_NAMES) + writer.beginArray() + packageNames.forEach { writer.value(it) } + writer.endArray() + + writer.endObject() + } +} + +data class CreateCategoryAction(val childId: String, val categoryId: String, val title: String): ParentAction() { + companion object { + const val TYPE_VALUE = "CREATE_CATEGORY" + private const val CHILD_ID = "childId" + private const val CATEGORY_ID = "categoryId" + private const val TITLE = "title" + + fun parse(action: JSONObject) = CreateCategoryAction( + childId = action.getString(CHILD_ID), + categoryId = action.getString(CATEGORY_ID), + title = action.getString(TITLE) + ) + } + + init { + IdGenerator.assertIdValid(categoryId) + IdGenerator.assertIdValid(childId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CHILD_ID).value(childId) + writer.name(CATEGORY_ID).value(categoryId) + writer.name(TITLE).value(title) + + writer.endObject() + } +} +data class DeleteCategoryAction(val categoryId: String): ParentAction() { + companion object { + const val TYPE_VALUE = "DELETE_CATEGORY" + private const val CATEGORY_ID = "categoryId" + + fun parse(action: JSONObject) = DeleteCategoryAction( + categoryId = action.getString(CATEGORY_ID) + ) + } + + init { + IdGenerator.assertIdValid(categoryId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CATEGORY_ID).value(categoryId) + + writer.endObject() + } +} +data class UpdateCategoryTitleAction(val categoryId: String, val newTitle: String): ParentAction() { + companion object { + const val TYPE_VALUE = "UPDATE_CATEGORY_TITLE" + private const val CATEGORY_ID = "categoryId" + private const val NEW_TITLE = "newTitle" + + fun parse(action: JSONObject) = UpdateCategoryTitleAction( + categoryId = action.getString(CATEGORY_ID), + newTitle = action.getString(NEW_TITLE) + ) + } + + init { + IdGenerator.assertIdValid(categoryId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CATEGORY_ID).value(categoryId) + writer.name(NEW_TITLE).value(newTitle) + + writer.endObject() + } +} +data class SetCategoryExtraTimeAction(val categoryId: String, val newExtraTime: Long): ParentAction() { + companion object { + const val TYPE_VALUE = "SET_CATEGORY_EXTRA_TIME" + private const val CATEGORY_ID = "categoryId" + private const val NEW_EXTRA_TIME = "newExtraTime" + + fun parse(action: JSONObject) = SetCategoryExtraTimeAction( + categoryId = action.getString(CATEGORY_ID), + newExtraTime = action.getLong(NEW_EXTRA_TIME) + ) + } + + init { + IdGenerator.assertIdValid(categoryId) + + if (newExtraTime < 0) { + throw IllegalArgumentException("newExtraTime must be >= 0") + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CATEGORY_ID).value(categoryId) + writer.name(NEW_EXTRA_TIME).value(newExtraTime) + + writer.endObject() + } +} +data class IncrementCategoryExtraTimeAction(val categoryId: String, val addedExtraTime: Long): ParentAction() { + companion object { + const val TYPE_VALUE = "INCREMENT_CATEGORY_EXTRATIME" + private const val CATEGORY_ID = "categoryId" + private const val ADDED_EXTRA_TIME = "addedExtraTime" + + fun parse(action: JSONObject) = IncrementCategoryExtraTimeAction( + categoryId = action.getString(CATEGORY_ID), + addedExtraTime = action.getLong(ADDED_EXTRA_TIME) + ) + } + + init { + IdGenerator.assertIdValid(categoryId) + + if (addedExtraTime <= 0) { + throw IllegalArgumentException("addedExtraTime must be more than zero") + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CATEGORY_ID).value(categoryId) + writer.name(ADDED_EXTRA_TIME).value(addedExtraTime) + + writer.endObject() + } +} +data class UpdateCategoryTemporarilyBlockedAction(val categoryId: String, val blocked: Boolean): ParentAction() { + companion object { + const val TYPE_VALUE = "UPDATE_CATEGORY_TEMPORARILY_BLOCKED" + private const val CATEGORY_ID = "categoryId" + private const val BLOCKED = "blocked" + + fun parse(action: JSONObject) = UpdateCategoryTemporarilyBlockedAction( + categoryId = action.getString(CATEGORY_ID), + blocked = action.getBoolean(BLOCKED) + ) + } + + init { + IdGenerator.assertIdValid(categoryId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CATEGORY_ID).value(categoryId) + writer.name(BLOCKED).value(blocked) + + writer.endObject() + } +} +data class SetCategoryForUnassignedApps(val childId: String, val categoryId: String): ParentAction() { + // category id can be empty + + companion object { + const val TYPE_VALUE = "SET_CATEGORY_FOR_UNASSIGNED_APPS" + private const val CHILD_ID = "childId" + private const val CATEGORY_ID = "categoryId" + } + + init { + IdGenerator.assertIdValid(childId) + + if (categoryId.isNotEmpty()) { + IdGenerator.assertIdValid(categoryId) + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CHILD_ID).value(childId) + writer.name(CATEGORY_ID).value(categoryId) + + writer.endObject() + } +} +data class SetParentCategory(val categoryId: String, val parentCategory: String): ParentAction() { + // parent category id can be empty + + companion object { + private const val TYPE_VALUE = "SET_PARENT_CATEGORY" + private const val CATEGORY_ID = "categoryId" + private const val PARENT_CATEGORY = "parentCategory" + } + + init { + IdGenerator.assertIdValid(categoryId) + + if (parentCategory.isNotEmpty()) { + IdGenerator.assertIdValid(parentCategory) + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CATEGORY_ID).value(categoryId) + writer.name(PARENT_CATEGORY).value(parentCategory) + + writer.endObject() + } +} + +// DeviceDao + +data class UpdateDeviceStatusAction( + val newProtectionLevel: ProtectionLevel?, + val newUsageStatsPermissionStatus: RuntimePermissionStatus?, + val newNotificationAccessPermission: NewPermissionStatus?, + val newAppVersion: Int?, + val didReboot: Boolean +): AppLogicAction() { + companion object { + const val TYPE_VALUE = "UPDATE_DEVICE_STATUS" + private const val NEW_PROTECTION_LEVEL = "protectionLevel" + private const val NEW_USAGE_STATS_PERMISSION_STATUS = "usageStats" + private const val NEW_NOTIFICATION_ACCESS_PERMISSION = "notificationAccess" + private const val NEW_APP_VERSION = "appVersion" + private const val DID_REBOOT = "didReboot" + + val empty = UpdateDeviceStatusAction( + newProtectionLevel = null, + newUsageStatsPermissionStatus = null, + newNotificationAccessPermission = null, + newAppVersion = null, + didReboot = false + ) + } + + init { + if (newAppVersion != null && newAppVersion < 0) { + throw IllegalArgumentException() + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + + if (newProtectionLevel != null) { + writer.name(NEW_PROTECTION_LEVEL) + writer.value(ProtectionLevelUtil.serialize(newProtectionLevel)) + } + + if (newUsageStatsPermissionStatus != null) { + writer + .name(NEW_USAGE_STATS_PERMISSION_STATUS) + .value(RuntimePermissionStatusUtil.serialize(newUsageStatsPermissionStatus)) + } + + if (newNotificationAccessPermission != null) { + writer + .name(NEW_NOTIFICATION_ACCESS_PERMISSION) + .value(NewPermissionStatusUtil.serialize(newNotificationAccessPermission)) + } + + if (newAppVersion != null) { + writer.name(NEW_APP_VERSION) + writer.value(newAppVersion) + } + + if (didReboot) { + writer.name(DID_REBOOT).value(true) + } + + writer.endObject() + } +} + +data class IgnoreManipulationAction( + val deviceId: String, + val ignoreDeviceAdminManipulation: Boolean, + val ignoreDeviceAdminManipulationAttempt: Boolean, + val ignoreAppDowngrade: Boolean, + val ignoreNotificationAccessManipulation: Boolean, + val ignoreUsageStatsAccessManipulation: Boolean, + val ignoreReboot: Boolean, + val ignoreHadManipulation: Boolean +): ParentAction() { + companion object { + const val TYPE_VALUE = "IGNORE_MANIPULATION" + private const val DEVICE_ID = "deviceId" + private const val IGNORE_ADMIN = "admin" + private const val IGNORE_ADMIN_ATTEMPT = "adminA" + private const val IGNORE_APP_DOWNGRADE = "downgrade" + private const val IGNORE_NOTIFICATION_ACCESS = "notification" + private const val IGNORE_USAGE_STATS_ACCESS = "usageStats" + private const val IGNORE_HAD_MANIPULATION = "hadManipulation" + private const val IGNORE_REBOOT = "reboot" + } + + init { + IdGenerator.assertIdValid(deviceId) + } + + val isEmpty = (!ignoreDeviceAdminManipulation) && + (!ignoreDeviceAdminManipulationAttempt) && + (!ignoreAppDowngrade) && + (!ignoreNotificationAccessManipulation) && + (!ignoreUsageStatsAccessManipulation) && + (!ignoreReboot) && + (!ignoreHadManipulation) + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(DEVICE_ID).value(deviceId) + writer.name(IGNORE_ADMIN).value(ignoreDeviceAdminManipulation) + writer.name(IGNORE_ADMIN_ATTEMPT).value(ignoreDeviceAdminManipulationAttempt) + writer.name(IGNORE_APP_DOWNGRADE).value(ignoreAppDowngrade) + writer.name(IGNORE_NOTIFICATION_ACCESS).value(ignoreNotificationAccessManipulation) + writer.name(IGNORE_USAGE_STATS_ACCESS).value(ignoreUsageStatsAccessManipulation) + writer.name(IGNORE_HAD_MANIPULATION).value(ignoreHadManipulation) + writer.name(IGNORE_REBOOT).value(ignoreReboot) + + writer.endObject() + } +} + +object TriedDisablingDeviceAdminAction: AppLogicAction() { + const val TYPE_VALUE = "TRIED_DISABLING_DEVICE_ADMIN" + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + + writer.endObject() + } +} + +data class UpdateNetworkTimeVerificationAction(val deviceId: String, val mode: NetworkTime): ParentAction() { + companion object { + const val TYPE_VALUE = "UPDATE_NETWORK_TIME_VERIFICATION" + private const val DEVICE_ID = "deviceId" + private const val MODE = "mode" + } + + init { + IdGenerator.assertIdValid(deviceId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(DEVICE_ID).value(deviceId) + writer.name(MODE).value(NetworkTimeJson.serialize(mode)) + + writer.endObject() + } +} + +data class SetDeviceUserAction(val deviceId: String, val userId: String): ParentAction() { + // user id can be an empty string + + companion object { + const val TYPE_VALUE = "SET_DEVICE_USER" + private const val DEVICE_ID = "deviceId" + private const val USER_ID = "userId" + } + + init { + IdGenerator.assertIdValid(deviceId) + + if (userId != "") { + IdGenerator.assertIdValid(userId) + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(DEVICE_ID).value(deviceId) + writer.name(USER_ID).value(userId) + + writer.endObject() + } +} + +data class SetKeepSignedInAction(val deviceId: String, val keepSignedIn: Boolean): ParentAction() { + companion object { + const val TYPE_VALUE = "SET_KEEP_SIGNED_IN" + private const val DEVICE_ID = "deviceId" + private const val KEEP_SIGNED_IN = "keepSignedIn" + } + + init { + IdGenerator.assertIdValid(deviceId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(DEVICE_ID).value(deviceId) + writer.name(KEEP_SIGNED_IN).value(keepSignedIn) + + writer.endObject() + } +} + +data class SetSendDeviceConnected(val deviceId: String, val enable: Boolean): ParentAction() { + companion object { + const val TYPE_VALUE = "SET_SEND_DEVICE_CONNECTED" + private const val DEVICE_ID = "deviceId" + private const val ENABLE = "enable" + } + + init { + IdGenerator.assertIdValid(deviceId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(DEVICE_ID).value(deviceId) + writer.name(ENABLE).value(enable) + + writer.endObject() + } +} + +data class SetDeviceDefaultUserAction(val deviceId: String, val defaultUserId: String): ParentAction() { + companion object { + private const val TYPE_VALUE = "SET_DEVICE_DEFAULT_USER" + private const val DEVICE_ID = "deviceId" + private const val DEFAULT_USER_ID = "defaultUserId" + } + + init { + IdGenerator.assertIdValid(deviceId) + + if (defaultUserId.isNotEmpty()) { + IdGenerator.assertIdValid(defaultUserId) + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(DEVICE_ID).value(deviceId) + writer.name(DEFAULT_USER_ID).value(defaultUserId) + + writer.endObject() + } +} + +data class SetDeviceDefaultUserTimeoutAction(val deviceId: String, val timeout: Int): ParentAction() { + companion object { + private const val TYPE_VALUE = "SET_DEVICE_DEFAULT_USER_TIMEOUT" + private const val DEVICE_ID = "deviceId" + private const val TIMEOUT = "timeout" + } + + init { + IdGenerator.assertIdValid(deviceId) + + if (timeout < 0) { + throw IllegalArgumentException("can not set a negative default user timeout") + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(DEVICE_ID).value(deviceId) + writer.name(TIMEOUT).value(timeout) + + writer.endObject() + } +} + +data class SetConsiderRebootManipulationAction(val deviceId: String, val considerRebootManipulation: Boolean): ParentAction() { + companion object { + private const val TYPE_VALUE = "SET_CONSIDER_REBOOT_MANIPULATION" + private const val DEVICE_ID = "deviceId" + private const val ENABLE = "enable" + } + + init { + IdGenerator.assertIdValid(deviceId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(DEVICE_ID).value(deviceId) + writer.name(ENABLE).value(considerRebootManipulation) + + writer.endObject() + } +} + +data class UpdateCategoryBlockedTimesAction(val categoryId: String, val blockedTimes: ImmutableBitmask): ParentAction() { + companion object { + const val TYPE_VALUE = "UPDATE_CATEGORY_BLOCKED_TIMES" + private const val CATEGORY_ID = "categoryId" + private const val BLOCKED_TIMES = "times" + } + + init { + IdGenerator.assertIdValid(categoryId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CATEGORY_ID).value(categoryId) + writer.name(BLOCKED_TIMES).value(ImmutableBitmaskJson.serialize(blockedTimes)) + + writer.endObject() + } +} + +data class CreateTimeLimitRuleAction(val rule: TimeLimitRule): ParentAction() { + companion object { + const val TYPE_VALUE = "CREATE_TIMELIMIT_RULE" + private const val RULE = "rule" + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + + writer.name(RULE) + rule.serialize(writer) + + writer.endObject() + } +} + +data class UpdateTimeLimitRuleAction(val ruleId: String, val dayMask: Byte, val maximumTimeInMillis: Int, val applyToExtraTimeUsage: Boolean): ParentAction() { + companion object { + const val TYPE_VALUE = "UPDATE_TIMELIMIT_RULE" + private const val RULE_ID = "ruleId" + private const val MAX_TIME_IN_MILLIS = "time" + private const val DAY_MASK = "days" + private const val APPLY_TO_EXTRA_TIME_USAGE = "extraTime" + } + + init { + IdGenerator.assertIdValid(ruleId) + + if (maximumTimeInMillis < 0) { + throw IllegalArgumentException() + } + + if (dayMask < 0 || dayMask > (1 or 2 or 4 or 8 or 16 or 32 or 64)) { + throw IllegalArgumentException() + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(RULE_ID).value(ruleId) + writer.name(MAX_TIME_IN_MILLIS).value(maximumTimeInMillis) + writer.name(DAY_MASK).value(dayMask) + writer.name(APPLY_TO_EXTRA_TIME_USAGE).value(applyToExtraTimeUsage) + + writer.endObject() + } +} + +data class DeleteTimeLimitRuleAction(val ruleId: String): ParentAction() { + companion object { + const val TYPE_VALUE = "DELETE_TIMELIMIT_RULE" + private const val RULE_ID = "ruleId" + + fun parse(action: JSONObject) = DeleteTimeLimitRuleAction( + ruleId = action.getString(RULE_ID) + ) + } + + init { + IdGenerator.assertIdValid(ruleId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(RULE_ID).value(this.ruleId) + + writer.endObject() + } +} + +// UserDao +data class AddUserAction(val name: String, val userType: UserType, val password: ParentPassword?, val userId: String, val timeZone: String): ParentAction() { + companion object { + const val TYPE_VALUE = "ADD_USER" + private const val USER_ID = "userId" + private const val USER_TYPE = "userType" + private const val NAME = "name" + private const val PASSWORD = "password" + private const val TIMEZONE = "timeZone" + + fun parse(action: JSONObject): AddUserAction { + var password: ParentPassword? = null + val passwordObject = action.getJSONObject(PASSWORD) + + if (passwordObject != null) { + password = ParentPassword.parse(passwordObject) + } + + return AddUserAction( + name = action.getString(NAME), + userType = UserTypeJson.parse(action.getString(USER_TYPE)), + password = password, + userId = action.getString(USER_ID), + timeZone = action.getString(TIMEZONE) + ) + } + } + + init { + if (userType == UserType.Parent) { + password!! + } + + IdGenerator.assertIdValid(userId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(NAME).value(name) + writer.name(USER_TYPE).value(UserTypeJson.serialize(userType)) + writer.name(USER_ID).value(userId) + writer.name(TIMEZONE).value(timeZone) + + if (password != null) { + writer.name(PASSWORD) + password.serialize(writer) + } + + writer.endObject() + } +} + +data class ChangeParentPasswordAction( + val parentUserId: String, + val newPasswordFirstHash: String, + val newPasswordSecondSalt: String, + val newPasswordSecondHashEncrypted: String, + val integrity: String // SHA512(old password second hash + parent user id + new password first hash + new password second salt + new password second hash encrypted) as hex string +): ParentAction() { + companion object { + const val TYPE_VALUE = "CHANGE_PARENT_PASSWORD" + private const val PARENT_USER_ID = "userId" + private const val NEW_PASSWORD_FIRST_HASH = "hash" + private const val NEW_PASSWORD_SECOND_SALT = "secondSalt" + private const val NEW_PASSWORD_SECOND_HASH_ENCRYPTED = "secondHashEncrypted" + private const val INTEGRITY = "integrity" + } + + init { + IdGenerator.assertIdValid(parentUserId) + + if (newPasswordFirstHash.isEmpty() || newPasswordSecondSalt.isEmpty() || newPasswordSecondHashEncrypted.isEmpty() || integrity.isEmpty()) { + throw IllegalArgumentException("missing required parameter") + } + + if (integrity.length != 128) { + throw IllegalArgumentException("wrong length of integrity data") + } + + HexString.assertIsHexString(integrity) + HexString.assertIsHexString(newPasswordSecondHashEncrypted) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(PARENT_USER_ID).value(parentUserId) + writer.name(NEW_PASSWORD_FIRST_HASH).value(newPasswordFirstHash) + writer.name(NEW_PASSWORD_SECOND_SALT).value(newPasswordSecondSalt) + writer.name(NEW_PASSWORD_SECOND_HASH_ENCRYPTED).value(newPasswordSecondHashEncrypted) + writer.name(INTEGRITY).value(integrity) + + writer.endObject() + } +} + +data class UpdateParentNotificationFlagsAction(val parentId: String, val flags: Int, val set: Boolean): ParentAction() { + companion object { + private const val TYPE_VALUE = "UPDATE_PARENT_NOTIFICATION_FLAGS" + private const val PARENT_ID = "parentId" + private const val FLAGS = "flags" + private const val SET = "set" + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(PARENT_ID).value(parentId) + writer.name(FLAGS).value(flags) + writer.name(SET).value(set) + + writer.endObject() + } +} + +data class RemoveUserAction(val userId: String, val authentication: String?): ParentAction() { + companion object { + const val TYPE_VALUE = "REMOVE_USER" + private const val USER_ID = "userId" + private const val AUTHENTICATION = "authentication" + } + + init { + IdGenerator.assertIdValid(userId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(USER_ID).value(userId) + + if (authentication != null) { + writer.name(AUTHENTICATION).value(authentication) + } + + writer.endObject() + } +} + +data class SetUserDisableLimitsUntilAction(val childId: String, val timestamp: Long): ParentAction() { + companion object { + const val TYPE_VALUE = "SET_USER_DISABLE_LIMITS_UNTIL" + private const val CHILD_ID = "childId" + private const val TIMESTAMP = "time" + } + + init { + IdGenerator.assertIdValid(childId) + + if (timestamp < 0) { + throw IllegalArgumentException() + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CHILD_ID).value(childId) + writer.name(TIMESTAMP).value(timestamp) + + writer.endObject() + } +} + +data class UpdateDeviceNameAction(val deviceId: String, val name: String): ParentAction() { + companion object { + const val TYPE_VALUE = "UPDATE_DEVICE_NAME" + private const val DEVICE_ID = "deviceId" + private const val NAME = "name" + } + + init { + IdGenerator.assertIdValid(deviceId) + + if (name.isBlank()) { + throw IllegalArgumentException("new device name must not be blank") + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(DEVICE_ID).value(deviceId) + writer.name(NAME).value(name) + + writer.endObject() + } +} + +data class SetRelaxPrimaryDeviceAction(val userId: String, val relax: Boolean): ParentAction() { + companion object { + const val TYPE_VALUE = "SET_RELAX_PRIMARY_DEVICE" + private const val USER_ID = "userId" + private const val RELAX = "relax" + } + + init { + IdGenerator.assertIdValid(userId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(USER_ID).value(userId) + writer.name(RELAX).value(relax) + + writer.endObject() + } +} + +data class SetUserTimezoneAction(val userId: String, val timezone: String): ParentAction() { + companion object { + private const val TYPE_VALUE = "SET_USER_TIMEZONE" + private const val USER_ID = "userId" + private const val TIMEZONE = "timezone" + } + + init { + IdGenerator.assertIdValid(userId) + + if (timezone.isBlank()) { + throw IllegalArgumentException("tried to set timezone to empty") + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(USER_ID).value(userId) + writer.name(TIMEZONE).value(timezone) + + writer.endObject() + } +} + +data class SetChildPasswordAction(val childId: String, val newPassword: ParentPassword): ParentAction() { + companion object { + private const val TYPE_VALUE = "SET_CHILD_PASSWORD" + private const val CHILD_ID = "childId" + private const val NEW_PASSWORD = "newPassword" + } + + init { + IdGenerator.assertIdValid(childId) + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CHILD_ID).value(childId) + + writer.name(NEW_PASSWORD) + newPassword.serialize(writer) + + writer.endObject() + } +} + +data class RenameChildAction(val childId: String, val newName: String): ParentAction() { + companion object { + private const val TYPE_VALUE = "RENAME_CHILD" + private const val CHILD_ID = "childId" + private const val NEW_NAME = "newName" + } + + init { + IdGenerator.assertIdValid(childId) + + if (newName.isEmpty()) { + throw IllegalArgumentException("newName must not be empty") + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + writer.name(CHILD_ID).value(childId) + writer.name(NEW_NAME).value(newName) + + writer.endObject() + } +} + +// child actions +object ChildSignInAction: ChildAction() { + private const val TYPE_VALUE = "CHILD_SIGN_IN" + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + + writer.endObject() + } +} + +data class ChildChangePasswordAction(val password: ParentPassword): ChildAction() { + companion object { + private const val TYPE_VALUE = "CHILD_CHANGE_PASSWORD" + private const val PASSWORD = "password" + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(TYPE).value(TYPE_VALUE) + + writer.name(PASSWORD) + password.serialize(writer) + + writer.endObject() + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/actions/DatabaseValidation.kt b/app/src/main/java/io/timelimit/android/sync/actions/DatabaseValidation.kt new file mode 100644 index 0000000..f5f5e1f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/DatabaseValidation.kt @@ -0,0 +1,49 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.actions + +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.UserType + +object DatabaseValidation { + fun assertCategoryExists(database: Database, categoryId: String) { + database.category().getCategoryByIdSync(categoryId) + ?:throw IllegalArgumentException("category with the specified id does not exist") + } + + fun assertChildExists(database: Database, childId: String) { + val userEntry = database.user().getUserByIdSync(childId) + + if (userEntry == null || userEntry.type != UserType.Child) { + throw IllegalArgumentException("child with the specified id does not exist") + } + } + + fun assertUserExists(database: Database, userId: String) { + database.user().getUserByIdSync(userId) + ?:throw IllegalArgumentException("user with the specified id does not exist") + } + + fun assertTimelimitRuleExists(database: Database, timeLimitRuleId: String) { + database.timeLimitRules().getTimeLimitRuleByIdSync(timeLimitRuleId) + ?:throw IllegalArgumentException("time limit rule with the specified id does not exist") + } + + fun assertDeviceExists(database: Database, devcieId: String) { + database.device().getDeviceByIdSync(devcieId) + ?:throw IllegalArgumentException("device does not exist") + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/actions/ParseUtils.kt b/app/src/main/java/io/timelimit/android/sync/actions/ParseUtils.kt new file mode 100644 index 0000000..c98e7b1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/ParseUtils.kt @@ -0,0 +1,23 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.actions + +import org.json.JSONArray + +object ParseUtils { + fun readStringArray(array: JSONArray) = (0..(array.length() - 1)).map { array.getString(it) } + fun readObjectArray(array: JSONArray) = (0..(array.length() - 1)).map { array.getJSONObject(it) } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/actions/Parser.kt b/app/src/main/java/io/timelimit/android/sync/actions/Parser.kt new file mode 100644 index 0000000..9423b7c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/Parser.kt @@ -0,0 +1,65 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.actions + +import org.json.JSONObject + +object ActionParser { + fun parseAppLogicAction(action: JSONObject): AppLogicAction = when(action.getString(TYPE)) { + AddUsedTimeAction.TYPE_VALUE -> AddUsedTimeAction.parse(action) + AddInstalledAppsAction.TYPE_VALUE -> AddInstalledAppsAction.parse(action) + RemoveInstalledAppsAction.TYPE_VALUE -> RemoveInstalledAppsAction.parse(action) + TriedDisablingDeviceAdminAction.TYPE_VALUE -> TriedDisablingDeviceAdminAction + SignOutAtDeviceAction.TYPE_VALUE -> SignOutAtDeviceAction + else -> throw IllegalStateException() + } + + fun parseParentAction(action: JSONObject): ParentAction = when(action.getString(TYPE)) { + AddCategoryAppsAction.TYPE_VALUE -> AddCategoryAppsAction.parse(action) + RemoveCategoryAppsAction.TYPE_VALUE -> RemoveCategoryAppsAction.parse(action) + CreateCategoryAction.TYPE_VALUE -> CreateCategoryAction.parse(action) + DeleteCategoryAction.TYPE_VALUE -> DeleteCategoryAction.parse(action) + UpdateCategoryTitleAction.TYPE_VALUE -> UpdateCategoryTitleAction.parse(action) + SetCategoryExtraTimeAction.TYPE_VALUE -> SetCategoryExtraTimeAction.parse(action) + IncrementCategoryExtraTimeAction.TYPE_VALUE -> IncrementCategoryExtraTimeAction.parse(action) + UpdateCategoryTemporarilyBlockedAction.TYPE_VALUE -> UpdateCategoryTemporarilyBlockedAction.parse(action) + DeleteTimeLimitRuleAction.TYPE_VALUE -> DeleteTimeLimitRuleAction.parse(action) + AddUserAction.TYPE_VALUE -> AddUserAction.parse(action) + // actions without parser: + // UpdateCategoryBlockedTimesAction + // AddTimeLimitRuleAction + // UpdateTimeLimitRuleAction + // UpdateNetworkTimeVerificationAction + // SetDeviceUserAction + // SetUserDisableLimitsUntilAction + // UpdateDeviceNameAction + // RemoveUserAction + // ChangeParentPasswordAction + // IgnoreManipulationAction + // SetKeepSignedInAction + // SetCategoryForUnassignedApps + // SetParentCategory + // SetRelaxPrimaryDeviceAction + // SetUserTimezoneAction + // SetDeviceDefaultUserAction + // SetChildPasswordAction + // SetDeviceDefaultUserTimeoutAction + // SetConsiderRebootManipulationAction + // RenameChildAction + // UpdateParentNotificationFlagsAction + else -> throw IllegalStateException() + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/actions/Serializer.kt b/app/src/main/java/io/timelimit/android/sync/actions/Serializer.kt new file mode 100644 index 0000000..a4e5709 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/Serializer.kt @@ -0,0 +1,39 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.actions + +import android.util.JsonWriter +import java.io.StringWriter + +object SerializationUtil { + fun serializeAction(action: ParentAction): String { + val stringWriter = StringWriter() + val jsonWriter = JsonWriter(stringWriter) + + action.serialize(jsonWriter) + + return stringWriter.buffer.toString() + } + + fun serializeAction(action: AppLogicAction): String { + val stringWriter = StringWriter() + val jsonWriter = JsonWriter(stringWriter) + + action.serialize(jsonWriter) + + return stringWriter.buffer.toString() + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/actions/apply/ApplyAction.kt b/app/src/main/java/io/timelimit/android/sync/actions/apply/ApplyAction.kt new file mode 100644 index 0000000..0d7195e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/apply/ApplyAction.kt @@ -0,0 +1,271 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.actions.apply + +import android.util.JsonWriter +import android.util.Log +import io.timelimit.android.BuildConfig +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.crypto.Sha512 +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.PendingSyncAction +import io.timelimit.android.data.model.PendingSyncActionType +import io.timelimit.android.data.model.UserType +import io.timelimit.android.data.transaction +import io.timelimit.android.integration.platform.PlatformIntegration +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.ManipulationLogic +import io.timelimit.android.sync.SyncUtil +import io.timelimit.android.sync.actions.* +import io.timelimit.android.sync.actions.dispatch.LocalDatabaseAppLogicActionDispatcher +import io.timelimit.android.sync.actions.dispatch.LocalDatabaseChildActionDispatcher +import io.timelimit.android.sync.actions.dispatch.LocalDatabaseParentActionDispatcher +import org.json.JSONObject +import java.io.StringWriter + +object ApplyActionUtil { + private const val LOG_TAG = "ApplyActionUtil" + + suspend fun applyAppLogicAction(action: AppLogicAction, appLogic: AppLogic) { + applyAppLogicAction(action, appLogic.database, appLogic.syncUtil, appLogic.manipulationLogic) + } + + private suspend fun applyAppLogicAction(action: AppLogicAction, database: Database, syncUtil: SyncUtil, manipulationLogic: ManipulationLogic) { + Threads.database.executeAndWait { + database.transaction().use { + LocalDatabaseAppLogicActionDispatcher.dispatchAppLogicActionSync(action, database.config().getOwnDeviceIdSync()!!, database, manipulationLogic) + + if (isSyncEnabled(database)) { + if (action is AddUsedTimeAction) { + val previousAction = database.pendingSyncAction().getLatestUnscheduledActionSync() + + if (previousAction != null && previousAction.type == PendingSyncActionType.AppLogic) { + val parsed = ActionParser.parseAppLogicAction(JSONObject(previousAction.encodedAction)) + + if (parsed is AddUsedTimeAction && parsed.categoryId == action.categoryId && parsed.dayOfEpoch == action.dayOfEpoch) { + // update the previous action + database.pendingSyncAction().updateEncodedActionSync( + sequenceNumber = previousAction.sequenceNumber, + action = StringWriter().apply { + JsonWriter(this).apply { + parsed.copy( + timeToAdd = parsed.timeToAdd + action.timeToAdd, + extraTimeToSubtract = parsed.extraTimeToSubtract + action.extraTimeToSubtract + ).serialize(this) + } + }.toString() + ) + + database.setTransactionSuccessful() + syncUtil.requestVeryUnimportantSync() + + return@executeAndWait + } + } + } + + val serializedAction = StringWriter().apply { + JsonWriter(this).apply { + action.serialize(this) + } + }.toString() + + database.pendingSyncAction().addSyncActionSync(PendingSyncAction( + sequenceNumber = database.config().getNextSyncActionSequenceActionAndIncrementIt(), + encodedAction = serializedAction, + integrity = "", + scheduledForUpload = false, + type = PendingSyncActionType.AppLogic, + userId = "" + )) + + if (action is AddUsedTimeAction) { + syncUtil.requestVeryUnimportantSync() + } else { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "request important sync due to dispatched app logic action") + } + + syncUtil.requestImportantSync() + } + } + + database.setTransactionSuccessful() + } + } + } + + suspend fun applyParentAction(action: ParentAction, database: Database, authentication: ApplyActionParentAuthentication, syncUtil: SyncUtil, platformIntegration: PlatformIntegration) { + Threads.database.executeAndWait { + database.transaction().use { + val deviceUserIdBeforeDispatchingForDeviceAuth = if (authentication is ApplyActionParentDeviceAuthentication) { + val deviceId = database.config().getOwnDeviceIdSync()!! + val device = database.device().getDeviceByIdSync(deviceId)!! + val user = database.user().getUserByIdSync(device.currentUserId) + + if (user?.type != UserType.Parent) { + throw IllegalStateException("no parent assigned to device") + } + + if (!device.isUserKeptSignedIn) { + throw IllegalArgumentException("user is not kept signed in") + } + + user.id + } else null + + LocalDatabaseParentActionDispatcher.dispatchParentActionSync(action, database) + + // disable suspending the assigned app + if (action is AddCategoryAppsAction) { + val thisDeviceId = database.config().getOwnDeviceIdSync()!! + val thisDeviceEntry = database.device().getDeviceByIdSync(thisDeviceId)!! + + if (thisDeviceEntry.currentUserId != "") { + val userCategories = database.category().getCategoriesByChildIdSync(thisDeviceEntry.currentUserId) + + if (userCategories.find { category -> category.id == action.categoryId } != null) { + platformIntegration.setSuspendedApps(action.packageNames, false) + } + } + } + + if (action is SetDeviceUserAction) { + val thisDeviceId = database.config().getOwnDeviceIdSync()!! + + if (action.deviceId == thisDeviceId) { + platformIntegration.stopSuspendingForAllApps() + } + } + + if (isSyncEnabled(database)) { + val serializedAction = StringWriter().apply { + JsonWriter(this).apply { + action.serialize(this) + } + }.toString() + + val sequenceNumber = database.config().getNextSyncActionSequenceActionAndIncrementIt() + + val pendingAction = when (authentication) { + is ApplyActionParentPasswordAuthentication -> { + val integrityData = sequenceNumber.toString() + + database.config().getOwnDeviceIdSync() + + authentication.secondPasswordHash + + serializedAction + + val hashedIntegrityData = Sha512.hashSync(integrityData) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "integrity data: $integrityData") + Log.d(LOG_TAG, "integrity hash: $hashedIntegrityData") + } + + PendingSyncAction( + sequenceNumber = sequenceNumber, + encodedAction = serializedAction, + integrity = hashedIntegrityData, + scheduledForUpload = false, + type = PendingSyncActionType.Parent, + userId = authentication.parentUserId + ) + } + ApplyActionParentDeviceAuthentication -> { + PendingSyncAction( + sequenceNumber = sequenceNumber, + encodedAction = serializedAction, + integrity = "device", + scheduledForUpload = false, + type = PendingSyncActionType.Parent, + userId = deviceUserIdBeforeDispatchingForDeviceAuth!! + ) + } + } + + database.pendingSyncAction().addSyncActionSync(pendingAction) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "request important sync due to dispatched parent action") + } + + syncUtil.requestImportantSync(enqueueIfOffline = true) + } + + database.setTransactionSuccessful() + } + } + } + + suspend fun applyChildAction(action: ChildAction, database: Database, authentication: ApplyActionChildAuthentication, syncUtil: SyncUtil) { + Threads.database.executeAndWait { + database.transaction().use { + LocalDatabaseChildActionDispatcher.dispatchChildActionSync(action, authentication.childUserId, database) + + if (isSyncEnabled(database)) { + val serializedAction = StringWriter().apply { + JsonWriter(this).apply { + action.serialize(this) + } + }.toString() + + val sequenceNumber = database.config().getNextSyncActionSequenceActionAndIncrementIt() + + val integrityData = sequenceNumber.toString() + + database.config().getOwnDeviceIdSync() + + authentication.secondPasswordHash + + serializedAction + + val hashedIntegrityData = Sha512.hashSync(integrityData) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "integrity data: $integrityData") + Log.d(LOG_TAG, "integrity hash: $hashedIntegrityData") + } + + database.pendingSyncAction().addSyncActionSync( + PendingSyncAction( + sequenceNumber = sequenceNumber, + encodedAction = serializedAction, + integrity = hashedIntegrityData, + scheduledForUpload = false, + type = PendingSyncActionType.Child, + userId = authentication.childUserId + ) + ) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "request important sync due to dispatched child action") + } + + syncUtil.requestImportantSync(enqueueIfOffline = true) + } + + database.setTransactionSuccessful() + } + } + } + + private fun isSyncEnabled(database: Database): Boolean { + return database.config().getDeviceAuthTokenSync() != "" + } +} + +sealed class ApplyActionParentAuthentication +object ApplyActionParentDeviceAuthentication: ApplyActionParentAuthentication() +data class ApplyActionParentPasswordAuthentication(val parentUserId: String, val secondPasswordHash: String): ApplyActionParentAuthentication() + +data class ApplyActionChildAuthentication(val childUserId: String, val secondPasswordHash: String) \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/actions/apply/UploadActionsUtil.kt b/app/src/main/java/io/timelimit/android/sync/actions/apply/UploadActionsUtil.kt new file mode 100644 index 0000000..be36c86 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/apply/UploadActionsUtil.kt @@ -0,0 +1,130 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.actions.apply + +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.data.Database +import io.timelimit.android.data.transaction +import io.timelimit.android.logic.ServerLogic +import io.timelimit.android.sync.network.ActionUploadItem +import io.timelimit.android.sync.network.ActionUploadRequest + +class UploadActionsUtil(private val database: Database) { + companion object { + private const val BATCH_SIZE = 25 + + fun deleteAllVersionNumbersSync(database: Database) { + database.transaction().use { + transaction -> + + database.config().setUserListVersionSync("") + database.config().setDeviceListVersionSync("") + database.device().deleteAllInstalledAppsVersions() + database.category().deleteAllCategoriesVersionNumbers() + + transaction.setSuccess() + } + } + } + + suspend fun uploadActions(server: ServerLogic.ServerConfig) { + while (uploadActionsRound(server)) { + // do nothing + } + } + + private suspend fun uploadActionsRound(server: ServerLogic.ServerConfig): Boolean { + val didUploadSomething = handleUploadIfItemsWhileAvailable(server) + val didPrepareSomething = markItemsForUploadingIfNeeded() + + return didUploadSomething or didPrepareSomething + } + + private suspend fun markItemsForUploadingIfNeeded(): Boolean { + return Threads.database.executeAndWait { + database.transaction().use { + transaction -> + + val preparedItems = database.pendingSyncAction().countScheduledActionsSync() + val unpreparedItems = database.pendingSyncAction().countUnscheduledActionsSync() + val missingItems = BATCH_SIZE - preparedItems + + if (missingItems > 0 && unpreparedItems > 0) { + val items = database.pendingSyncAction().getNextUnscheduledActionsSync(missingItems.toInt()) + database.pendingSyncAction().markSyncActionsAsScheduledForUpload(items.last().sequenceNumber) + + transaction.setSuccess() + true + } else { + false + } + } + } + } + + private suspend fun handleUploadIfItemsWhileAvailable(server: ServerLogic.ServerConfig): Boolean { + var hadOneIteration = false + + while (handleUploadIfItemsAreAvailable(server)) { + hadOneIteration = true + } + + return hadOneIteration + } + + private suspend fun handleUploadIfItemsAreAvailable(server: ServerLogic.ServerConfig): Boolean { + val pendingItems = Threads.database.executeAndWait { + database.pendingSyncAction().getScheduledActionsSync(BATCH_SIZE) + } + + if (pendingItems.isEmpty()) { + return false + } + + val response = server.api.pushChanges( + ActionUploadRequest( + deviceAuthToken = server.deviceAuthToken, + actions = pendingItems.map { + ActionUploadItem( + encodedAction = it.encodedAction, + integrity = it.integrity, + sequenceNumber = it.sequenceNumber, + type = it.type, + userId = it.userId + ) + } + ) + ) + + Threads.database.executeAndWait { + database.transaction().use { + transaction -> + + if (response.shouldDoFullSync) { + deleteAllVersionNumbersSync(database) + } + + // delete now processed items + database.pendingSyncAction().removeSyncActionsBySequenceNumbersSync(pendingItems.map { it.sequenceNumber }) + + transaction.setSuccess() + } + } + + return true + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/actions/dispatch/AppLogicAction.kt b/app/src/main/java/io/timelimit/android/sync/actions/dispatch/AppLogicAction.kt new file mode 100644 index 0000000..33d8351 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/dispatch/AppLogicAction.kt @@ -0,0 +1,217 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.actions.dispatch + +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.App +import io.timelimit.android.data.model.UsedTimeItem +import io.timelimit.android.integration.platform.NewPermissionStatusUtil +import io.timelimit.android.integration.platform.ProtectionLevelUtil +import io.timelimit.android.integration.platform.RuntimePermissionStatusUtil +import io.timelimit.android.logic.ManipulationLogic +import io.timelimit.android.sync.actions.* + +object LocalDatabaseAppLogicActionDispatcher { + fun dispatchAppLogicActionSync(action: AppLogicAction, deviceId: String, database: Database, manipulationLogic: ManipulationLogic) { + DatabaseValidation.assertDeviceExists(database, deviceId) + + database.beginTransaction() + + try { + when(action) { + is AddUsedTimeAction -> { + val categoryEntry = database.category().getCategoryByIdSync(action.categoryId)!! + val parentCategoryEntry = if (categoryEntry.parentCategoryId.isNotEmpty()) + database.category().getCategoryByIdSync(categoryEntry.parentCategoryId) + else + null + + fun handleAddUsedTime(categoryId: String) { + // try to update + val updatedRows = database.usedTimes().addUsedTime( + categoryId = categoryId, + timeToAdd = action.timeToAdd, + dayOfEpoch = action.dayOfEpoch + ) + + if (updatedRows == 0) { + // create new entry + + database.usedTimes().insertUsedTime(UsedTimeItem( + categoryId = categoryId, + dayOfEpoch = action.dayOfEpoch, + usedMillis = action.timeToAdd.toLong() + )) + } + + + if (action.extraTimeToSubtract != 0) { + database.category().subtractCategoryExtraTime( + categoryId = categoryId, + removedExtraTime = action.extraTimeToSubtract + ) + } + } + + handleAddUsedTime(categoryEntry.id) + + if (parentCategoryEntry?.childId == categoryEntry.childId) { + handleAddUsedTime(parentCategoryEntry.id) + } + + null + } + is AddInstalledAppsAction -> { + database.app().addAppsSync( + action.apps.map { + App( + deviceId = deviceId, + packageName = it.packageName, + title = it.title, + isLaunchable = it.isLaunchable, + recommendation = it.recommendation + ) + } + ) + } + is RemoveInstalledAppsAction -> { + database.app().removeAppsByDeviceIdAndPackageNamesSync( + deviceId = deviceId, + packageNames = action.packageNames + ) + } + is UpdateDeviceStatusAction -> { + var device = database.device().getDeviceByIdSync(deviceId)!! + + if (action.newProtectionLevel != null) { + if (device.currentProtectionLevel != action.newProtectionLevel) { + device = device.copy( + currentProtectionLevel = action.newProtectionLevel + ) + + if (ProtectionLevelUtil.toInt(action.newProtectionLevel) > ProtectionLevelUtil.toInt(device.highestProtectionLevel)) { + device = device.copy( + highestProtectionLevel = action.newProtectionLevel + ) + } + + if (device.currentProtectionLevel != device.highestProtectionLevel) { + device = device.copy(hadManipulation = true) + } + } + } + + if (action.newUsageStatsPermissionStatus != null) { + if (device.currentUsageStatsPermission != action.newUsageStatsPermissionStatus) { + device = device.copy( + currentUsageStatsPermission = action.newUsageStatsPermissionStatus + ) + + if (RuntimePermissionStatusUtil.toInt(action.newUsageStatsPermissionStatus) > RuntimePermissionStatusUtil.toInt(device.highestUsageStatsPermission)) { + device = device.copy( + highestUsageStatsPermission = action.newUsageStatsPermissionStatus + ) + } + + if (device.currentUsageStatsPermission != device.highestUsageStatsPermission) { + device = device.copy(hadManipulation = true) + } + } + } + + if (action.newNotificationAccessPermission != null) { + if (device.currentNotificationAccessPermission != action.newNotificationAccessPermission) { + device = device.copy( + currentNotificationAccessPermission = action.newNotificationAccessPermission + ) + + if (NewPermissionStatusUtil.toInt(action.newNotificationAccessPermission) > NewPermissionStatusUtil.toInt(device.highestNotificationAccessPermission)) { + device = device.copy( + highestNotificationAccessPermission = action.newNotificationAccessPermission + ) + } + + if (device.currentNotificationAccessPermission != device.highestNotificationAccessPermission) { + device = device.copy(hadManipulation = true) + } + } + } + + if (action.newAppVersion != null) { + if (device.currentAppVersion != action.newAppVersion) { + device = device.copy( + currentAppVersion = action.newAppVersion, + highestAppVersion = Math.max(device.highestAppVersion, action.newAppVersion) + ) + + if (device.currentAppVersion != device.highestAppVersion) { + device = device.copy(hadManipulation = true) + } + } + } + + if (action.didReboot && device.considerRebootManipulation) { + device = device.copy( + manipulationDidReboot = true + ) + } + + database.device().updateDeviceEntry(device) + + if (device.hasActiveManipulationWarning) { + manipulationLogic.lockDeviceSync() + } + + null + } + is TriedDisablingDeviceAdminAction -> { + database.device().updateDeviceEntry( + database.device().getDeviceByIdSync( + database.config().getOwnDeviceIdSync()!! + )!!.copy( + manipulationTriedDisablingDeviceAdmin = true + ) + ) + + manipulationLogic.lockDeviceSync() + + null + } + is SignOutAtDeviceAction -> { + val deviceEntry = database.device().getDeviceByIdSync(database.config().getOwnDeviceIdSync()!!)!! + + if (deviceEntry.defaultUser.isEmpty()) { + throw IllegalStateException("can not sign out without configured default user") + } + + LocalDatabaseParentActionDispatcher.dispatchParentActionSync( + SetDeviceUserAction( + deviceId = deviceEntry.id, + userId = deviceEntry.defaultUser + ), + database + ) + + null + } + }.let { } + + database.setTransactionSuccessful() + } finally { + database.endTransaction() + } + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/actions/dispatch/ChildAction.kt b/app/src/main/java/io/timelimit/android/sync/actions/dispatch/ChildAction.kt new file mode 100644 index 0000000..01c877e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/dispatch/ChildAction.kt @@ -0,0 +1,73 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.actions.dispatch + +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.UserType +import io.timelimit.android.sync.actions.* + +object LocalDatabaseChildActionDispatcher { + fun dispatchChildActionSync(action: ChildAction, childId: String, database: Database) { + DatabaseValidation.assertChildExists(database, childId) + + database.beginTransaction() + + try { + when (action) { + is ChildSignInAction -> { + val deviceId = database.config().getOwnDeviceIdSync()!! + + LocalDatabaseParentActionDispatcher.dispatchParentActionSync( + action = SetDeviceUserAction( + deviceId = deviceId, + userId = childId + ), + database = database + ) + + val userEntry = database.user().getUserByIdSync(childId)!! + + // sign out to prevent way around current device rule + if (userEntry.currentDevice == deviceId) { + database.user().updateUserSync(userEntry.copy( + currentDevice = "" + )) + } + + null + } + is ChildChangePasswordAction -> { + val userEntry = database.user().getUserByIdSync(childId) + + if (userEntry == null || userEntry.type != UserType.Child) { + throw IllegalArgumentException("invalid user entry") + } + + database.user().updateUserSync( + userEntry.copy( + password = action.password.parentPasswordHash, + secondPasswordSalt = action.password.parentPasswordSecondSalt + ) + ) + } + }.let { /* require handling all paths */ } + + database.setTransactionSuccessful() + } finally { + database.endTransaction() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/actions/dispatch/ParentAction.kt b/app/src/main/java/io/timelimit/android/sync/actions/dispatch/ParentAction.kt new file mode 100644 index 0000000..f8f803b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/dispatch/ParentAction.kt @@ -0,0 +1,463 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.actions.dispatch + +import io.timelimit.android.data.Database +import io.timelimit.android.data.customtypes.ImmutableBitmask +import io.timelimit.android.data.model.Category +import io.timelimit.android.data.model.CategoryApp +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.sync.actions.* +import java.util.* + +object LocalDatabaseParentActionDispatcher { + fun dispatchParentActionSync(action: ParentAction, database: Database) { + database.beginTransaction() + + try { + when (action) { + is AddCategoryAppsAction -> { + // validate that the category exists + val categoryEntry = database.category().getCategoryByIdSync(action.categoryId) + ?: throw IllegalArgumentException("category with the specified id does not exist") + + // remove same apps from other categories of the same child + val allCategoriesOfChild = database.category().getCategoriesByChildIdSync(categoryEntry.childId) + + database.categoryApp().removeCategoryAppsSyncByCategoryIds( + packageNames = action.packageNames, + categoryIds = allCategoriesOfChild.map { it.id } + ) + + // add the apps to the new category + database.categoryApp().addCategoryAppsSync( + action.packageNames.map { + CategoryApp( + categoryId = action.categoryId, + packageName = it + ) + } + ) + } + is RemoveCategoryAppsAction -> { + DatabaseValidation.assertCategoryExists(database, action.categoryId) + + // remove the apps from the category + database.categoryApp().removeCategoryAppsSyncByCategoryIds( + packageNames = action.packageNames, + categoryIds = listOf(action.categoryId) + ) + } + is CreateCategoryAction -> { + DatabaseValidation.assertChildExists(database, action.childId) + + // create the category + database.category().addCategory(Category( + id = action.categoryId, + childId = action.childId, + title = action.title, + // nothing blocked by default + blockedMinutesInWeek = ImmutableBitmask(BitSet()), + extraTimeInMillis = 0, + temporarilyBlocked = false, + baseVersion = "", + assignedAppsVersion = "", + timeLimitRulesVersion = "", + usedTimesVersion = "", + parentCategoryId = "" + )) + } + is DeleteCategoryAction -> { + DatabaseValidation.assertCategoryExists(database, action.categoryId) + + // delete all related data and the category + database.timeLimitRules().deleteTimeLimitRulesByCategory(action.categoryId) + database.usedTimes().deleteUsedTimeItems(action.categoryId) + database.categoryApp().deleteCategoryAppsByCategoryId(action.categoryId) + database.user().removeAsCategoryForUnassignedApps(action.categoryId) + database.category().deleteCategory(action.categoryId) + } + is UpdateCategoryTitleAction -> { + DatabaseValidation.assertCategoryExists(database, action.categoryId) + + database.category().updateCategoryTitle( + categoryId = action.categoryId, + newTitle = action.newTitle + ) + } + is SetCategoryExtraTimeAction -> { + DatabaseValidation.assertCategoryExists(database, action.categoryId) + + if (action.newExtraTime < 0) { + throw IllegalArgumentException("invalid new extra time") + } + + database.category().updateCategoryExtraTime(action.categoryId, action.newExtraTime) + } + is IncrementCategoryExtraTimeAction -> { + if (action.addedExtraTime < 0) { + throw IllegalArgumentException("invalid added extra time") + } + + val category = database.category().getCategoryByIdSync(action.categoryId) + ?: throw IllegalArgumentException("category ${action.categoryId} does not exist") + + database.category().incrementCategoryExtraTime(action.categoryId, action.addedExtraTime) + + if (category.parentCategoryId.isNotEmpty()) { + val parentCategory = database.category().getCategoryByIdSync(category.parentCategoryId) + + if (parentCategory?.childId == category.childId) { + database.category().incrementCategoryExtraTime(parentCategory.id, action.addedExtraTime) + } + } + + null + } + is UpdateCategoryTemporarilyBlockedAction -> { + DatabaseValidation.assertCategoryExists(database, action.categoryId) + + database.category().updateCategoryTemporarilyBlocked(action.categoryId, action.blocked) + } + is DeleteTimeLimitRuleAction -> { + DatabaseValidation.assertTimelimitRuleExists(database, action.ruleId) + + database.timeLimitRules().deleteTimeLimitRuleByIdSync(action.ruleId) + } + is AddUserAction -> { + database.user().addUserSync(User( + id = action.userId, + name = action.name, + type = action.userType, + timeZone = action.timeZone, + password = if (action.password == null) "" else action.password.parentPasswordHash, + secondPasswordSalt = if (action.password == null) "" else action.password.parentPasswordSecondSalt, + disableLimitsUntil = 0, + mail = "", + currentDevice = "", + categoryForNotAssignedApps = "", + relaxPrimaryDevice = false, + mailNotificationFlags = 0 + )) + } + is UpdateCategoryBlockedTimesAction -> { + DatabaseValidation.assertCategoryExists(database, action.categoryId) + + database.category().updateCategoryBlockedTimes(action.categoryId, action.blockedTimes) + } + is CreateTimeLimitRuleAction -> { + DatabaseValidation.assertCategoryExists(database, action.rule.categoryId) + + database.timeLimitRules().addTimeLimitRule(action.rule) + } + is UpdateNetworkTimeVerificationAction -> { + DatabaseValidation.assertDeviceExists(database, action.deviceId) + + database.device().updateNetworkTimeVerification( + deviceId = action.deviceId, + mode = action.mode + ) + } + is UpdateTimeLimitRuleAction -> { + val oldRule = database.timeLimitRules().getTimeLimitRuleByIdSync(action.ruleId)!! + + database.timeLimitRules().updateTimeLimitRule(oldRule.copy( + maximumTimeInMillis = action.maximumTimeInMillis, + dayMask = action.dayMask, + applyToExtraTimeUsage = action.applyToExtraTimeUsage + )) + } + is SetDeviceUserAction -> { + DatabaseValidation.assertDeviceExists(database, action.deviceId) + + if (action.userId != "") { + DatabaseValidation.assertUserExists(database, action.userId) + } + + database.device().updateDeviceUser( + deviceId = action.deviceId, + userId = action.userId + ) + } + is SetUserDisableLimitsUntilAction -> { + val affectedRows = database.user().updateDisableChildUserLimitsUntil( + childId = action.childId, + timestamp = action.timestamp + ) + + if (affectedRows == 0) { + throw IllegalArgumentException("provided user id does not exist") + } + + null + } + is UpdateDeviceNameAction -> { + val affectedRows = database.device().updateDeviceName( + deviceId = action.deviceId, + name = action.name + ) + + if (affectedRows == 0) { + throw IllegalArgumentException("provided device id was invalid") + } + + null + } + is RemoveUserAction -> { + // authentication is not checked locally, only at the server + + val userToDelete = database.user().getUserByIdSync(action.userId)!! + + if (userToDelete.type == UserType.Parent) { + val currentParents = database.user().getParentUsersSync() + + if (currentParents.size <= 1) { + throw IllegalStateException("would delete last parent") + } + } + + if (userToDelete.type == UserType.Child) { + val categories = database.category().getCategoriesByChildIdSync(userToDelete.id) + + categories.forEach { + category -> + + dispatchParentActionSync( + DeleteCategoryAction( + categoryId = category.id + ), + database + ) + } + } + + database.device().unassignCurrentUserFromAllDevices(action.userId) + + database.user().deleteUsersByIds(listOf(action.userId)) + } + is ChangeParentPasswordAction -> { + val userEntry = database.user().getUserByIdSync(action.parentUserId) + + if (userEntry == null || userEntry.type != UserType.Parent) { + throw IllegalArgumentException("invalid user entry") + } + + // the client does not have the data to check the integrity + + database.user().updateUserSync( + userEntry.copy( + password = action.newPasswordFirstHash, + secondPasswordSalt = action.newPasswordSecondSalt + ) + ) + } + is IgnoreManipulationAction -> { + val originalDeviceEntry = database.device().getDeviceByIdSync(action.deviceId)!! + var deviceEntry = originalDeviceEntry + + if (action.ignoreDeviceAdminManipulation) { + deviceEntry = deviceEntry.copy(highestProtectionLevel = deviceEntry.currentProtectionLevel) + } + + if (action.ignoreDeviceAdminManipulationAttempt) { + deviceEntry = deviceEntry.copy(manipulationTriedDisablingDeviceAdmin = false) + } + + if (action.ignoreAppDowngrade) { + deviceEntry = deviceEntry.copy(highestAppVersion = deviceEntry.currentAppVersion) + } + + if (action.ignoreNotificationAccessManipulation) { + deviceEntry = deviceEntry.copy(highestNotificationAccessPermission = deviceEntry.currentNotificationAccessPermission) + } + + if (action.ignoreUsageStatsAccessManipulation) { + deviceEntry = deviceEntry.copy(highestUsageStatsPermission = deviceEntry.currentUsageStatsPermission) + } + + if (action.ignoreReboot) { + deviceEntry = deviceEntry.copy(manipulationDidReboot = false) + } + + if (action.ignoreHadManipulation) { + deviceEntry = deviceEntry.copy(hadManipulation = false) + } + + database.device().updateDeviceEntry(deviceEntry) + } + is SetKeepSignedInAction -> { + database.device().updateKeepSignedIn( + deviceId = action.deviceId, + keepSignedIn = action.keepSignedIn + ) + } + is SetCategoryForUnassignedApps -> { + DatabaseValidation.assertChildExists(database, action.childId) + + if (action.categoryId.isNotEmpty()) { + val category = database.category().getCategoryByIdSync(action.categoryId)!! + + if (category.childId != action.childId) { + throw IllegalArgumentException("category does not belong to child") + } + } + + database.user().updateCategoryForUnassignedApps( + categoryId = action.categoryId, + childId = action.childId + ) + } + is SetParentCategory -> { + val category = database.category().getCategoryByIdSync(action.categoryId)!! + + if (action.parentCategory.isNotEmpty()) { + val categories = database.category().getCategoriesByChildIdSync(category.childId) + + val parentCategoryItem = categories.find { it.id == action.parentCategory } + ?: throw IllegalArgumentException("selected parent category does not exist") + + if (parentCategoryItem.parentCategoryId.isNotEmpty()) { + throw IllegalArgumentException("can not set a category as parent which itself has got a parent") + } + + if (categories.find { it.parentCategoryId == action.categoryId } != null) { + throw IllegalArgumentException("can not make category a child category if it is already a parent category") + } + } + + database.category().updateParentCategory( + categoryId = action.categoryId, + parentCategoryId = action.parentCategory + ) + } + is SetSendDeviceConnected -> { + val deviceEntry = database.device().getDeviceByIdSync(action.deviceId) + ?: throw IllegalArgumentException("invalid device id for setting send device connected: ${action.deviceId}") + + val newDeviceEntry = deviceEntry.copy( + showDeviceConnected = action.enable + ) + + if (newDeviceEntry != deviceEntry) { + database.device().updateDeviceEntry(newDeviceEntry) + } + + null + } + is SetRelaxPrimaryDeviceAction -> { + val userEntry = database.user().getUserByIdSync(action.userId) + ?: throw IllegalArgumentException("invalid user id for setting relay primary device: ${action.userId}") + + val newUserEntry = userEntry.copy( + relaxPrimaryDevice = action.relax + ) + + if (newUserEntry != userEntry) { + database.user().updateUserSync(newUserEntry) + } + + null + } + is SetUserTimezoneAction -> { + DatabaseValidation.assertUserExists(database, action.userId) + + database.user().updateUserTimezone( + userId = action.userId, + timezone = action.timezone + ) + } + is SetDeviceDefaultUserAction -> { + if (action.defaultUserId.isNotEmpty()) { + DatabaseValidation.assertUserExists(database, action.defaultUserId) + } + + DatabaseValidation.assertDeviceExists(database, action.deviceId) + + database.device().updateDeviceDefaultUser( + deviceId = action.deviceId, + defaultUserId = action.defaultUserId + ) + } + is SetChildPasswordAction -> { + val userEntry = database.user().getUserByIdSync(action.childId) + + if (userEntry?.type != UserType.Child) { + throw IllegalArgumentException("can not set child password for a child which does not exist") + } + + database.user().updateUserSync( + userEntry.copy( + password = action.newPassword.parentPasswordHash, + secondPasswordSalt = action.newPassword.parentPasswordSecondSalt + ) + ) + } + is SetDeviceDefaultUserTimeoutAction -> { + val deviceEntry = database.device().getDeviceByIdSync(action.deviceId) + ?: throw IllegalArgumentException("device not found") + + database.device().updateDeviceEntry(deviceEntry.copy( + defaultUserTimeout = action.timeout + )) + } + is SetConsiderRebootManipulationAction -> { + val deviceEntry = database.device().getDeviceByIdSync(action.deviceId) + ?: throw IllegalArgumentException("device not found") + + database.device().updateDeviceEntry( + deviceEntry.copy( + considerRebootManipulation = action.considerRebootManipulation + ) + ) + } + is RenameChildAction -> { + val userEntry = database.user().getUserByIdSync(action.childId) + + if (userEntry?.type != UserType.Child) { + throw IllegalArgumentException("can not set child password for a child which does not exist") + } + + database.user().updateUserSync( + userEntry.copy( + name = action.newName + ) + ) + } + is UpdateParentNotificationFlagsAction -> { + val userEntry = database.user().getUserByIdSync(action.parentId) + + if (userEntry?.type != UserType.Parent) { + throw IllegalArgumentException("can not set mail notification flags for a parent which does not exist") + } + + database.user().updateUserSync( + userEntry.copy( + mailNotificationFlags = if (action.set) + userEntry.mailNotificationFlags or action.flags + else + userEntry.mailNotificationFlags and (action.flags.inv()) + ) + ) + } + }.let { } + + database.setTransactionSuccessful() + } finally { + database.endTransaction() + } + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/network/ActionUpload.kt b/app/src/main/java/io/timelimit/android/sync/network/ActionUpload.kt new file mode 100644 index 0000000..209445e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/ActionUpload.kt @@ -0,0 +1,82 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network + +import android.util.JsonReader +import android.util.JsonWriter +import io.timelimit.android.data.model.PendingSyncActionType +import io.timelimit.android.data.model.PendingSyncActionTypeConverter + +data class ActionUploadRequest( + val deviceAuthToken: String, + val actions: List +) { + fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name("deviceAuthToken").value(deviceAuthToken) + + writer.name("actions") + writer.beginArray() + actions.forEach { it.serialize(writer) } + writer.endArray() + + writer.endObject() + } +} + +data class ActionUploadItem( + val encodedAction: String, + val sequenceNumber: Long, + val integrity: String, + val type: PendingSyncActionType, + val userId: String +) { + fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name("encodedAction").value(encodedAction) + writer.name("sequenceNumber").value(sequenceNumber) + writer.name("integrity").value(integrity) + writer.name("type").value(PendingSyncActionTypeConverter.serialize(type)) + writer.name("userId").value(userId) + + writer.endObject() + } +} + +data class ActionUploadResponse( + val shouldDoFullSync: Boolean +) { + companion object { + fun parse(reader: JsonReader): ActionUploadResponse { + var shouldDoFullSync: Boolean? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + "shouldDoFullSync" -> shouldDoFullSync = reader.nextBoolean() + else -> reader.skipValue() + } + } + reader.endObject() + + return ActionUploadResponse( + shouldDoFullSync = shouldDoFullSync!! + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/network/AddDeviceResponse.kt b/app/src/main/java/io/timelimit/android/sync/network/AddDeviceResponse.kt new file mode 100644 index 0000000..32b22ed --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/AddDeviceResponse.kt @@ -0,0 +1,48 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network + +import android.util.JsonReader + +data class AddDeviceResponse ( + val deviceAuthToken: String, + val ownDeviceId: String +) { + companion object { + private const val DEVICE_AUTH_TOKEN = "deviceAuthToken" + private const val OWN_DEVICE_ID = "ownDeviceId" + + fun parse(reader: JsonReader): AddDeviceResponse { + var deviceAuthToken: String? = null + var ownDeviceId: String? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + DEVICE_AUTH_TOKEN -> deviceAuthToken = reader.nextString() + OWN_DEVICE_ID -> ownDeviceId = reader.nextString() + else -> reader.skipValue() + } + } + reader.endObject() + + return AddDeviceResponse( + deviceAuthToken = deviceAuthToken!!, + ownDeviceId = ownDeviceId!! + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/network/CanDoPurchaseStatus.kt b/app/src/main/java/io/timelimit/android/sync/network/CanDoPurchaseStatus.kt new file mode 100644 index 0000000..d3d1217 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/CanDoPurchaseStatus.kt @@ -0,0 +1,31 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network + +enum class CanDoPurchaseStatus { + Yes, NotDueToOldPurchase, NoForUnknownReason +} + +object CanDoPurchaseParser { + private const val YES = "yes" + private const val NO_DUE_TO_OLD_PURCHASE = "no due to old purchase" + + fun parse(value: String) = when(value) { + YES -> CanDoPurchaseStatus.Yes + NO_DUE_TO_OLD_PURCHASE -> CanDoPurchaseStatus.NotDueToOldPurchase + else -> CanDoPurchaseStatus.NoForUnknownReason + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/network/ClientDataStatus.kt b/app/src/main/java/io/timelimit/android/sync/network/ClientDataStatus.kt new file mode 100644 index 0000000..d6df50a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/ClientDataStatus.kt @@ -0,0 +1,123 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network + +import android.util.JsonWriter +import io.timelimit.android.data.Database +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.waitForNonNullValue +import java.util.* +import kotlin.collections.HashMap + +data class ClientDataStatus( + val deviceListVersion: String, + val installedAppsVersionsByDeviceId: Map, + val categories: Map, + val userListVersion: String +) { + companion object { + private const val DEVICES = "devices" + private const val APPS = "apps" + private const val CATEGORIES = "categories" + private const val USERS = "users" + + val empty = ClientDataStatus( + deviceListVersion = "", + installedAppsVersionsByDeviceId = Collections.emptyMap(), + categories = Collections.emptyMap(), + userListVersion = "" + ) + + suspend fun getClientDataStatusAsync(database: Database): ClientDataStatus { + return ClientDataStatus( + deviceListVersion = database.config().getDeviceListVersion().waitForNonNullValue(), + installedAppsVersionsByDeviceId = database.device().getInstalledAppsVersions().map { + val devicesWithAppVersions = it + val result = HashMap() + + devicesWithAppVersions.forEach { result[it.deviceId] = it.installedAppsVersions } + + Collections.unmodifiableMap(result) + }.waitForNonNullValue(), + categories = database.category().getCategoriesWithVersionNumbers().map { + val categoriesWithVersions = it + val result = HashMap() + + categoriesWithVersions.forEach { + result[it.categoryId] = CategoryDataStatus( + baseVersion = it.baseVersion, + assignedAppsVersion = it.assignedAppsVersion, + timeLimitRulesVersion = it.timeLimitRulesVersion, + usedTimeItemsVersion = it.usedTimeItemsVersion + ) + } + + Collections.unmodifiableMap(result) + }.waitForNonNullValue(), + userListVersion = database.config().getUserListVersion().waitForNonNullValue() + ) + } + } + + fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(DEVICES).value(deviceListVersion) + writer.name(USERS).value(userListVersion) + + writer.name(APPS) + writer.beginObject() + installedAppsVersionsByDeviceId.entries.forEach { + writer.name(it.key).value(it.value) + } + writer.endObject() + + writer.name(CATEGORIES) + writer.beginObject() + categories.entries.forEach { + writer.name(it.key) + it.value.serialize(writer) + } + writer.endObject() + + writer.endObject() + } +} + +data class CategoryDataStatus( + val baseVersion: String, + val assignedAppsVersion: String, + val timeLimitRulesVersion: String, + val usedTimeItemsVersion: String +) { + companion object { + private const val BASE_VERSION = "base" + private const val ASSIGNED_APPS_VERSION = "apps" + private const val TIME_LIMIT_RULES_VERSION = "rules" + private const val USED_TIME_ITEMS_VERSION = "usedTime" + } + + fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(BASE_VERSION).value(baseVersion) + writer.name(ASSIGNED_APPS_VERSION).value(assignedAppsVersion) + writer.name(TIME_LIMIT_RULES_VERSION).value(timeLimitRulesVersion) + writer.name(USED_TIME_ITEMS_VERSION).value(usedTimeItemsVersion) + + writer.endObject() + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/network/CreateAddDeviceTokenResponse.kt b/app/src/main/java/io/timelimit/android/sync/network/CreateAddDeviceTokenResponse.kt new file mode 100644 index 0000000..4f19a24 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/CreateAddDeviceTokenResponse.kt @@ -0,0 +1,48 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network + +import android.util.JsonReader + +data class CreateAddDeviceTokenResponse ( + val token: String, + val deviceId: String +) { + companion object { + private const val TOKEN = "token" + private const val DEVICE_ID = "deviceId" + + fun parse(reader: JsonReader): CreateAddDeviceTokenResponse { + var token: String? = null + var deviceId: String? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + TOKEN -> token = reader.nextString() + DEVICE_ID -> deviceId = reader.nextString() + else -> reader.skipValue() + } + } + reader.endObject() + + return CreateAddDeviceTokenResponse( + token = token!!, + deviceId = deviceId!! + ) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/network/NewDeviceInfo.kt b/app/src/main/java/io/timelimit/android/sync/network/NewDeviceInfo.kt new file mode 100644 index 0000000..de1c6da --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/NewDeviceInfo.kt @@ -0,0 +1,30 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network + +import android.util.JsonWriter + +data class NewDeviceInfo ( + val model: String +) { + fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name("model").value(model) + + writer.endObject() + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/network/ParentPassword.kt b/app/src/main/java/io/timelimit/android/sync/network/ParentPassword.kt new file mode 100644 index 0000000..000ced5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/ParentPassword.kt @@ -0,0 +1,64 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network + +import android.util.JsonWriter +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.crypto.PasswordHashing +import org.json.JSONObject + +data class ParentPassword ( + val parentPasswordHash: String, + val parentPasswordSecondHash: String, + val parentPasswordSecondSalt: String +) { + companion object { + private const val HASH = "hash" + private const val SECOND_HASH = "secondHash" + private const val SECOND_SALT = "secondSalt" + + fun createSync(password: String): ParentPassword { + val secondSalt = PasswordHashing.generateSalt() + + return ParentPassword( + parentPasswordHash = PasswordHashing.hashSync(password), + parentPasswordSecondSalt = secondSalt, + parentPasswordSecondHash = PasswordHashing.hashSyncWithSalt(password, secondSalt) + ) + } + + suspend fun createCoroutine(password: String) = Threads.crypto.executeAndWait { + createSync(password) + } + + fun parse(obj: JSONObject) = ParentPassword( + parentPasswordHash = obj.getString(HASH), + parentPasswordSecondHash = obj.getString(SECOND_HASH), + parentPasswordSecondSalt = obj.getString(SECOND_SALT) + ) + } + + fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(HASH).value(parentPasswordHash) + writer.name(SECOND_HASH).value(parentPasswordSecondHash) + writer.name(SECOND_SALT).value(parentPasswordSecondSalt) + + writer.endObject() + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/network/ServerDataStatus.kt b/app/src/main/java/io/timelimit/android/sync/network/ServerDataStatus.kt new file mode 100644 index 0000000..68b5576 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/ServerDataStatus.kt @@ -0,0 +1,614 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network + +import android.util.JsonReader +import io.timelimit.android.data.customtypes.ImmutableBitmask +import io.timelimit.android.data.customtypes.ImmutableBitmaskJson +import io.timelimit.android.data.model.* +import io.timelimit.android.integration.platform.* +import io.timelimit.android.sync.actions.InstalledApp +import io.timelimit.android.util.parseJsonArray +import io.timelimit.android.util.parseJsonStringArray +import java.util.* +import kotlin.collections.ArrayList + +data class ServerDataStatus( + val newDeviceList: ServerDeviceList?, + val newInstalledApps: List, + val removedCategories: List, + val newCategoryBaseData: List, + val newCategoryAssignedApps: List, + val newCategoryUsedTimes: List, + val newCategoryTimeLimitRules: List, + val newUserList: ServerUserList?, + val fullVersionUntil: Long, + val message: String? +) { + companion object { + private const val NEW_DEVICE_LIST = "devices" + private const val NEW_INSTALLED_APPS = "apps" + private const val REMOVED_CATEGORIES = "rmCategories" + private const val NEW_CATEGORIES_BASE_DATA = "categoryBase" + private const val NEW_CATEGORY_ASSIGNED_APPS = "categoryApp" + private const val NEW_CATEGORY_USED_TIMES = "usedTimes" + private const val NEW_CATEGORY_TIME_LIMIT_RULES = "rules" + private const val NEW_USER_LIST = "users" + private const val FULL_VERSION_UNTIL = "fullVersion" + private const val MESSAGE = "message" + + fun parse(reader: JsonReader): ServerDataStatus { + var newDeviceList: ServerDeviceList? = null + var newInstalledApps: List = Collections.emptyList() + var removedCategories: List = Collections.emptyList() + var newCategoryBaseData: List = Collections.emptyList() + var newCategoryAssignedApps: List = Collections.emptyList() + var newCategoryUsedTimes: List = Collections.emptyList() + var newCategoryTimeLimitRules: List = Collections.emptyList() + var newUserList: ServerUserList? = null + var fullVersionUntil: Long? = null + var message: String? = null + + reader.beginObject() + while (reader.hasNext()) { + when(reader.nextName()) { + NEW_DEVICE_LIST -> newDeviceList = ServerDeviceList.parse(reader) + NEW_INSTALLED_APPS -> newInstalledApps = ServerInstalledAppsData.parseList(reader) + REMOVED_CATEGORIES -> removedCategories = parseJsonStringArray(reader) + NEW_CATEGORIES_BASE_DATA -> newCategoryBaseData = ServerUpdatedCategoryBaseData.parseList(reader) + NEW_CATEGORY_ASSIGNED_APPS -> newCategoryAssignedApps = ServerUpdatedCategoryAssignedApps.parseList(reader) + NEW_CATEGORY_USED_TIMES -> newCategoryUsedTimes = ServerUpdatedCategoryUsedTimes.parseList(reader) + NEW_CATEGORY_TIME_LIMIT_RULES -> newCategoryTimeLimitRules = ServerUpdatedTimeLimitRules.parseList(reader) + NEW_USER_LIST -> newUserList = ServerUserList.parse(reader) + FULL_VERSION_UNTIL -> fullVersionUntil = reader.nextLong() + MESSAGE -> message = reader.nextString() + else -> reader.skipValue() + } + } + reader.endObject() + + return ServerDataStatus( + newDeviceList = newDeviceList, + newInstalledApps = newInstalledApps, + removedCategories = removedCategories, + newCategoryBaseData = newCategoryBaseData, + newCategoryAssignedApps = newCategoryAssignedApps, + newCategoryUsedTimes = newCategoryUsedTimes, + newCategoryTimeLimitRules = newCategoryTimeLimitRules, + newUserList = newUserList, + fullVersionUntil = fullVersionUntil!!, + message = message + ) + } + } +} + +data class ServerDeviceList( + val version: String, + val data: List +) { + companion object { + private const val VERSION = "version" + private const val DATA = "data" + + fun parse(reader: JsonReader): ServerDeviceList { + var version: String? = null + var data: List? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + VERSION -> version = reader.nextString() + DATA -> data = ServerDeviceData.parseList(reader) + } + } + reader.endObject() + + return ServerDeviceList( + version = version!!, + data = data!! + ) + } + } +} + +data class ServerUserList( + val version: String, + val data: List +) { + companion object { + private const val VERSION = "version" + private const val DATA = "data" + + fun parse(reader: JsonReader): ServerUserList { + var version: String? = null + var data: List? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + VERSION -> version = reader.nextString() + DATA -> data = User.parseList(reader) + else -> reader.skipValue() + } + } + reader.endObject() + + return ServerUserList( + version = version!!, + data = data!! + ) + } + } +} + +data class ServerDeviceData( + val deviceId: String, + val name: String, + val model: String, + val addedAt: Long, + val currentUserId: String, + val networkTime: NetworkTime, + val currentProtectionLevel: ProtectionLevel, + val highestProtectionLevel: ProtectionLevel, + val currentUsageStatsPermission: RuntimePermissionStatus, + val highestUsageStatsPermission: RuntimePermissionStatus, + val currentNotificationAccessPermission: NewPermissionStatus, + val highestNotificationAccessPermission: NewPermissionStatus, + val currentAppVersion: Int, + val highestAppVersion: Int, + val triedDisablingAdmin: Boolean, + val didReboot: Boolean, + val hadManipulation: Boolean, + val didReportUninstall: Boolean, + val isUserKeptSignedIn: Boolean, + val showDeviceConnected: Boolean, + val defaultUser: String, + val defaultUserTimeout: Int, + val considerRebootManipulation: Boolean +) { + companion object { + private const val DEVICE_ID = "deviceId" + private const val NAME = "name" + private const val MODEL = "model" + private const val ADDED_AT = "addedAt" + private const val CURRENT_USER_ID = "currentUserId" + private const val NETWORK_TIME = "networkTime" + private const val CURRENT_PROTECTION_LEVEL = "cProtectionLevel" + private const val HIGHEST_PROTECTION_LEVEL = "hProtectionLevel" + private const val CURRENT_USAGE_STATS_PERMISSION = "cUsageStats" + private const val HIGHEST_USAGE_STATS_PERMISSION = "hUsageStats" + private const val CURRENT_NOTIFICATION_ACCESS = "cNotificationAccess" + private const val HIGHEST_NOTIFICATION_ACCESS = "hNotificationAccess" + private const val CURRENT_APP_VERSION = "cAppVersion" + private const val HIGHEST_APP_VERSION = "hAppVersion" + private const val TRIED_DISABLING_ADMIN = "tDisablingAdmin" + private const val DID_REBOOT = "reboot" + private const val HAD_MANIPULATION = "hadManipulation" + private const val DID_REPORT_UNINSTALL = "reportUninstall" + private const val IS_USER_KEPT_SIGNED_IN = "isUserKeptSignedIn" + private const val SHOW_DEVICE_CONNECTED = "showDeviceConnected" + private const val DEFAULT_USER = "defUser" + private const val DEFAULT_USER_TIMEOUT = "defUserTimeout" + private const val CONSIDER_REBOOT_MANIPULATION = "rebootIsManipulation" + + fun parse(reader: JsonReader): ServerDeviceData { + var deviceId: String? = null + var name: String? = null + var model: String? = null + var addedAt: Long? = null + var currentUserId: String? = null + var networkTime: NetworkTime? = null + var currentProtectionLevel: ProtectionLevel? = null + var highestProtectionLevel: ProtectionLevel? = null + var currentUsageStatsPermission: RuntimePermissionStatus? = null + var highestUsageStatsPermission: RuntimePermissionStatus? = null + var currentNotificationAccessPermission: NewPermissionStatus? = null + var highestNotificationAccessPermission: NewPermissionStatus? = null + var currentAppVersion: Int? = null + var highestAppVersion: Int? = null + var triedDisablingAdmin: Boolean? = null + var didReboot: Boolean? = null + var hadManipulation: Boolean? = null + var didReportUninstall: Boolean? = null + var isUserKeptSignedIn: Boolean? = null + var showDeviceConnected: Boolean? = null + var defaultUser: String? = null + var defaultUserTimeout: Int? = null + var considerRebootManipulation: Boolean? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + DEVICE_ID -> deviceId = reader.nextString() + NAME -> name = reader.nextString() + MODEL -> model = reader.nextString() + ADDED_AT -> addedAt = reader.nextLong() + CURRENT_USER_ID -> currentUserId = reader.nextString() + NETWORK_TIME -> networkTime = NetworkTimeJson.parse(reader.nextString()) + CURRENT_PROTECTION_LEVEL -> currentProtectionLevel = ProtectionLevelUtil.parse(reader.nextString()) + HIGHEST_PROTECTION_LEVEL -> highestProtectionLevel = ProtectionLevelUtil.parse(reader.nextString()) + CURRENT_USAGE_STATS_PERMISSION -> currentUsageStatsPermission = RuntimePermissionStatusUtil.parse(reader.nextString()) + HIGHEST_USAGE_STATS_PERMISSION -> highestUsageStatsPermission = RuntimePermissionStatusUtil.parse(reader.nextString()) + CURRENT_NOTIFICATION_ACCESS -> currentNotificationAccessPermission = NewPermissionStatusUtil.parse(reader.nextString()) + HIGHEST_NOTIFICATION_ACCESS -> highestNotificationAccessPermission = NewPermissionStatusUtil.parse(reader.nextString()) + CURRENT_APP_VERSION -> currentAppVersion = reader.nextInt() + HIGHEST_APP_VERSION -> highestAppVersion = reader.nextInt() + TRIED_DISABLING_ADMIN -> triedDisablingAdmin = reader.nextBoolean() + DID_REBOOT -> didReboot = reader.nextBoolean() + HAD_MANIPULATION -> hadManipulation = reader.nextBoolean() + DID_REPORT_UNINSTALL -> didReportUninstall = reader.nextBoolean() + IS_USER_KEPT_SIGNED_IN -> isUserKeptSignedIn = reader.nextBoolean() + SHOW_DEVICE_CONNECTED -> showDeviceConnected = reader.nextBoolean() + DEFAULT_USER -> defaultUser = reader.nextString() + DEFAULT_USER_TIMEOUT -> defaultUserTimeout = reader.nextInt() + CONSIDER_REBOOT_MANIPULATION -> considerRebootManipulation = reader.nextBoolean() + else -> reader.skipValue() + } + } + reader.endObject() + + return ServerDeviceData( + deviceId = deviceId!!, + name = name!!, + model = model!!, + addedAt = addedAt!!, + currentUserId = currentUserId!!, + networkTime = networkTime!!, + currentProtectionLevel = currentProtectionLevel!!, + highestProtectionLevel = highestProtectionLevel!!, + currentUsageStatsPermission = currentUsageStatsPermission!!, + highestUsageStatsPermission = highestUsageStatsPermission!!, + currentNotificationAccessPermission = currentNotificationAccessPermission!!, + highestNotificationAccessPermission = highestNotificationAccessPermission!!, + currentAppVersion = currentAppVersion!!, + highestAppVersion = highestAppVersion!!, + triedDisablingAdmin = triedDisablingAdmin!!, + didReboot = didReboot!!, + hadManipulation = hadManipulation!!, + didReportUninstall = didReportUninstall!!, + isUserKeptSignedIn = isUserKeptSignedIn!!, + showDeviceConnected = showDeviceConnected!!, + defaultUser = defaultUser!!, + defaultUserTimeout = defaultUserTimeout!!, + considerRebootManipulation = considerRebootManipulation!! + ) + } + + fun parseList(reader: JsonReader) = parseJsonArray(reader) { parse(reader) } + } +} + +data class ServerUpdatedCategoryBaseData( + val categoryId: String, + val childId: String, + val title: String, + val blockedMinutesInWeek: ImmutableBitmask, + val extraTimeInMillis: Long, + val temporarilyBlocked: Boolean, + val baseDataVersion: String, + val parentCategoryId: String +) { + companion object { + private const val CATEGORY_ID = "categoryId" + private const val CHILD_ID = "childId" + private const val TITLE = "title" + private const val BLOCKED_MINUTES_IN_WEEK = "blockedTimes" + private const val EXTRA_TIME_IN_MILLIS = "extraTime" + private const val TEMPORARILY_BLOCKED = "tempBlocked" + private const val BASE_DATA_VERSION = "version" + private const val PARENT_CATEGORY_ID = "parentCategoryId" + + fun parse(reader: JsonReader): ServerUpdatedCategoryBaseData { + var categoryId: String? = null + var childId: String? = null + var title: String? = null + var blockedMinutesInWeek: ImmutableBitmask? = null + var extraTimeInMillis: Long? = null + var temporarilyBlocked: Boolean? = null + var baseDataVersion: String? = null + var parentCategoryId: String? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + CATEGORY_ID -> categoryId = reader.nextString() + CHILD_ID -> childId = reader.nextString() + TITLE -> title = reader.nextString() + BLOCKED_MINUTES_IN_WEEK -> blockedMinutesInWeek = ImmutableBitmaskJson.parse(reader.nextString(), Category.BLOCKED_MINUTES_IN_WEEK_LENGTH) + EXTRA_TIME_IN_MILLIS -> extraTimeInMillis = reader.nextLong() + TEMPORARILY_BLOCKED -> temporarilyBlocked = reader.nextBoolean() + BASE_DATA_VERSION -> baseDataVersion = reader.nextString() + PARENT_CATEGORY_ID -> parentCategoryId = reader.nextString() + else -> reader.skipValue() + } + } + reader.endObject() + + return ServerUpdatedCategoryBaseData( + categoryId = categoryId!!, + childId = childId!!, + title = title!!, + blockedMinutesInWeek = blockedMinutesInWeek!!, + extraTimeInMillis = extraTimeInMillis!!, + temporarilyBlocked = temporarilyBlocked!!, + baseDataVersion = baseDataVersion!!, + parentCategoryId = parentCategoryId!! + ) + } + + fun parseList(reader: JsonReader) = parseJsonArray(reader) { parse(reader) } + } +} + +data class ServerUpdatedCategoryAssignedApps( + val categoryId: String, + val assignedApps: List, + val version: String +) { + companion object { + private const val CATEGORY_ID = "categoryId" + private const val ASSIGNED_APPS = "apps" + private const val VERSION = "version" + + fun parse(reader: JsonReader): ServerUpdatedCategoryAssignedApps { + var categoryId: String? = null + var assignedApps: List? = null + var version: String? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + CATEGORY_ID -> categoryId = reader.nextString() + ASSIGNED_APPS -> { + reader.beginArray() + assignedApps = ArrayList() + + while (reader.hasNext()) { + assignedApps.add(reader.nextString()) + } + + assignedApps = Collections.unmodifiableList(assignedApps) + reader.endArray() + } + VERSION -> version = reader.nextString() + else -> reader.skipValue() + } + } + reader.endObject() + + return ServerUpdatedCategoryAssignedApps( + categoryId = categoryId!!, + assignedApps = assignedApps!!, + version = version!! + ) + } + + fun parseList(reader: JsonReader) = parseJsonArray(reader) { parse(reader) } } +} + +data class ServerUpdatedCategoryUsedTimes( + val categoryId: String, + val usedTimeItems: List, + val version: String +) { + companion object { + private const val CATEGORY_ID = "categoryId" + private const val USED_TIMES_ITEMS = "times" + private const val VERSION = "version" + + fun parse(reader: JsonReader): ServerUpdatedCategoryUsedTimes { + var categoryId: String? = null + var usedTimeItems: List? = null + var version: String? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + CATEGORY_ID -> categoryId = reader.nextString() + USED_TIMES_ITEMS -> usedTimeItems = ServerUsedTimeItem.parseList(reader) + VERSION -> version = reader.nextString() + else -> reader.skipValue() + } + } + reader.endObject() + + return ServerUpdatedCategoryUsedTimes( + categoryId = categoryId!!, + usedTimeItems = usedTimeItems!!, + version = version!! + ) + } + + fun parseList(reader: JsonReader) = parseJsonArray(reader) { parse(reader) } + } +} + +data class ServerUsedTimeItem( + val dayOfEpoch: Int, + val usedMillis: Long +) { + companion object { + private const val DAY_OF_EPOCH = "day" + private const val USED_MILLIS = "time" + + fun parse(reader: JsonReader): ServerUsedTimeItem { + var dayOfEpoch: Int? = null + var usedMillis: Long? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + DAY_OF_EPOCH -> dayOfEpoch = reader.nextInt() + USED_MILLIS -> usedMillis = reader.nextLong() + else -> reader.skipValue() + } + } + reader.endObject() + + return ServerUsedTimeItem( + dayOfEpoch = dayOfEpoch!!, + usedMillis = usedMillis!! + ) + } + + fun parseList(reader: JsonReader): List { + val result = ArrayList() + + reader.beginArray() + while (reader.hasNext()) { + result.add(parse(reader)) + } + reader.endArray() + + return Collections.unmodifiableList(result) + } + } +} + +data class ServerUpdatedTimeLimitRules( + val categoryId: String, + val version: String, + val rules: List +) { + companion object { + private const val CATEGORY_ID = "categoryId" + private const val VERSION = "version" + private const val RULES = "rules" + + fun parse(reader: JsonReader): ServerUpdatedTimeLimitRules { + var categoryId: String? = null + var version: String? = null + var rules: List? = null + + reader.beginObject() + while (reader.hasNext()) { + when(reader.nextName()) { + CATEGORY_ID -> categoryId = reader.nextString() + VERSION -> version = reader.nextString() + RULES -> rules = ServerTimeLimitRule.parseArray(reader) + else -> reader.skipValue() + } + } + reader.endObject() + + return ServerUpdatedTimeLimitRules( + categoryId = categoryId!!, + version = version!!, + rules = rules!! + ) + } + + fun parseList(reader: JsonReader) = parseJsonArray(reader) { parse(reader) } + } +} + +data class ServerTimeLimitRule( + val id: String, + val applyToExtraTimeUsage: Boolean, + val dayMask: Byte, + val maximumTimeInMillis: Int +) { + companion object { + private const val ID = "id" + private const val APPLY_TO_EXTRA_TIME_USAGE = "extraTime" + private const val DAY_MASK = "dayMask" + private const val MAXIMUM_TIME_IN_MILLIS = "maxTime" + + fun parse(reader: JsonReader): ServerTimeLimitRule { + var id: String? = null + var applyToExtraTimeUsage: Boolean? = null + var dayMask: Byte? = null + var maximumTimeInMillis: Int? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + ID -> id = reader.nextString() + APPLY_TO_EXTRA_TIME_USAGE -> applyToExtraTimeUsage = reader.nextBoolean() + DAY_MASK -> dayMask = reader.nextInt().toByte() + MAXIMUM_TIME_IN_MILLIS -> maximumTimeInMillis = reader.nextInt() + else -> reader.skipValue() + } + } + reader.endObject() + + return ServerTimeLimitRule( + id = id!!, + applyToExtraTimeUsage = applyToExtraTimeUsage!!, + dayMask = dayMask!!, + maximumTimeInMillis = maximumTimeInMillis!! + ) + } + + fun parseArray(reader: JsonReader): List { + val result = ArrayList() + + reader.beginArray() + while (reader.hasNext()) { + result.add(parse(reader)) + } + reader.endArray() + + return Collections.unmodifiableList(result) + } + } + + fun toRealRule(categoryId: String) = TimeLimitRule( + id = id, + applyToExtraTimeUsage = applyToExtraTimeUsage, + dayMask = dayMask, + maximumTimeInMillis = maximumTimeInMillis, + categoryId = categoryId + ) +} + +data class ServerInstalledAppsData( + val deviceId: String, + val version: String, + val apps: List +) { + companion object { + private const val DEVICE_ID = "deviceId" + private const val VERSION = "version" + private const val APPS = "apps" + + fun parse(reader: JsonReader): ServerInstalledAppsData { + var deviceId: String? = null + var version: String? = null + var apps: List? = null + + reader.beginObject() + while (reader.hasNext()) { + when(reader.nextName()) { + DEVICE_ID -> deviceId = reader.nextString() + VERSION -> version = reader.nextString() + APPS -> apps = InstalledApp.parseList(reader) + else -> reader.skipValue() + } + } + reader.endObject() + + return ServerInstalledAppsData( + deviceId = deviceId!!, + version = version!!, + apps = apps!! + ) + } + + fun parseList(reader: JsonReader) = parseJsonArray(reader) { parse(reader) } + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/network/StatusOfMailAddress.kt b/app/src/main/java/io/timelimit/android/sync/network/StatusOfMailAddress.kt new file mode 100644 index 0000000..674ca0e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/StatusOfMailAddress.kt @@ -0,0 +1,54 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network + +import android.util.JsonReader + +data class StatusOfMailAddressResponse( + val mail: String, + val status: StatusOfMailAddress +) { + companion object { + fun parse(reader: JsonReader): StatusOfMailAddressResponse { + var mail: String? = null + var status: StatusOfMailAddress? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + "status" -> status = when(reader.nextString()) { + "with family" -> StatusOfMailAddress.MailAddressWithFamily + "without family" -> StatusOfMailAddress.MailAddressWithoutFamily + else -> throw IllegalArgumentException() + } + "mail" -> mail = reader.nextString() + else -> reader.skipValue() + } + } + reader.endObject() + + return StatusOfMailAddressResponse( + mail = mail!!, + status = status!! + ) + } + } +} + +enum class StatusOfMailAddress { + MailAddressWithoutFamily, + MailAddressWithFamily +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/sync/network/UpdatePrimaryDevice.kt b/app/src/main/java/io/timelimit/android/sync/network/UpdatePrimaryDevice.kt new file mode 100644 index 0000000..b030691 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/UpdatePrimaryDevice.kt @@ -0,0 +1,92 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network + +import android.util.JsonReader +import android.util.JsonWriter + +data class UpdatePrimaryDeviceRequest( + val action: UpdatePrimaryDeviceRequestType, + val currentUserId: String, + val deviceAuthToken: String +) { + companion object { + private const val ACTION = "action" + private const val CURRENT_USER = "currentUserId" + private const val AUTH_TOKEN = "authToken" + } + + fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(ACTION).value(when(action) { + UpdatePrimaryDeviceRequestType.SetThisDevice -> "set this device" + UpdatePrimaryDeviceRequestType.UnsetThisDevice -> "unset this device" + }) + writer.name(CURRENT_USER).value(currentUserId) + writer.name(AUTH_TOKEN).value(deviceAuthToken) + + writer.endObject() + } +} + +enum class UpdatePrimaryDeviceRequestType { + SetThisDevice, + UnsetThisDevice +} + +data class UpdatePrimaryDeviceResponse( + val status: UpdatePrimaryDeviceResponseType +) { + companion object { + private const val STATUS = "status" + + fun parse(reader: JsonReader): UpdatePrimaryDeviceResponse { + var status: UpdatePrimaryDeviceResponseType? = null + + reader.beginObject() + + while (reader.hasNext()) { + when (reader.nextName()) { + STATUS -> status = UpdatePrimaryDeviceResponseTypeParser.parse(reader.nextString()) + else -> reader.skipValue() + } + } + + reader.endObject() + + return UpdatePrimaryDeviceResponse( + status = status!! + ) + } + } +} + +enum class UpdatePrimaryDeviceResponseType { + Success, + AssignedToOtherDevice, + RequiresFullVersion, + UnknownError +} + +object UpdatePrimaryDeviceResponseTypeParser { + fun parse(value: String) = when (value) { + "success" -> UpdatePrimaryDeviceResponseType.Success + "assigned to other device" -> UpdatePrimaryDeviceResponseType.AssignedToOtherDevice + "requires full version" -> UpdatePrimaryDeviceResponseType.RequiresFullVersion + else -> UpdatePrimaryDeviceResponseType.UnknownError + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/network/api/Api.kt b/app/src/main/java/io/timelimit/android/sync/network/api/Api.kt new file mode 100644 index 0000000..709140e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/api/Api.kt @@ -0,0 +1,64 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network.api + +import io.timelimit.android.sync.network.* + +interface ServerApi { + suspend fun getTimeInMillis(): Long + // returns null if the server does not accept the token + suspend fun getMailAuthTokenByGoogleAccountToken(googleToken: String): String + suspend fun sendMailLoginCode(mail: String, locale: String): String + suspend fun signInByMailCode(mailLoginToken: String, code: String): String + suspend fun getStatusByMailToken(mailAuthToken: String): StatusOfMailAddressResponse + suspend fun createFamilyByMailToken( + mailToken: String, + parentPassword: ParentPassword, + parentDevice: NewDeviceInfo, + timeZone: String, + parentName: String, + deviceName: String + ): AddDeviceResponse + suspend fun signInToFamilyByMailToken( + mailToken: String, + parentDevice: NewDeviceInfo, + deviceName: String + ): AddDeviceResponse + suspend fun recoverPasswordByMailToken( + mailToken: String, + parentPassword: ParentPassword + ) + suspend fun canRecoverPassword( + mailToken: String, + parentUserId: String + ): Boolean + suspend fun registerChildDevice( + registerToken: String, + childDeviceInfo: NewDeviceInfo, + deviceName: String + ): AddDeviceResponse + suspend fun pushChanges(request: ActionUploadRequest): ActionUploadResponse + suspend fun pullChanges(deviceAuthToken: String, status: ClientDataStatus): ServerDataStatus + suspend fun createAddDeviceToken(deviceAuthToken: String, parentUserId: String, parentPasswordSecondHash: String): CreateAddDeviceTokenResponse + suspend fun canDoPurchase(deviceAuthToken: String): CanDoPurchaseStatus + suspend fun finishPurchaseByGooglePlay(receipt: String, signature: String, deviceAuthToken: String) + suspend fun linkParentMailAddress(mailAuthToken: String, deviceAuthToken: String, parentUserId: String, secondPasswordHash: String) + suspend fun updatePrimaryDevice(request: UpdatePrimaryDeviceRequest): UpdatePrimaryDeviceResponse + suspend fun requestSignOutAtPrimaryDevice(deviceAuthToken: String) + suspend fun reportDeviceRemoved(deviceAuthToken: String) + suspend fun removeDevice(deviceAuthToken: String, parentUserId: String, parentPasswordSecondHash: String, deviceId: String) + suspend fun isDeviceRemoved(deviceAuthToken: String): Boolean +} diff --git a/app/src/main/java/io/timelimit/android/sync/network/api/DummyServerApi.kt b/app/src/main/java/io/timelimit/android/sync/network/api/DummyServerApi.kt new file mode 100644 index 0000000..b3ed370 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/api/DummyServerApi.kt @@ -0,0 +1,109 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network.api + +import io.timelimit.android.sync.network.* +import java.io.IOException + +class DummyServerApi: ServerApi { + var currentTime = 0L + + override suspend fun getTimeInMillis(): Long { + if (currentTime == 0L) { + throw IOException() + } else { + return currentTime + } + } + + override suspend fun getMailAuthTokenByGoogleAccountToken(googleToken: String): String { + throw IOException() + } + + override suspend fun sendMailLoginCode(mail: String, locale: String): String { + throw IOException() + } + + override suspend fun signInByMailCode(mailLoginToken: String, code: String): String { + throw IOException() + } + + override suspend fun getStatusByMailToken(mailAuthToken: String): StatusOfMailAddressResponse { + throw IOException() + } + + override suspend fun createFamilyByMailToken(mailToken: String, parentPassword: ParentPassword, parentDevice: NewDeviceInfo, timeZone: String, parentName: String, deviceName: String): AddDeviceResponse { + throw IOException() + } + + override suspend fun signInToFamilyByMailToken(mailToken: String, parentDevice: NewDeviceInfo, deviceName: String): AddDeviceResponse { + throw IOException() + } + + override suspend fun recoverPasswordByMailToken(mailToken: String, parentPassword: ParentPassword) { + throw IOException() + } + + override suspend fun canRecoverPassword(mailToken: String, parentUserId: String): Boolean { + throw IOException() + } + + override suspend fun registerChildDevice(registerToken: String, childDeviceInfo: NewDeviceInfo, deviceName: String): AddDeviceResponse { + throw IOException() + } + + override suspend fun pushChanges(request: ActionUploadRequest): ActionUploadResponse { + throw IOException() + } + + override suspend fun pullChanges(deviceAuthToken: String, status: ClientDataStatus): ServerDataStatus { + throw IOException() + } + + override suspend fun createAddDeviceToken(deviceAuthToken: String, parentUserId: String, parentPasswordSecondHash: String): CreateAddDeviceTokenResponse { + throw IOException() + } + + override suspend fun canDoPurchase(deviceAuthToken: String) = CanDoPurchaseStatus.NoForUnknownReason + + override suspend fun finishPurchaseByGooglePlay(receipt: String, signature: String, deviceAuthToken: String) { + throw IOException() + } + + override suspend fun linkParentMailAddress(mailAuthToken: String, deviceAuthToken: String, parentUserId: String, secondPasswordHash: String) { + throw IOException() + } + + override suspend fun updatePrimaryDevice(request: UpdatePrimaryDeviceRequest): UpdatePrimaryDeviceResponse { + throw IOException() + } + + override suspend fun requestSignOutAtPrimaryDevice(deviceAuthToken: String) { + throw IOException() + } + + override suspend fun reportDeviceRemoved(deviceAuthToken: String) { + throw IOException() + } + + override suspend fun removeDevice(deviceAuthToken: String, parentUserId: String, parentPasswordSecondHash: String, deviceId: String) { + throw IOException() + } + + override suspend fun isDeviceRemoved(deviceAuthToken: String): Boolean { + throw IOException() + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/network/api/HttpClient.kt b/app/src/main/java/io/timelimit/android/sync/network/api/HttpClient.kt new file mode 100644 index 0000000..ce13c01 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/api/HttpClient.kt @@ -0,0 +1,35 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network.api + +import android.util.Log +import io.timelimit.android.BuildConfig +import io.timelimit.pinning.CertificatePinning +import okhttp3.OkHttpClient +import okhttp3.logging.HttpLoggingInterceptor + +val httpClient: OkHttpClient by lazy { + val builder = OkHttpClient.Builder() + .certificatePinner(CertificatePinning.configuration) + + if (BuildConfig.DEBUG) { + builder.addInterceptor (HttpLoggingInterceptor { + Log.d("HttpClient", it) + }) + } + + builder.build() +} diff --git a/app/src/main/java/io/timelimit/android/sync/network/api/HttpErrors.kt b/app/src/main/java/io/timelimit/android/sync/network/api/HttpErrors.kt new file mode 100644 index 0000000..939350f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/api/HttpErrors.kt @@ -0,0 +1,43 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network.api + +import okhttp3.Response +import java.io.IOException + +sealed class HttpError: IOException() +class BadRequestHttpError: HttpError() +class UnauthorizedHttpError: HttpError() +class ConflictHttpError: HttpError() +class ForbiddenHttpError: HttpError() +class GoneHttpError: HttpError() +class NotFoundHttpError: HttpError() + +fun Response.assertSuccess() { + if (!this.isSuccessful) { + val code = this.code() + + when (code) { + 400 -> throw BadRequestHttpError() + 401 -> throw UnauthorizedHttpError() + 403 -> throw ForbiddenHttpError() + 404 -> throw NotFoundHttpError() + 409 -> throw ConflictHttpError() + 410 -> throw GoneHttpError() + else -> throw IOException("server returned $code") + } + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/network/api/HttpServerApi.kt b/app/src/main/java/io/timelimit/android/sync/network/api/HttpServerApi.kt new file mode 100644 index 0000000..17a11ea --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/network/api/HttpServerApi.kt @@ -0,0 +1,689 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.network.api + +import android.util.JsonReader +import android.util.JsonWriter +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.waitForResponse +import io.timelimit.android.sync.network.* +import okhttp3.MediaType +import okhttp3.Request +import okhttp3.RequestBody +import okio.BufferedSink +import okio.GzipSink +import okio.Okio +import java.io.OutputStreamWriter + +class HttpServerApi(private val endpointWithoutSlashAtEnd: String): ServerApi { + companion object { + fun createInstance(url: String) = HttpServerApi(url.removeSuffix("/")) + + private const val DEVICE_AUTH_TOKEN = "deviceAuthToken" + private const val GOOGLE_AUTH_TOKEN = "googleAuthToken" + private const val MAIL_AUTH_TOKEN = "mailAuthToken" + private const val REGISTER_TOKEN = "registerToken" + private const val MILLISECONDS = "ms" + private const val STATUS = "status" + private const val PASSWORD = "password" + private const val PARENT_PASSWORD = "parentPassword" + private const val PARENT_DEVICE = "parentDevice" + private const val CHILD_DEVICE = "childDevice" + private const val DEVICE_NAME = "deviceName" + private const val TIMEZONE = "timeZone" + private const val PARENT_NAME = "parentName" + private const val PARENT_ID = "parentId" + private const val PARENT_USER_ID = "parentUserId" + private const val PARENT_PASSWORD_SECOND_HASH = "parentPasswordSecondHash" + private const val DEVICE_ID = "deviceId" + private const val MAIL = "mail" + private const val LOCALE = "locale" + private const val MAIL_LOGIN_TOKEN = "mailLoginToken" + private const val RECEIVED_CODE = "receivedCode" + + private val JSON = MediaType.parse("application/json; charset=utf-8") + + private fun createJsonRequestBody(serialize: (writer: JsonWriter) -> Unit) = object: RequestBody() { + override fun contentType() = JSON + override fun writeTo(sink: BufferedSink) { + val writer = JsonWriter( + OutputStreamWriter( + Okio.buffer( + GzipSink(sink) + ).outputStream() + ) + ) + + serialize(writer) + + writer.flush() + writer.close() + } + } + } + + override suspend fun getTimeInMillis(): Long { + httpClient.newCall( + Request.Builder() + .get() + .url("$endpointWithoutSlashAtEnd/time") + .build() + ).waitForResponse().use { + it.assertSuccess() + + return Threads.network.executeAndWait { + val body = it.body()!! + val reader = JsonReader(body.charStream()) + var result: Long? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + MILLISECONDS -> result = reader.nextLong() + else -> reader.skipValue() + } + } + reader.endObject() + + result!! + } + } + } + + override suspend fun getMailAuthTokenByGoogleAccountToken(googleToken: String): String { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/auth/sign-in-with-google") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + writer.name(GOOGLE_AUTH_TOKEN).value(googleToken) + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + + val body = it.body()!! + + return Threads.network.executeAndWait { + val reader = JsonReader(body.charStream()) + + var token: String? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + MAIL_AUTH_TOKEN -> token = reader.nextString() + else -> reader.skipValue() + } + } + reader.endObject() + + token!! + } + } + } + + override suspend fun sendMailLoginCode(mail: String, locale: String): String { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/auth/send-mail-login-code") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + writer.name(MAIL).value(mail) + writer.name(LOCALE).value(locale) + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + + val body = it.body()!! + + return Threads.network.executeAndWait { + var response: String? = null + + JsonReader(body.charStream()).use { reader -> + reader.beginObject() + + while (reader.hasNext()) { + when (reader.nextName()) { + MAIL_LOGIN_TOKEN -> response = reader.nextString() + else -> reader.skipValue() + } + } + + reader.endObject() + } + + response!! + } + } + } + + override suspend fun signInByMailCode(mailLoginToken: String, code: String): String { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/auth/sign-in-by-mail-code") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + writer.name(MAIL_LOGIN_TOKEN).value(mailLoginToken) + writer.name(RECEIVED_CODE).value(code) + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + + val body = it.body()!! + + return Threads.network.executeAndWait { + var response: String? = null + + JsonReader(body.charStream()).use { reader -> + reader.beginObject() + + while (reader.hasNext()) { + when (reader.nextName()) { + MAIL_AUTH_TOKEN -> response = reader.nextString() + else -> reader.skipValue() + } + } + + reader.endObject() + } + + response!! + } + } + } + + override suspend fun getStatusByMailToken(mailAuthToken: String): StatusOfMailAddressResponse { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/parent/get-status-by-mail-address") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + writer.name(MAIL_AUTH_TOKEN).value(mailAuthToken) + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + + val body = it.body()!! + + return Threads.network.executeAndWait { + StatusOfMailAddressResponse.parse(JsonReader(body.charStream())) + } + } + } + + override suspend fun createFamilyByMailToken(mailToken: String, parentPassword: ParentPassword, parentDevice: NewDeviceInfo, timeZone: String, parentName: String, deviceName: String): AddDeviceResponse { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/parent/create-family") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + + writer.name(MAIL_AUTH_TOKEN).value(mailToken) + writer.name(TIMEZONE).value(timeZone) + writer.name(PARENT_NAME).value(parentName) + writer.name(DEVICE_NAME).value(deviceName) + + writer.name(PARENT_PASSWORD) + parentPassword.serialize(writer) + + writer.name(PARENT_DEVICE) + parentDevice.serialize(writer) + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + + val body = it.body()!! + + return Threads.network.executeAndWait { + AddDeviceResponse.parse(JsonReader(body.charStream())) + } + } + } + + override suspend fun signInToFamilyByMailToken(mailToken: String, parentDevice: NewDeviceInfo, deviceName: String): AddDeviceResponse { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/parent/sign-in-into-family") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + + writer.name(MAIL_AUTH_TOKEN).value(mailToken) + writer.name(DEVICE_NAME).value(deviceName) + + writer.name(PARENT_DEVICE) + parentDevice.serialize(writer) + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + + val body = it.body()!! + + return Threads.network.executeAndWait { + AddDeviceResponse.parse(JsonReader(body.charStream())) + } + } + } + + override suspend fun recoverPasswordByMailToken(mailToken: String, parentPassword: ParentPassword) { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/parent/recover-parent-password") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + + writer.name(MAIL_AUTH_TOKEN).value(mailToken) + + writer.name(PASSWORD) + parentPassword.serialize(writer) + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + } + } + + override suspend fun canRecoverPassword(mailToken: String, parentUserId: String): Boolean { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/parent/can-recover-password") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + + writer.name(MAIL_AUTH_TOKEN).value(mailToken) + writer.name(PARENT_USER_ID).value(parentUserId) + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + response -> + + response.assertSuccess() + + val body = response.body()!! + + return Threads.network.executeAndWait { + val reader = JsonReader(body.charStream()) + var result: Boolean? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + "canRecover" -> result = reader.nextBoolean() + else -> reader.skipValue() + } + } + reader.endObject() + + result!! + } + } + } + + override suspend fun registerChildDevice(registerToken: String, childDeviceInfo: NewDeviceInfo, deviceName: String): AddDeviceResponse { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/child/add-device") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + + writer.name(REGISTER_TOKEN).value(registerToken) + + writer.name(CHILD_DEVICE) + childDeviceInfo.serialize(writer) + + writer.name(DEVICE_NAME).value(deviceName) + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + + val body = it.body()!! + + return Threads.network.executeAndWait { + AddDeviceResponse.parse(JsonReader(body.charStream())) + } + } + } + + override suspend fun pushChanges(request: ActionUploadRequest): ActionUploadResponse { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/sync/push-actions") + .post(createJsonRequestBody{ request.serialize(it) }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + + val body = it.body()!! + + return Threads.network.executeAndWait { + ActionUploadResponse.parse(JsonReader(body.charStream())) + } + } + } + + override suspend fun pullChanges(deviceAuthToken: String, status: ClientDataStatus): ServerDataStatus { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/sync/pull-status") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + + writer.name(DEVICE_AUTH_TOKEN).value(deviceAuthToken) + + writer.name(STATUS) + status.serialize(writer) + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + + val body = it.body()!! + + return Threads.network.executeAndWait { + ServerDataStatus.parse(JsonReader(body.charStream())) + } + } + } + + override suspend fun createAddDeviceToken(deviceAuthToken: String, parentUserId: String, parentPasswordSecondHash: String): CreateAddDeviceTokenResponse { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/parent/create-add-device-token") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + + writer.name(DEVICE_AUTH_TOKEN).value(deviceAuthToken) + writer.name(PARENT_ID).value(parentUserId) + writer.name(PARENT_PASSWORD_SECOND_HASH).value(parentPasswordSecondHash) + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + it.assertSuccess() + + val body = it.body()!! + + return Threads.network.executeAndWait { + CreateAddDeviceTokenResponse.parse(JsonReader(body.charStream())) + } + } + } + + override suspend fun canDoPurchase(deviceAuthToken: String): CanDoPurchaseStatus { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/purchase/can-do-purchase") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + + writer.name(DEVICE_AUTH_TOKEN).value(deviceAuthToken) + writer.name("type").value("googleplay") + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + response -> + + response.assertSuccess() + + return Threads.network.executeAndWait { + val reader = JsonReader(response.body()!!.charStream()) + var status: CanDoPurchaseStatus? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + "canDoPurchase" -> status = CanDoPurchaseParser.parse(reader.nextString()) + else -> reader.skipValue() + } + } + reader.endObject() + + status!! + } + } + } + + override suspend fun finishPurchaseByGooglePlay(receipt: String, signature: String, deviceAuthToken: String) { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/purchase/finish-purchase-by-google-play") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + + writer.name("receipt").value(receipt) + writer.name("signature").value(signature) + writer.name(DEVICE_AUTH_TOKEN).value(deviceAuthToken) + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + response -> + + response.assertSuccess() + } + } + + override suspend fun linkParentMailAddress(mailAuthToken: String, deviceAuthToken: String, parentUserId: String, secondPasswordHash: String) { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/parent/link-mail-address") + .post(createJsonRequestBody { + writer -> + + writer.beginObject() + + writer.name(MAIL_AUTH_TOKEN).value(mailAuthToken) + writer.name(DEVICE_AUTH_TOKEN).value(deviceAuthToken) + writer.name(PARENT_USER_ID).value(parentUserId) + writer.name(PARENT_PASSWORD_SECOND_HASH).value(secondPasswordHash) + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + response -> + + response.assertSuccess() + } + } + + override suspend fun updatePrimaryDevice(request: UpdatePrimaryDeviceRequest): UpdatePrimaryDeviceResponse { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/child/update-primary-device") + .post(createJsonRequestBody { writer -> + request.serialize(writer) + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + response -> + + response.assertSuccess() + + return Threads.network.executeAndWait { + val reader = JsonReader(response.body()!!.charStream()) + + UpdatePrimaryDeviceResponse.parse(reader) + } + } + } + + override suspend fun requestSignOutAtPrimaryDevice(deviceAuthToken: String) { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/child/logout-at-primary-device") + .post(createJsonRequestBody { writer -> + writer.beginObject() + + writer.name(DEVICE_AUTH_TOKEN).value(deviceAuthToken) + + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { response -> + response.assertSuccess() + + return Threads.network.executeAndWait { + val reader = JsonReader(response.body()!!.charStream()) + + reader.skipValue() + } + } + } + + override suspend fun reportDeviceRemoved(deviceAuthToken: String) { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/sync/report-removed") + .post(createJsonRequestBody { writer -> + writer.beginObject() + writer.name(DEVICE_AUTH_TOKEN).value(deviceAuthToken) + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + response -> + + response.assertSuccess() + } + } + + override suspend fun removeDevice(deviceAuthToken: String, parentUserId: String, parentPasswordSecondHash: String, deviceId: String) { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/parent/remove-device") + .post(createJsonRequestBody { writer -> + writer.beginObject() + writer.name(DEVICE_AUTH_TOKEN).value(deviceAuthToken) + writer.name(PARENT_USER_ID).value(parentUserId) + writer.name(PARENT_PASSWORD_SECOND_HASH).value(parentPasswordSecondHash) + writer.name(DEVICE_ID).value(deviceId) + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + response -> + + response.assertSuccess() + } + } + + override suspend fun isDeviceRemoved(deviceAuthToken: String): Boolean { + httpClient.newCall( + Request.Builder() + .url("$endpointWithoutSlashAtEnd/sync/is-device-removed") + .post(createJsonRequestBody { writer -> + writer.beginObject() + writer.name(DEVICE_AUTH_TOKEN).value(deviceAuthToken) + writer.endObject() + }) + .header("Content-Encoding", "gzip") + .build() + ).waitForResponse().use { + response -> + + response.assertSuccess() + + return Threads.network.executeAndWait { + val reader = JsonReader(response.body()!!.charStream()) + var result: Boolean? = null + + reader.beginObject() + while (reader.hasNext()) { + when (reader.nextName()) { + "isDeviceRemoved" -> result = reader.nextBoolean() + else -> reader.skipValue() + } + } + reader.endObject() + + result!! + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/validation/ListValidation.kt b/app/src/main/java/io/timelimit/android/sync/validation/ListValidation.kt new file mode 100644 index 0000000..1dba2bb --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/validation/ListValidation.kt @@ -0,0 +1,28 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.validation + +object ListValidation { + fun assertNotEmptyListWithoutDuplicates(list: List) { + if (list.isEmpty()) { + throw IllegalArgumentException() + } + + if (list.distinct().size != list.size) { + throw IllegalArgumentException() + } + } +} diff --git a/app/src/main/java/io/timelimit/android/sync/websocket/NetworkStatus.kt b/app/src/main/java/io/timelimit/android/sync/websocket/NetworkStatus.kt new file mode 100644 index 0000000..ffe3531 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/websocket/NetworkStatus.kt @@ -0,0 +1,58 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.websocket + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.net.ConnectivityManager +import android.net.NetworkInfo +import androidx.core.net.ConnectivityManagerCompat +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig + +object NetworkStatusUtil { + fun getSystemNetworkStatusLive(context: Context): LiveData { + val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + val status = MutableLiveData() + + status.value = NetworkStatus.Offline + + if (BuildConfig.hasServer) { + context.applicationContext.registerReceiver(object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent) { + val networkInfo = ConnectivityManagerCompat.getNetworkInfoFromBroadcast(connectivityManager, intent) + + if (networkInfo == null) { + status.value = NetworkStatus.Offline + } else if (networkInfo.detailedState == NetworkInfo.DetailedState.CONNECTED) { + status.value = NetworkStatus.Online + } else { + status.value = NetworkStatus.Offline + } + } + }, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)) + } + + return status + } +} + +enum class NetworkStatus { + Offline, Online +} diff --git a/app/src/main/java/io/timelimit/android/sync/websocket/WebsocketClient.kt b/app/src/main/java/io/timelimit/android/sync/websocket/WebsocketClient.kt new file mode 100644 index 0000000..68ae767 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/websocket/WebsocketClient.kt @@ -0,0 +1,113 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.sync.websocket + +import io.socket.client.Ack +import io.socket.client.IO +import io.socket.client.Socket +import io.socket.engineio.client.transports.WebSocket +import io.timelimit.android.sync.network.api.httpClient +import org.json.JSONArray +import org.json.JSONObject + +interface WebsocketClientCreator { + fun createWebsocketClient(serverUrl: String, deviceAuthTokenToConnectFor: String, listener: WebsocketClientListener): WebsocketClient +} + +interface WebsocketClientListener { + fun onSyncRequestedByServer(important: Boolean) + fun onConnectionEstablished() + fun onConnectionLost() + fun onGotConnectedDeviceList(connectedDeviceIds: Set) + fun onGotSignOutRequest() +} + +abstract class WebsocketClient() { + abstract fun shutdown() +} + +class SocketIoWebsocketClient(serverUrl: String, private val deviceAuthTokenToConnectFor: String, private val listener: WebsocketClientListener): WebsocketClient() { + companion object { + val creator = object: WebsocketClientCreator { + override fun createWebsocketClient(serverUrl: String, deviceAuthTokenToConnectFor: String, listener: WebsocketClientListener): WebsocketClient { + return SocketIoWebsocketClient(serverUrl, deviceAuthTokenToConnectFor, listener) + } + } + } + + private val client = IO.socket( + serverUrl, + IO.Options().apply { + transports = arrayOf(WebSocket.NAME) + webSocketFactory = httpClient + } + ) + + init { + client.on(Socket.EVENT_CONNECT) { _ -> + client.emit("devicelogin", deviceAuthTokenToConnectFor, Ack { + listener.onConnectionEstablished() + }) + } + + client.on(Socket.EVENT_DISCONNECT) { + listener.onConnectionLost() + } + + client.on("should sync") { + val params = it[0] as JSONObject + + val isImportant = params.getBoolean("isImportant") + + listener.onSyncRequestedByServer( + important = isImportant + ) + } + + client.on("connected devices") { + val devices = it[0] as JSONArray + val result = mutableSetOf() + + for (i in 0..(devices.length() - 1)) { + result.add(devices[i] as String) + } + + listener.onGotConnectedDeviceList(result) + } + + client.on("sign out") { + listener.onGotSignOutRequest() + } + + client.connect() + } + + override fun shutdown() { + client.disconnect() + } +} + +object DummyWebsocketClient: WebsocketClient() { + val creator = object: WebsocketClientCreator { + override fun createWebsocketClient(serverUrl: String, deviceAuthTokenToConnectFor: String, listener: WebsocketClientListener): WebsocketClient { + return DummyWebsocketClient + } + } + + override fun shutdown() { + // nothing to do + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/IsAppInForeground.kt b/app/src/main/java/io/timelimit/android/ui/IsAppInForeground.kt new file mode 100644 index 0000000..a49cf1a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/IsAppInForeground.kt @@ -0,0 +1,72 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui + +import android.util.Log +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.async.Threads +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.map + +object IsAppInForeground { + private const val LOG_TAG = "IsAppInForeground" + private const val REPORT_INACTIVE_DELAY = 300L // 0.3 seconds + + private val activeInstancesInternal = MutableLiveData().apply { value = 0 } + private val isRunningInternal = activeInstancesInternal.map { it != 0 }.ignoreUnchanged() + private val isRunningWithDelayInternal = object: LiveData() { + private val reportNotRunning = Runnable { + value = false + } + + init { + isRunningInternal.observeForever { + if (it == true) { + Threads.mainThreadHandler.removeCallbacks(reportNotRunning) + value = true + } else if (it == false) { + Threads.mainThreadHandler.postDelayed(reportNotRunning, REPORT_INACTIVE_DELAY) + } + } + } + }.ignoreUnchanged() + val isRunning = isRunningWithDelayInternal.castDown() + + fun reportStart() { + activeInstancesInternal.value = activeInstancesInternal.value!! + 1 + } + + fun reportStop() { + activeInstancesInternal.value = activeInstancesInternal.value!! - 1 + + if (activeInstancesInternal.value!! < 0) { + throw IllegalStateException() + } + } + + fun isRunning() = activeInstancesInternal.value != 0 + + init { + if (BuildConfig.DEBUG) { + isRunning.observeForever { + Log.d(LOG_TAG, "isRunning = $it") + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/MainActivity.kt b/app/src/main/java/io/timelimit/android/ui/MainActivity.kt new file mode 100644 index 0000000..680fa13 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/MainActivity.kt @@ -0,0 +1,195 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui + +import android.content.Intent +import android.os.Bundle +import android.view.MenuItem +import androidx.appcompat.app.AppCompatActivity +import androidx.fragment.app.Fragment +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Observer +import androidx.lifecycle.Transformations +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.NavController +import androidx.navigation.fragment.NavHostFragment +import io.timelimit.android.Application +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.flavors.GoogleSignInUtil +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.login.NewLoginFragment +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.main.FragmentWithCustomTitle +import io.timelimit.android.ui.overview.main.MainFragment +import io.timelimit.android.ui.payment.ActivityPurchaseModel +import io.timelimit.android.ui.setup.SetupTermsFragment +import io.timelimit.android.ui.util.SyncStatusModel +import org.solovyev.android.checkout.ActivityCheckout +import org.solovyev.android.checkout.Checkout + +class MainActivity : AppCompatActivity(), ActivityViewModelHolder { + companion object { + private const val AUTH_DIALOG_TAG = "adt" + } + + private val currentNavigatorFragment = MutableLiveData() + private val application: Application by lazy { getApplication() as Application } + private val checkout: ActivityCheckout by lazy { Checkout.forActivity(this, application.billing) } + private val syncModel: SyncStatusModel by lazy { + ViewModelProviders.of(this).get(SyncStatusModel::class.java) + } + val purchaseModel: ActivityPurchaseModel by lazy { + ViewModelProviders.of(this).get(ActivityPurchaseModel::class.java).apply { + setActivityCheckout(checkout) + } + } + + val googleSignInUtil = GoogleSignInUtil(this) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + // init the purchaseModel + purchaseModel.getApplication() + + // prepare livedata + val customTitle = currentNavigatorFragment.switchMap { + if (it != null && it is FragmentWithCustomTitle) { + it.getCustomTitle() + } else { + liveDataFromValue(null as String?) + } + }.ignoreUnchanged() + + val title = Transformations.map(customTitle) { + if (it == null) { + getString(R.string.app_name) + } else { + it + } + } + + // up button + val shouldShowBackButtonForNavigatorFragment = currentNavigatorFragment.map { fragment -> + (!(fragment is MainFragment)) && (!(fragment is SetupTermsFragment)) + } + + val shouldShowUpButton = shouldShowBackButtonForNavigatorFragment + + shouldShowUpButton.observe(this, Observer { supportActionBar!!.setDisplayHomeAsUpEnabled(it) }) + + // init if not yet done + DefaultAppLogic.with(this) + + val fragmentContainer = supportFragmentManager.findFragmentById(R.id.nav_host)!! + val fragmentContainerManager = fragmentContainer.childFragmentManager + getNavController().addOnDestinationChangedListener { _, _, _ -> + Threads.mainThreadHandler.post { + currentNavigatorFragment.value = fragmentContainerManager.fragments.first() + } + } + + title.observe(this, Observer { setTitle(it) }) + syncModel.statusText.observe(this, Observer { supportActionBar!!.subtitle = it }) + } + + override fun onOptionsItemSelected(item: MenuItem) = when { + item.itemId == android.R.id.home -> { + onBackPressed() + + true + } + else -> super.onOptionsItemSelected(item) + } + + override fun onStart() { + super.onStart() + + purchaseModel.queryAndProcessPurchasesAsync() + + IsAppInForeground.reportStart() + } + + override fun onStop() { + super.onStop() + + if (!isChangingConfigurations) { + getActivityViewModel().logOut() + } + + IsAppInForeground.reportStop() + } + + override fun onDestroy() { + super.onDestroy() + + purchaseModel.forgetActivityCheckout() + } + + override fun onNewIntent(intent: Intent?) { + super.onNewIntent(intent) + + getNavController().popBackStack(R.id.overviewFragment, true) + getNavController().handleDeepLink( + getNavController().createDeepLink() + .setDestination(R.id.overviewFragment) + .createTaskStackBuilder() + .intents + .first() + ) + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + super.onActivityResult(requestCode, resultCode, data) + + checkout.onActivityResult(requestCode, resultCode, data) + } + + override fun getActivityViewModel(): ActivityViewModel { + return ViewModelProviders.of(this).get(ActivityViewModel::class.java) + } + + private fun getNavHostFragment(): NavHostFragment { + return supportFragmentManager.findFragmentById(R.id.nav_host) as NavHostFragment + } + + private fun getNavController(): NavController { + return getNavHostFragment().navController + } + + override fun onBackPressed() { + if (currentNavigatorFragment.value is SetupTermsFragment) { + // hack to prevent the user from going to the launch screen of the App if it is not set up + finish() + } else { + super.onBackPressed() + } + } + + override fun showAuthenticationScreen() { + if (supportFragmentManager.findFragmentByTag(AUTH_DIALOG_TAG) == null) { + NewLoginFragment().showSafe(supportFragmentManager, AUTH_DIALOG_TAG) + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/authentication/AuthenticateByMailFragment.kt b/app/src/main/java/io/timelimit/android/ui/authentication/AuthenticateByMailFragment.kt new file mode 100644 index 0000000..97b0d2f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/authentication/AuthenticateByMailFragment.kt @@ -0,0 +1,124 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.authentication + +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentAuthenticateByMailBinding +import io.timelimit.android.extensions.setOnEnterListenr +import io.timelimit.android.flavors.GoogleSignInUtil +import io.timelimit.android.livedata.map +import io.timelimit.android.ui.MainActivity + +class AuthenticateByMailFragment : Fragment() { + companion object { + private const val REQUEST_SIGN_IN_WITH_GOOGLE = 1 + } + + private val listener: AuthenticateByMailFragmentListener by lazy { parentFragment as AuthenticateByMailFragmentListener } + private val googleAuthUtil: GoogleSignInUtil by lazy { (activity as MainActivity).googleSignInUtil } + private val model: AuthenticateByMailModel by lazy { ViewModelProviders.of(this).get(AuthenticateByMailModel::class.java) } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentAuthenticateByMailBinding.inflate(layoutInflater, container, false) + + model.usingDefaultServer.observe(this, Observer { + binding.usingDefaultServer = it + }) + + binding.signInWithGoogleButton.setOnClickListener { + startActivityForResult(googleAuthUtil.getSignInIntent(), REQUEST_SIGN_IN_WITH_GOOGLE) + } + + binding.mailEdit.setOnEnterListenr { + val mail = binding.mailEdit.text.toString() + + if (mail.isNotBlank()) { + model.sendAuthMessage(mail) + } + } + + binding.codeEdit.setOnEnterListenr { + val code = binding.codeEdit.text.toString() + + if (code.isNotBlank()) { + model.confirmCode(code) + + binding.codeEdit.setText("") + } + } + + model.mailAddressToWhichCodeWasSent.observe(this, Observer { + binding.mailAddressToWhichCodeWasSent = it + }) + + model.isBusy.map { + if (it) { + 1 + } else { + 0 + } + }.observe(this, Observer { + binding.switcher.displayedChild = it!! + }) + + model.mailAuthToken.observe(this, Observer { + if (it != null) { + listener.onLoginSucceeded(it) + } + }) + + model.errorMessage.observe(this, Observer { + if (it != null) { + Snackbar.make( + binding.root, + when(it) { + ErrorMessage.NetworkProblem -> R.string.error_network + ErrorMessage.ServerRejection -> R.string.error_server_rejected + ErrorMessage.WrongCode -> R.string.authenticate_by_mail_snackbar_wrong_code + }, + Snackbar.LENGTH_SHORT + ).show() + + model.errorMessage.value = null + } + }) + + return binding.root + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { + if (requestCode == REQUEST_SIGN_IN_WITH_GOOGLE) { + val googleAuthToken = googleAuthUtil.processActivityResult(data) + + if (googleAuthToken != null) { + model.handleGoogleAuthToken(googleAuthToken) + } + } + } +} + +interface AuthenticateByMailFragmentListener { + fun onLoginSucceeded(mailAuthToken: String) +} diff --git a/app/src/main/java/io/timelimit/android/ui/authentication/AuthenticateByMailModel.kt b/app/src/main/java/io/timelimit/android/ui/authentication/AuthenticateByMailModel.kt new file mode 100644 index 0000000..12bc88e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/authentication/AuthenticateByMailModel.kt @@ -0,0 +1,137 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.authentication + +import android.app.Application +import android.util.Log +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.map +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.network.api.BadRequestHttpError +import io.timelimit.android.sync.network.api.ForbiddenHttpError +import io.timelimit.android.sync.network.api.GoneHttpError +import io.timelimit.android.sync.network.api.HttpError +import java.io.IOException + +class AuthenticateByMailModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "AuthenticateByMailModel" + } + + private val logic = DefaultAppLogic.with(application) + private val isBusyInternal = MutableLiveData().apply { value = false } + private val mailAuthTokenInternal = MutableLiveData().apply { value = null } + private val mailAddressToWhichCodeWasSentInternal = MutableLiveData().apply { value = null } + private var mailLoginToken: String? = null + + val usingDefaultServer = logic.database.config().getCustomServerUrlAsync().map { it.isEmpty() } + val isBusy = isBusyInternal.castDown() + val mailAuthToken = mailAuthTokenInternal.castDown() + val errorMessage = MutableLiveData().apply { value = null } + val mailAddressToWhichCodeWasSent = mailAddressToWhichCodeWasSentInternal.castDown() + + fun handleGoogleAuthToken(googleAuthToken: String) { + isBusyInternal.value = true + + runAsync { + try { + val api = logic.serverLogic.getServerConfigCoroutine().api + val mailAuthToken = api.getMailAuthTokenByGoogleAccountToken(googleAuthToken) + + mailAuthTokenInternal.value = mailAuthToken + } catch (ex: BadRequestHttpError) { + errorMessage.value = ErrorMessage.ServerRejection + } catch (ex: Exception) { + errorMessage.value = ErrorMessage.NetworkProblem + } finally { + isBusyInternal.value = false + } + } + } + + fun sendAuthMessage(receiver: String) { + isBusyInternal.value = true + + runAsync { + try { + val api = logic.serverLogic.getServerConfigCoroutine().api + + mailLoginToken = api.sendMailLoginCode( + mail = receiver, + locale = getApplication().resources.configuration.locale.language + ) + + mailAddressToWhichCodeWasSentInternal.value = receiver + } catch (ex: HttpError) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "sendAuthMessage()", ex) + } + + errorMessage.value = ErrorMessage.ServerRejection + } catch (ex: IOException) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "sendAuthMessage()", ex) + } + + errorMessage.value = ErrorMessage.NetworkProblem + } finally { + isBusyInternal.value = false + } + } + } + + fun confirmCode(code: String) { + isBusyInternal.value = true + + runAsync { + try { + val api = logic.serverLogic.getServerConfigCoroutine().api + val mailAuthToken = api.signInByMailCode(mailLoginToken!!, code) + + mailAuthTokenInternal.value = mailAuthToken + } catch (ex: ForbiddenHttpError) { + errorMessage.value = ErrorMessage.WrongCode + } catch (ex: GoneHttpError) { + errorMessage.value = ErrorMessage.WrongCode + + // go back to first step + mailAddressToWhichCodeWasSentInternal.value = null + } catch (ex: HttpError) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "sendAuthMessage()", ex) + } + + errorMessage.value = ErrorMessage.ServerRejection + } catch (ex: IOException) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "sendAuthMessage()", ex) + } + + errorMessage.value = ErrorMessage.NetworkProblem + } finally { + isBusyInternal.value = false + } + } + } +} + +enum class ErrorMessage { + NetworkProblem, ServerRejection, WrongCode +} diff --git a/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseClockFragment.kt b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseClockFragment.kt new file mode 100644 index 0000000..8d55a13 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseClockFragment.kt @@ -0,0 +1,103 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.diagnose + +import android.os.Bundle +import android.text.format.DateFormat +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import io.timelimit.android.R +import io.timelimit.android.databinding.DiagnoseClockFragmentBinding +import io.timelimit.android.date.CalendarCache +import io.timelimit.android.date.DateInTimezone +import io.timelimit.android.date.getMinuteOfWeek +import io.timelimit.android.livedata.liveDataFromFunction +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.util.TimeTextUtil +import java.util.* + +class DiagnoseClockFragment : Fragment() { + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = DiagnoseClockFragmentBinding.inflate(inflater, container, false) + val logic = DefaultAppLogic.with(context!!) + + val timeZone = logic.deviceUserEntry.map { TimeZone.getTimeZone(it?.timeZone) ?: logic.timeApi.getSystemTimeZone() } + val timestamp = liveDataFromFunction { logic.realTimeLogic.getCurrentTimeInMillis() } + val dateInTimezone = timeZone.switchMap { tz -> timestamp.map { ts -> DateInTimezone.newInstance(ts, tz) } } + val minuteOfWeek = timeZone.switchMap { tz -> timestamp.map { ts -> getMinuteOfWeek(ts, tz) } } + val timeOfDay = timeZone.switchMap { tz -> timestamp.map { ts -> + val calendar = CalendarCache.getCalendar() + + calendar.firstDayOfWeek = Calendar.MONDAY + + calendar.timeZone = tz + calendar.timeInMillis = ts + + String.format("%2d:%2d", calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE)) + }} + val dateString = timeZone.switchMap { tz -> timestamp.map { ts -> + DateFormat.getDateFormat(context).apply { + setTimeZone(tz) + }.format(Date(ts)) + }} + + timestamp.observe(this, androidx.lifecycle.Observer { binding.epochalSeconds = it / 1000 }) + timeZone.observe(this, androidx.lifecycle.Observer { binding.timeZone = it.displayName }) + timeOfDay.observe(this, androidx.lifecycle.Observer { binding.timeOfDay = it }) + dateString.observe(this, androidx.lifecycle.Observer { binding.dateString = it }) + dateInTimezone.observe(this, androidx.lifecycle.Observer { + binding.dayOfWeek = it.dayOfWeek + binding.dayOfEpoch = it.dayOfEpoch.toLong() + }) + minuteOfWeek.observe(this, androidx.lifecycle.Observer { + binding.minuteOfWeek = it + }) + + logic.realTimeLogic.shouldQueryTime.observe(this, androidx.lifecycle.Observer { + binding.syncTimeButton.isEnabled = it + }) + + logic.realTimeLogic.shouldQueryTime.switchMap { shouldQueryTime -> + if (shouldQueryTime) { + liveDataFromFunction { logic.realTimeLogic.durationSinceLastSuccessfullyTimeSync } + .map { durationSinceLastSync -> + if (durationSinceLastSync != null) + getString( + R.string.diagnose_clock_last_time_request_x_ago, + TimeTextUtil.minutes((durationSinceLastSync / (1000 * 60)).toInt(), context!!) + ) + else + getString(R.string.diagnose_clock_last_time_request_never) + } + } else { + liveDataFromValue(getString(R.string.diagnose_clock_last_time_request_disabled)) + } + }.observe(this, androidx.lifecycle.Observer { + binding.lastTimeRequest = it + }) + + binding.syncTimeButton.setOnClickListener { + logic.realTimeLogic.tryQueryTime() + } + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseConnectionFragment.kt b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseConnectionFragment.kt new file mode 100644 index 0000000..c2ca29f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseConnectionFragment.kt @@ -0,0 +1,52 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.diagnose + + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentDiagnoseConnectionBinding +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.websocket.NetworkStatus + +class DiagnoseConnectionFragment : Fragment() { + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentDiagnoseConnectionBinding.inflate(inflater, container, false) + val logic = DefaultAppLogic.with(context!!) + + logic.networkStatus.observe(this, Observer { + binding.generalStatus = getString(when (it!!) { + NetworkStatus.Online -> R.string.diagnose_connection_yes + NetworkStatus.Offline -> R.string.diagnose_connection_no + }) + }) + + logic.isConnected.observe(this, Observer { + binding.ownServerStatus = getString(if (it == true) + R.string.diagnose_connection_yes + else + R.string.diagnose_connection_no + ) + }) + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseMainFragment.kt b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseMainFragment.kt new file mode 100644 index 0000000..11fb0a8 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseMainFragment.kt @@ -0,0 +1,56 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.diagnose + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.navigation.Navigation +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentDiagnoseMainBinding +import io.timelimit.android.extensions.safeNavigate + +class DiagnoseMainFragment : Fragment() { + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentDiagnoseMainBinding.inflate(inflater, container, false) + val navigation = Navigation.findNavController(container!!) + + binding.diagnoseClockButton.setOnClickListener { + navigation.safeNavigate( + DiagnoseMainFragmentDirections.actionDiagnoseMainFragmentToDiagnoseClockFragment(), + R.id.diagnoseMainFragment + ) + } + + binding.diagnoseConnectionButton.setOnClickListener { + navigation.safeNavigate( + DiagnoseMainFragmentDirections.actionDiagnoseMainFragmentToDiagnoseConnectionFragment(), + R.id.diagnoseMainFragment + ) + } + + binding.diagnoseSyncButton.setOnClickListener { + navigation.safeNavigate( + DiagnoseMainFragmentDirections.actionDiagnoseMainFragmentToDiagnoseSyncFragment(), + R.id.diagnoseMainFragment + ) + } + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseSyncFragment.kt b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseSyncFragment.kt new file mode 100644 index 0000000..277ffbb --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseSyncFragment.kt @@ -0,0 +1,66 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.diagnose + + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.paging.LivePagedListBuilder +import androidx.recyclerview.widget.LinearLayoutManager +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.databinding.DiagnoseSyncFragmentBinding +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.apply.UploadActionsUtil + +class DiagnoseSyncFragment : Fragment() { + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = DiagnoseSyncFragmentBinding.inflate(inflater, container, false) + val logic = DefaultAppLogic.with(context!!) + val adapter = PendingSyncActionAdapter() + + binding.recycler.layoutManager = LinearLayoutManager(context!!) + binding.recycler.adapter = adapter + + LivePagedListBuilder(logic.database.pendingSyncAction().getAllPendingSyncActionsPaged(), 10) + .build() + .observe(this, Observer { + adapter.submitList(it) + binding.isListEmpty = it.isEmpty() + }) + + binding.clearCacheBtn.setOnClickListener { + Threads.database.execute { + UploadActionsUtil.deleteAllVersionNumbersSync(logic.database) + } + + Toast.makeText(context!!, R.string.diagnose_sync_btn_clear_cache_toast, Toast.LENGTH_SHORT).show() + } + + binding.requestSyncBtn.setOnClickListener { + logic.syncUtil.requestImportantSync(true) + + Toast.makeText(context!!, R.string.diagnose_sync_btn_request_sync_toast, Toast.LENGTH_SHORT).show() + } + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/diagnose/PendingSyncActionAdapter.kt b/app/src/main/java/io/timelimit/android/ui/diagnose/PendingSyncActionAdapter.kt new file mode 100644 index 0000000..e641bdb --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/diagnose/PendingSyncActionAdapter.kt @@ -0,0 +1,84 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.diagnose + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.view.LayoutInflater +import android.view.ViewGroup +import android.widget.Toast +import androidx.paging.PagedListAdapter +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.R +import io.timelimit.android.data.model.PendingSyncAction +import io.timelimit.android.databinding.DiagnoseSyncCardBinding +import org.json.JSONObject + +class PendingSyncActionAdapter: PagedListAdapter(diffCallback) { + companion object { + private val diffCallback = object: DiffUtil.ItemCallback() { + override fun areContentsTheSame(oldItem: PendingSyncAction, newItem: PendingSyncAction) = oldItem == newItem + override fun areItemsTheSame(oldItem: PendingSyncAction, newItem: PendingSyncAction) = oldItem.sequenceNumber == newItem.sequenceNumber + } + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = PendingSyncActionViewHolder( + DiagnoseSyncCardBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ).apply { + copyButton.setOnClickListener { + val clipboard = it.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager? + clipboard!!.primaryClip = ClipData.newPlainText("TimeLimit", text) + + Toast.makeText(it.context, R.string.diagnose_sync_copied_to_clipboard, Toast.LENGTH_SHORT).show() + } + } + ) + + override fun onBindViewHolder(holder: PendingSyncActionViewHolder, position: Int) { + val item = getItem(position) + + holder.binding.text = if (item == null) { + "null" + } else { + val builder = StringBuilder("sequence number: ${item.sequenceNumber}\n") + + if (item.userId.isNotEmpty()) { + builder.append("user: ${item.userId}\n") + } + + if (item.integrity.isNotEmpty()) { + builder.append("integrity: ${item.integrity}\n") + } + + builder.append("action: ").append( + try { + JSONObject(item.encodedAction).toString(2) + } catch (ex: Exception) { + "error" + } + ) + + builder.toString() + } + } +} + +class PendingSyncActionViewHolder(val binding: DiagnoseSyncCardBinding): RecyclerView.ViewHolder(binding.root) diff --git a/app/src/main/java/io/timelimit/android/ui/list/TextViewHolder.kt b/app/src/main/java/io/timelimit/android/ui/list/TextViewHolder.kt new file mode 100644 index 0000000..1421dbe --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/list/TextViewHolder.kt @@ -0,0 +1,28 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.list + +import android.view.LayoutInflater +import android.view.ViewGroup +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.R + +class TextViewHolder(parentView: ViewGroup): RecyclerView.ViewHolder( + LayoutInflater.from(parentView.context).inflate(R.layout.simple_list_item, parentView, false) +) { + val textView = itemView as TextView +} diff --git a/app/src/main/java/io/timelimit/android/ui/lock/LockActivity.kt b/app/src/main/java/io/timelimit/android/ui/lock/LockActivity.kt new file mode 100644 index 0000000..4a17647 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/lock/LockActivity.kt @@ -0,0 +1,129 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.lock + +import android.app.ActivityManager +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Bundle +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import io.timelimit.android.R +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.IsAppInForeground +import io.timelimit.android.ui.login.NewLoginFragment +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.util.SyncStatusModel + +class LockActivity : AppCompatActivity(), ActivityViewModelHolder { + companion object { + private const val EXTRA_PACKAGE_NAME = "pkg" + private const val LOGIN_DIALOG_TAG = "ldt" + + fun start(context: Context, packageName: String) { + context.startActivity( + Intent(context, LockActivity::class.java) + .putExtra(EXTRA_PACKAGE_NAME, packageName) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + .addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) + ) + } + } + + val blockedPackageName: String by lazy { + intent.getStringExtra(EXTRA_PACKAGE_NAME) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.lock_activity) + + if (savedInstanceState == null) { + supportFragmentManager.beginTransaction() + .replace(R.id.container, LockFragment.newInstance(blockedPackageName)) + .commitNow() + } + + val syncModel = ViewModelProviders.of(this).get(SyncStatusModel::class.java) + + syncModel.statusText.observe(this, Observer { + supportActionBar?.subtitle = it + }) + } + + override fun getActivityViewModel(): ActivityViewModel { + return ViewModelProviders.of(this).get(ActivityViewModel::class.java) + } + + override fun showAuthenticationScreen() { + NewLoginFragment().showSafe(supportFragmentManager, LOGIN_DIALOG_TAG) + } + + override fun onResume() { + super.onResume() + + lockTaskModeWorkaround() + } + + override fun onPause() { + super.onPause() + + lockTaskModeWorkaround() + } + + override fun onStart() { + super.onStart() + + IsAppInForeground.reportStart() + } + + override fun onStop() { + super.onStop() + + if (!isChangingConfigurations) { + getActivityViewModel().logOut() + } + + IsAppInForeground.reportStop() + } + + fun lockTaskModeWorkaround() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + val platformIntegration = DefaultAppLogic.with(this).platformIntegration + val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager + + val isLocked = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) + activityManager.lockTaskModeState == ActivityManager.LOCK_TASK_MODE_PINNED + else + activityManager.isInLockTaskMode + + if (isLocked) { + platformIntegration.setSuspendedApps(listOf(blockedPackageName), true) + platformIntegration.setSuspendedApps(listOf(blockedPackageName), false) + } + } + } + + override fun onBackPressed() { + // do nothing because going back would open the blocked app again + // super.onBackPressed() + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/lock/LockFragment.kt b/app/src/main/java/io/timelimit/android/ui/lock/LockFragment.kt new file mode 100644 index 0000000..f6c979d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/lock/LockFragment.kt @@ -0,0 +1,391 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.lock + +import android.content.Intent +import android.os.Bundle +import android.text.format.DateUtils +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import androidx.lifecycle.Transformations +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.* +import io.timelimit.android.databinding.LockFragmentBinding +import io.timelimit.android.livedata.* +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.BlockingReason +import io.timelimit.android.logic.BlockingReasonUtil +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.AddCategoryAppsAction +import io.timelimit.android.sync.actions.IncrementCategoryExtraTimeAction +import io.timelimit.android.sync.actions.UpdateCategoryTemporarilyBlockedAction +import io.timelimit.android.sync.actions.UpdateNetworkTimeVerificationAction +import io.timelimit.android.sync.network.UpdatePrimaryDeviceRequestType +import io.timelimit.android.ui.MainActivity +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.AuthenticationFab +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.child.ManageChildFragmentArgs +import io.timelimit.android.ui.manage.child.advanced.managedisabletimelimits.ManageDisableTimelimitsViewHelper +import io.timelimit.android.ui.manage.child.category.create.CreateCategoryDialogFragment +import io.timelimit.android.ui.manage.child.primarydevice.UpdatePrimaryDeviceDialogFragment +import io.timelimit.android.ui.payment.RequiresPurchaseDialogFragment + +class LockFragment : Fragment() { + companion object { + private const val EXTRA_PACKAGE_NAME = "pkg" + + fun newInstance(packageName: String): LockFragment { + val result = LockFragment() + val arguments = Bundle() + + arguments.putString(EXTRA_PACKAGE_NAME, packageName) + + result.arguments = arguments + return result + } + } + + private val packageName: String by lazy { arguments!!.getString(EXTRA_PACKAGE_NAME) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val title: String? by lazy { logic.platformIntegration.getLocalAppTitle(packageName) } + private val blockingReason: LiveData by lazy { BlockingReasonUtil(logic).getBlockingReason(packageName) } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + val binding = LockFragmentBinding.inflate(layoutInflater, container, false) + + AuthenticationFab.manageAuthenticationFab( + fab = binding.fab, + shouldHighlight = auth.shouldHighlightAuthenticationButton, + authenticatedUser = auth.authenticatedUser, + fragment = this, + doesSupportAuth = liveDataFromValue(true) + ) + + liveDataFromFunction { logic.timeApi.getCurrentTimeInMillis() }.observe(this, Observer { + systemTime -> + + binding.currentTime = DateUtils.formatDateTime( + context, + systemTime!!, + DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or + DateUtils.FORMAT_SHOW_YEAR or DateUtils.FORMAT_SHOW_WEEKDAY + ) + }) + + binding.packageName = packageName + + if (title != null) { + binding.appTitle = title + } else { + binding.appTitle = "???" + } + + binding.appIcon.setImageDrawable(logic.platformIntegration.getAppIcon(packageName)) + + blockingReason.observe(this, Observer { + if (it == BlockingReason.None) { + activity!!.finish() + } else { + binding.reason = it + } + }) + + val categories = logic.deviceUserEntry.switchMap { + user -> + + if (user != null && user.type == UserType.Child) { + Transformations.map(logic.database.category().getCategoriesByChildId(user.id)) { + categories -> + + user to categories + } + } else { + liveDataFromValue(null as Pair>?) + } + }.ignoreUnchanged() + + // bind category name of the app + val appCategory = categories.switchMap { + status -> + + if (status == null) { + liveDataFromValue(null as Category?) + } else { + val (_, categoryItems) = status + + Transformations.map(logic.database.categoryApp().getCategoryApp( + categoryItems.map { it.id }, + packageName + )) { + appEntry -> + + categoryItems.find { it.id == appEntry?.categoryId } + } + } + } + + appCategory.observe(this, Observer { + binding.appCategoryTitle = it?.title + }) + + // bind add to category list + categories.observe(this, Observer { + status -> + + binding.addToCategoryOptions.removeAllViews() + + if (status == null) { + // nothing to do + } else { + val (user, categoryEntries) = status + + categoryEntries.forEach { + category -> + + val button = Button(context) + + button.text = category.title + button.setOnClickListener { + _ -> + + auth.tryDispatchParentAction( + AddCategoryAppsAction( + categoryId = category.id, + packageNames = listOf(packageName) + ) + ) + } + + binding.addToCategoryOptions.addView(button) + } + + run { + val button = Button(context) + + button.text = getString(R.string.create_category_title) + button.setOnClickListener { + if (auth.requestAuthenticationOrReturnTrue()) { + CreateCategoryDialogFragment + .newInstance(ManageChildFragmentArgs(childId = user.id)) + .show(fragmentManager!!) + } + } + + binding.addToCategoryOptions.addView(button) + } + } + }) + + // bind adding extra time controls + logic.fullVersion.shouldProvideFullVersionFunctions.observe(this, Observer { hasFullVersion -> + binding.extraTimeBtnOk.setOnClickListener { + if (hasFullVersion) { + if (auth.isParentAuthenticated()) { + runAsync { + val extraTimeToAdd = binding.extraTimeSelection.timeInMillis + + if (extraTimeToAdd > 0) { + binding.extraTimeBtnOk.isEnabled = false + + val categoryId = appCategory.waitForNullableValue()?.id + + if (categoryId != null) { + auth.tryDispatchParentAction(IncrementCategoryExtraTimeAction( + categoryId = categoryId, + addedExtraTime = extraTimeToAdd + )) + } else { + Snackbar.make(binding.root, R.string.error_general, Snackbar.LENGTH_SHORT).show() + } + + binding.extraTimeBtnOk.isEnabled = true + } + } + } else { + auth.requestAuthentication() + } + } else { + RequiresPurchaseDialogFragment().show(fragmentManager!!) + } + } + }) + + // bind disable time limits + mergeLiveData(logic.deviceUserEntry, logic.fullVersion.shouldProvideFullVersionFunctions).observe(this, Observer { + (child, hasFullVersion) -> + + if (child != null) { + binding.manageDisableTimeLimits.handlers = ManageDisableTimelimitsViewHelper.createHandlers( + childId = child.id, + childTimezone = child.timeZone, + activity = activity!!, + hasFullVersion = hasFullVersion == true + ) + + binding.manageDisableTimeLimits.userName = child.name + } + }) + + mergeLiveData(logic.deviceUserEntry, liveDataFromFunction { logic.realTimeLogic.getCurrentTimeInMillis() }).map { + (child, time) -> + + if (time == null || child == null) { + null + } else { + ManageDisableTimelimitsViewHelper.getDisabledUntilString(child, time, context!!) + } + }.observe(this, Observer { + binding.manageDisableTimeLimits.disableTimeLimitsUntilString = it + }) + + // bind disable temporarily blocking + categories + .map { it != null && it.second.filter { category -> category.temporarilyBlocked }.size > 1 } + .observe(this, Observer { + binding.areMultipleCategoriesBlocked = it!! + }) + + binding.handlers = object: Handlers { + override fun openMainApp() { + startActivity(Intent(context, MainActivity::class.java)) + } + + override fun allowTemporarily() { + if (auth.requestAuthenticationOrReturnTrue()) { + val database = logic.database + val deviceIdLive = logic.deviceId + + // this accesses the database directly because it is not synced + runAsync { + val deviceId = deviceIdLive.waitForNullableValue() + + if (deviceId != null) { + logic.platformIntegration.setSuspendedApps(listOf(packageName), false) + + Threads.database.executeAndWait(Runnable { + database.temporarilyAllowedApp().addTemporarilyAllowedAppSync(TemporarilyAllowedApp( + deviceId = deviceId, + packageName = packageName + )) + }) + } + } + } + } + + override fun confirmLocalTime() { + if (auth.requestAuthenticationOrReturnTrue()) { + logic.realTimeLogic.confirmLocalTime() + } + } + + override fun disableTimeVerification() { + if (auth.requestAuthenticationOrReturnTrue()) { + runAsync { + val deviceId = logic.deviceId.waitForNullableValue() + + if (deviceId != null) { + auth.tryDispatchParentAction( + UpdateNetworkTimeVerificationAction( + deviceId = deviceId, + mode = NetworkTime.IfPossible + ) + ) + } + } + } + } + + override fun disableTemporarilyLockForAllCategories() { + if (auth.requestAuthenticationOrReturnTrue()) { + runAsync { + categories.waitForNullableValue()?.second?.filter { it.temporarilyBlocked }?.map { it.id }?.forEach { + categoryId -> + + auth.tryDispatchParentAction( + UpdateCategoryTemporarilyBlockedAction( + categoryId = categoryId, + blocked = false + ) + ) + } + } + } + } + + override fun disableTemporarilyLockForCurrentCategory() { + if (auth.requestAuthenticationOrReturnTrue()) { + runAsync { + val category = appCategory.waitForNullableValue() + + if (category != null) { + auth.tryDispatchParentAction( + UpdateCategoryTemporarilyBlockedAction( + categoryId = category.id, + blocked = false + ) + ) + } + } + } + } + + override fun showAuthenticationScreen() { + (activity as LockActivity).showAuthenticationScreen() + } + + override fun setThisDeviceAsCurrentDevice() { + UpdatePrimaryDeviceDialogFragment + .newInstance(UpdatePrimaryDeviceRequestType.SetThisDevice) + .show(fragmentManager!!) + } + } + + if (savedInstanceState == null) { + runAsync { + if (blockingReason.waitForNonNullValue() == BlockingReason.RequiresCurrentDevice) { + if (isResumed) { + binding.handlers!!.setThisDeviceAsCurrentDevice() + } + } + } + } + + return binding.root + } +} + +interface Handlers { + fun openMainApp() + fun allowTemporarily() + fun confirmLocalTime() + fun disableTimeVerification() + fun disableTemporarilyLockForCurrentCategory() + fun disableTemporarilyLockForAllCategories() + fun showAuthenticationScreen() + fun setThisDeviceAsCurrentDevice() +} diff --git a/app/src/main/java/io/timelimit/android/ui/login/LoginDialogFragmentModel.kt b/app/src/main/java/io/timelimit/android/ui/login/LoginDialogFragmentModel.kt new file mode 100644 index 0000000..6123eec --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/login/LoginDialogFragmentModel.kt @@ -0,0 +1,281 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.login + +import android.app.Application +import android.widget.Toast +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.crypto.PasswordHashing +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.* +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.ChildSignInAction +import io.timelimit.android.sync.actions.SetDeviceUserAction +import io.timelimit.android.sync.actions.SetKeepSignedInAction +import io.timelimit.android.sync.actions.apply.ApplyActionChildAuthentication +import io.timelimit.android.sync.actions.apply.ApplyActionUtil +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.AuthenticatedUser +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +class LoginDialogFragmentModel(application: Application): AndroidViewModel(application) { + val selectedUserId = MutableLiveData().apply { value = null } + private val logic = DefaultAppLogic.with(application) + private val users = logic.database.user().getAllUsersLive() + private val isConnectedMode = logic.fullVersion.isLocalMode.invert() + private val selectedUser = users.switchMap { users -> + selectedUserId.map { userId -> + users.find { it.id == userId } + } + } + private val currentDeviceUser = logic.deviceUserId + private val isCheckingPassword = MutableLiveData().apply { value = false } + private val wasPasswordWrong = MutableLiveData().apply { value = false } + private val isLoginDone = MutableLiveData().apply { value = false } + private val loginLock = Mutex() + + val status: LiveData = isLoginDone.switchMap { isLoginDone -> + if (isLoginDone) { + liveDataFromValue(LoginDialogDone as LoginDialogStatus) + } else { + selectedUser.switchMap { selectedUser -> + when (selectedUser?.type) { + UserType.Parent -> { + val isAlreadyCurrentUser = currentDeviceUser.map { it == selectedUser.id }.ignoreUnchanged() + + isConnectedMode.switchMap { isConnectedMode -> + isAlreadyCurrentUser.switchMap { isAlreadyCurrentUser -> + isCheckingPassword.switchMap { isCheckingPassword -> + wasPasswordWrong.map { wasPasswordWrong -> + ParentUserLogin( + isConnectedMode = isConnectedMode, + isAlreadyCurrentDeviceUser = isAlreadyCurrentUser, + isCheckingPassword = isCheckingPassword, + wasPasswordWrong = wasPasswordWrong + ) as LoginDialogStatus + } + } + } + } + } + UserType.Child -> { + logic.fullVersion.shouldProvideFullVersionFunctions.switchMap { fullversion -> + if (fullversion) { + if (selectedUser.password.isEmpty()) { + liveDataFromValue(CanNotSignInChildHasNoPassword(childName = selectedUser.name) as LoginDialogStatus) + } else { + val isAlreadyCurrentUser = currentDeviceUser.map { it == selectedUser.id }.ignoreUnchanged() + + isAlreadyCurrentUser.switchMap { isSignedIn -> + if (isSignedIn) { + liveDataFromValue(ChildAlreadyDeviceUser as LoginDialogStatus) + } else { + isCheckingPassword.switchMap { isCheckingPassword -> + wasPasswordWrong.map { wasPasswordWrong -> + ChildUserLogin( + isCheckingPassword = isCheckingPassword, + wasPasswordWrong = wasPasswordWrong + ) as LoginDialogStatus + } + } + } + } + } + } else { + liveDataFromValue(ChildLoginRequiresPremiumStatus as LoginDialogStatus) + } + } + } + null -> { + users.map { users -> + UserListLoginDialogStatus(users) as LoginDialogStatus + } + } + } + } + } + } + + fun startSignIn(user: User) { + selectedUserId.value = user.id + } + + fun tryParentLogin( + password: String, + keepSignedIn: Boolean, + setAsDeviceUser: Boolean, + model: ActivityViewModel + ) { + runAsync { + loginLock.withLock { + try { + isCheckingPassword.value = true + + val userEntry = selectedUser.waitForNullableValue() + val ownDeviceId = logic.deviceId.waitForNullableValue() + + if (userEntry?.type != UserType.Parent || ownDeviceId == null) { + selectedUserId.value = null + + return@runAsync + } + + val passwordValid = Threads.crypto.executeAndWait { PasswordHashing.validateSync(password, userEntry.password) } + + if (!passwordValid) { + wasPasswordWrong.value = true + + return@runAsync + } + + val secondPasswordHash = Threads.crypto.executeAndWait { PasswordHashing.hashSyncWithSalt(password, userEntry.secondPasswordSalt) } + + val authenticatedUser = AuthenticatedUser( + userId = userEntry.id, + firstPasswordHash = userEntry.password, + secondPasswordHash = secondPasswordHash + ) + + model.setAuthenticatedUser(authenticatedUser) + + if (setAsDeviceUser) { + val deviceEntry = logic.deviceEntry.waitForNonNullValue()!! + + if (deviceEntry.currentUserId != userEntry.id) { + ActivityViewModel.dispatchWithoutCheckOrCatching( + SetDeviceUserAction( + deviceId = ownDeviceId, + userId = userEntry.id + ), + authenticatedUser = authenticatedUser, + logic = logic + ) + } + } + + if (keepSignedIn) { + if ( + setAsDeviceUser || + (currentDeviceUser.waitForNullableValue() == userEntry.id) + ) { + ActivityViewModel.dispatchWithoutCheckOrCatching( + SetKeepSignedInAction( + deviceId = ownDeviceId, + keepSignedIn = true + ), + authenticatedUser = authenticatedUser, + logic = logic + ) + } + } + + isLoginDone.value = true + } finally { + isCheckingPassword.value = false + } + } + } + } + + fun tryChildLogin( + password: String, + model: ActivityViewModel + ) { + runAsync { + loginLock.withLock { + try { + isCheckingPassword.value = true + + val userEntry = selectedUser.waitForNullableValue() + val ownDeviceId = logic.deviceId.waitForNullableValue() + + if (userEntry?.type != UserType.Child || ownDeviceId == null) { + selectedUserId.value = null + + return@runAsync + } + + val passwordValid = Threads.crypto.executeAndWait { PasswordHashing.validateSync(password, userEntry.password) } + + if (!passwordValid) { + wasPasswordWrong.value = true + + return@runAsync + } + + val secondPasswordHash = Threads.crypto.executeAndWait { PasswordHashing.hashSyncWithSalt(password, userEntry.secondPasswordSalt) } + + ApplyActionUtil.applyChildAction( + action = ChildSignInAction, + database = logic.database, + authentication = ApplyActionChildAuthentication( + childUserId = userEntry.id, + secondPasswordHash = secondPasswordHash + ), + syncUtil = logic.syncUtil + ) + + Toast.makeText(getApplication(), R.string.login_child_done_toast, Toast.LENGTH_SHORT).show() + + isLoginDone.value = true + } finally { + isCheckingPassword.value = false + } + } + } + } + + fun resetPasswordWrong() { + if (wasPasswordWrong.value == true) { + wasPasswordWrong.value = false + } + } + + fun goBack(): Boolean { + return if (status.value is UserListLoginDialogStatus) { + false + } else { + selectedUserId.value = null + + true + } + } +} + +sealed class LoginDialogStatus +data class UserListLoginDialogStatus(val usersToShow: List): LoginDialogStatus() +data class ParentUserLogin( + val isConnectedMode: Boolean, + val isAlreadyCurrentDeviceUser: Boolean, + val isCheckingPassword: Boolean, + val wasPasswordWrong: Boolean +): LoginDialogStatus() +object LoginDialogDone: LoginDialogStatus() +data class CanNotSignInChildHasNoPassword(val childName: String): LoginDialogStatus() +object ChildAlreadyDeviceUser: LoginDialogStatus() +data class ChildUserLogin( + val isCheckingPassword: Boolean, + val wasPasswordWrong: Boolean +): LoginDialogStatus() +object ChildLoginRequiresPremiumStatus: LoginDialogStatus() \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/login/LoginUserAdapter.kt b/app/src/main/java/io/timelimit/android/ui/login/LoginUserAdapter.kt new file mode 100644 index 0000000..959b5f7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/login/LoginUserAdapter.kt @@ -0,0 +1,70 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.login + +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.data.model.User +import io.timelimit.android.ui.list.TextViewHolder +import kotlin.properties.Delegates + +class LoginUserAdapter : RecyclerView.Adapter() { + var data: List? by Delegates.observable(null as List?) { _, _, _ -> notifyDataSetChanged() } + var listener: LoginUserAdapterListener? by Delegates.observable(null as LoginUserAdapterListener?) { _, _, _ -> notifyDataSetChanged() } + + init { + setHasStableIds(true) + } + + fun getItem(position: Int): User { + return data!![position] + } + + override fun getItemCount(): Int { + val data = this.data + + if (data == null) { + return 0 + } else { + return data.size + } + } + + override fun getItemId(position: Int): Long { + return getItem(position).id.hashCode().toLong() + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TextViewHolder { + return TextViewHolder(parent) + } + + override fun onBindViewHolder(holder: TextViewHolder, position: Int) { + val item = getItem(position) + val listener = this.listener + + holder.textView.text = item.name + + if (listener !=null) { + holder.textView.setOnClickListener { listener.onUserClicked(item) } + } else { + holder.textView.setOnClickListener(null) + } + } +} + +interface LoginUserAdapterListener { + fun onUserClicked(user: User) +} diff --git a/app/src/main/java/io/timelimit/android/ui/login/NewLoginFragment.kt b/app/src/main/java/io/timelimit/android/ui/login/NewLoginFragment.kt new file mode 100644 index 0000000..d96e11c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/login/NewLoginFragment.kt @@ -0,0 +1,225 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.login + +import android.content.Context +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.InputMethodManager +import android.widget.Toast +import androidx.fragment.app.DialogFragment +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.recyclerview.widget.LinearLayoutManager +import com.google.android.material.bottomsheet.BottomSheetDialog +import io.timelimit.android.R +import io.timelimit.android.data.model.User +import io.timelimit.android.databinding.NewLoginFragmentBinding +import io.timelimit.android.extensions.setOnEnterListenr +import io.timelimit.android.ui.main.getActivityViewModel + +class NewLoginFragment: DialogFragment() { + companion object { + private const val SELECTED_USER_ID = "selectedUserId" + private const val USER_LIST = 0 + private const val PARENT_AUTH = 1 + private const val CHILD_MISSING_PASSWORD = 2 + private const val CHILD_ALREADY_CURRENT_USER = 3 + private const val CHILD_AUTH = 4 + private const val CHILD_LOGIN_REQUIRES_PREMIUM = 5 + } + + private val model: LoginDialogFragmentModel by lazy { + ViewModelProviders.of(this).get(LoginDialogFragmentModel::class.java) + } + private val inputMethodManager: InputMethodManager by lazy { + context!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + if (savedInstanceState?.containsKey(SELECTED_USER_ID) == true) { + model.selectedUserId.value = savedInstanceState.getString(SELECTED_USER_ID) + } + } + + override fun onCreateDialog(savedInstanceState: Bundle?) = object: BottomSheetDialog(context!!, theme) { + override fun onBackPressed() { + if (!model.goBack()) { + super.onBackPressed() + } + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + + model.selectedUserId.value?.let { outState.putString(SELECTED_USER_ID, it) } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = NewLoginFragmentBinding.inflate(inflater, container, false) + + val adapter = LoginUserAdapter() + + adapter.listener = object: LoginUserAdapterListener { + override fun onUserClicked(user: User) { + // reset parent password view + binding.enterPassword.checkAssignMyself.isChecked = false + binding.enterPassword.checkDontAskAgain.isChecked = false + binding.enterPassword.password.setText("") + + // go to the next step + model.startSignIn(user) + } + } + + binding.userList.recycler.adapter = adapter + binding.userList.recycler.layoutManager = LinearLayoutManager(context) + + binding.enterPassword.apply { + password.setOnEnterListenr { + model.tryParentLogin( + password = password.text.toString(), + keepSignedIn = checkDontAskAgain.isChecked, + model = getActivityViewModel(activity!!), + setAsDeviceUser = checkAssignMyself.isChecked + ) + } + } + + binding.childPassword.apply { + password.setOnEnterListenr { + model.tryChildLogin( + password = password.text.toString(), + model = getActivityViewModel(activity!!) + ) + } + } + + model.status.observe(this, Observer { status -> + when (status) { + LoginDialogDone -> { + dismissAllowingStateLoss() + } + is UserListLoginDialogStatus -> { + if (binding.switcher.displayedChild != USER_LIST) { + binding.switcher.setInAnimation(context!!, R.anim.wizard_close_step_in) + binding.switcher.setOutAnimation(context!!, R.anim.wizard_close_step_out) + binding.switcher.displayedChild = USER_LIST + } + + adapter.data = status.usersToShow + } + is ParentUserLogin -> { + if (binding.switcher.displayedChild != PARENT_AUTH) { + binding.switcher.setInAnimation(context!!, R.anim.wizard_open_step_in) + binding.switcher.setOutAnimation(context!!, R.anim.wizard_open_step_out) + binding.switcher.displayedChild = PARENT_AUTH + } + + binding.enterPassword.password.requestFocus() + inputMethodManager.showSoftInput(binding.enterPassword.password, 0) + + binding.enterPassword.showKeepLoggedInOption = status.isConnectedMode + + if (status.isAlreadyCurrentDeviceUser) { + binding.enterPassword.canNotKeepLoggedIn = false + + binding.enterPassword.checkAssignMyself.setOnCheckedChangeListener { _, _ -> } + binding.enterPassword.checkAssignMyself.isEnabled = false + binding.enterPassword.checkAssignMyself.isChecked = true + } else { + binding.enterPassword.checkAssignMyself.isEnabled = true + + fun bindCanNotKeepLoggedIn() { + binding.enterPassword.canNotKeepLoggedIn = !binding.enterPassword.checkAssignMyself.isChecked + } + + bindCanNotKeepLoggedIn() + binding.enterPassword.checkAssignMyself.setOnCheckedChangeListener { _, _ -> bindCanNotKeepLoggedIn() } + } + + binding.enterPassword.password.isEnabled = !status.isCheckingPassword + + if (status.wasPasswordWrong) { + Toast.makeText(context!!, R.string.login_snackbar_wrong, Toast.LENGTH_SHORT).show() + binding.enterPassword.password.setText("") + + model.resetPasswordWrong() + } + + null + } + is CanNotSignInChildHasNoPassword -> { + if (binding.switcher.displayedChild != CHILD_MISSING_PASSWORD) { + binding.switcher.setInAnimation(context!!, R.anim.wizard_open_step_in) + binding.switcher.setOutAnimation(context!!, R.anim.wizard_open_step_out) + binding.switcher.displayedChild = CHILD_MISSING_PASSWORD + } + + binding.childWithoutPassword.childName = status.childName + + null + } + is ChildAlreadyDeviceUser -> { + if (binding.switcher.displayedChild != CHILD_ALREADY_CURRENT_USER) { + binding.switcher.setInAnimation(context!!, R.anim.wizard_open_step_in) + binding.switcher.setOutAnimation(context!!, R.anim.wizard_open_step_out) + binding.switcher.displayedChild = CHILD_ALREADY_CURRENT_USER + } + + null + } + is ChildUserLogin -> { + if (binding.switcher.displayedChild != CHILD_AUTH) { + binding.switcher.setInAnimation(context!!, R.anim.wizard_open_step_in) + binding.switcher.setOutAnimation(context!!, R.anim.wizard_open_step_out) + binding.switcher.displayedChild = CHILD_AUTH + } + + binding.childPassword.password.requestFocus() + inputMethodManager.showSoftInput(binding.childPassword.password, 0) + + binding.childPassword.password.isEnabled = !status.isCheckingPassword + + if (status.wasPasswordWrong) { + Toast.makeText(context!!, R.string.login_snackbar_wrong, Toast.LENGTH_SHORT).show() + binding.childPassword.password.setText("") + + model.resetPasswordWrong() + } + + null + } + ChildLoginRequiresPremiumStatus -> { + if (binding.switcher.displayedChild != CHILD_LOGIN_REQUIRES_PREMIUM) { + binding.switcher.setInAnimation(context!!, R.anim.wizard_open_step_in) + binding.switcher.setOutAnimation(context!!, R.anim.wizard_open_step_out) + binding.switcher.displayedChild = CHILD_LOGIN_REQUIRES_PREMIUM + } + + null + } + }.let { /* require handling all cases */ } + }) + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/main/ActivityViewModel.kt b/app/src/main/java/io/timelimit/android/ui/main/ActivityViewModel.kt new file mode 100644 index 0000000..b465122 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/main/ActivityViewModel.kt @@ -0,0 +1,178 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.main + +import android.app.Application +import android.util.Log +import android.widget.Toast +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.ParentAction +import io.timelimit.android.sync.actions.apply.ApplyActionParentAuthentication +import io.timelimit.android.sync.actions.apply.ApplyActionParentDeviceAuthentication +import io.timelimit.android.sync.actions.apply.ApplyActionParentPasswordAuthentication +import io.timelimit.android.sync.actions.apply.ApplyActionUtil + +class ActivityViewModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "ActivityViewModel" + + suspend fun dispatchWithoutCheckOrCatching( + action: ParentAction, + authenticatedUser: AuthenticatedUser, + logic: AppLogic + ) { + ApplyActionUtil.applyParentAction( + action = action, + database = logic.database, + authentication = ApplyActionParentPasswordAuthentication( + parentUserId = authenticatedUser.userId, + secondPasswordHash = authenticatedUser.secondPasswordHash + ), + syncUtil = logic.syncUtil, + platformIntegration = logic.platformIntegration + ) + } + } + + val logic = DefaultAppLogic.with(application) + val database = logic.database + + val shouldHighlightAuthenticationButton = MutableLiveData().apply { value = false } + + private val authenticatedUserMetadata = MutableLiveData().apply { value = null } + private val deviceEntry = logic.deviceEntry + private val deviceUser = logic.deviceUserEntry + private val userWhichIsKeptSignedIn = deviceEntry.switchMap { device -> + if (device?.isUserKeptSignedIn == true) { + deviceUser.map { user -> + if (user?.id == device.currentUserId) { + user + } else { + null as User? + } + } + } else { + liveDataFromValue(null as User?) + } + }.ignoreUnchanged() + + val authenticatedUser = userWhichIsKeptSignedIn.switchMap { signedInUser -> + if (signedInUser != null) { + liveDataFromValue( + (ApplyActionParentDeviceAuthentication to signedInUser) + as Pair? + ) + } else { + authenticatedUserMetadata.switchMap { + authenticatedUser -> + + if (authenticatedUser == null) { + liveDataFromValue(null as Pair?) + } else { + database.user().getUserByIdLive(authenticatedUser.userId).map { + if (it == null || it.password != authenticatedUser.firstPasswordHash) { + null as Pair? + } else { + ApplyActionParentPasswordAuthentication( + parentUserId = authenticatedUser.userId, + secondPasswordHash = authenticatedUser.secondPasswordHash + ) to it + } + } + } + } + } + } + + fun isParentAuthenticated(): Boolean { + val user = authenticatedUser.value + + return user != null && user.second.type == UserType.Parent + } + + fun requestAuthentication() { + shouldHighlightAuthenticationButton.value = true + } + + fun requestAuthenticationOrReturnTrue(): Boolean { + if (isParentAuthenticated()) { + return true + } else { + requestAuthentication() + + return false + } + } + + fun tryDispatchParentAction(action: ParentAction): Boolean = tryDispatchParentActions(listOf(action)) + + fun tryDispatchParentActions(actions: List): Boolean { + val status = authenticatedUser.value + + if (status == null || status.second.type != UserType.Parent) { + requestAuthentication() + return false + } + + runAsync { + try { + actions.forEach { action -> + ApplyActionUtil.applyParentAction( + action = action, + database = database, + authentication = status.first, + syncUtil = logic.syncUtil, + platformIntegration = logic.platformIntegration + ) + } + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "error dispatching actions", ex) + } + + Toast.makeText(getApplication(), R.string.error_general, Toast.LENGTH_SHORT).show() + } + } + + return true + } + + fun setAuthenticatedUser(user: AuthenticatedUser) { + authenticatedUserMetadata.value = user + } + + fun logOut() { + authenticatedUserMetadata.value = null + } +} + +data class AuthenticatedUser ( + val userId: String, + val firstPasswordHash: String, + val secondPasswordHash: String +) diff --git a/app/src/main/java/io/timelimit/android/ui/main/ActivityViewModelHolder.kt b/app/src/main/java/io/timelimit/android/ui/main/ActivityViewModelHolder.kt new file mode 100644 index 0000000..20c7258 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/main/ActivityViewModelHolder.kt @@ -0,0 +1,31 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.main + +import android.app.Activity + +interface ActivityViewModelHolder { + fun getActivityViewModel(): ActivityViewModel + fun showAuthenticationScreen() +} + +fun getActivityViewModel(activity: Activity): ActivityViewModel { + if (activity is ActivityViewModelHolder) { + return activity.getActivityViewModel() + } else { + throw IllegalStateException() + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/main/AuthenticationFab.kt b/app/src/main/java/io/timelimit/android/ui/main/AuthenticationFab.kt new file mode 100644 index 0000000..2bfa332 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/main/AuthenticationFab.kt @@ -0,0 +1,115 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.main + +import android.util.Log +import androidx.core.content.ContextCompat +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Observer +import com.getkeepsafe.taptargetview.TapTarget +import com.getkeepsafe.taptargetview.TapTargetView +import com.google.android.material.floatingactionbutton.FloatingActionButton +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.and +import io.timelimit.android.livedata.invert +import io.timelimit.android.livedata.map +import io.timelimit.android.sync.actions.apply.ApplyActionParentAuthentication + +object AuthenticationFab { + private const val LOG_TAG = "AuthenticationFab" + + fun manageAuthenticationFab( + fab: FloatingActionButton, + shouldHighlight: MutableLiveData, + authenticatedUser: LiveData?>, + doesSupportAuth: LiveData, + fragment: Fragment + ) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "start managing FAB instance") + } + + var tapTargetView: TapTargetView? = null + + val highlightObserver = Observer { + if (it == true) { + if (tapTargetView == null && fab.isAttachedToWindow) { + tapTargetView = TapTargetView.showFor(fragment.activity!!, + TapTarget.forView(fab, fragment.getString(R.string.authentication_required_overlay_title), fragment.getString(R.string.authentication_required_overlay_text)) + .cancelable(true) + .tintTarget(true) + .transparentTarget(false) + .outerCircleColor(R.color.colorAccent) + .icon(ContextCompat.getDrawable(fragment.context!!, R.drawable.ic_lock_open_white_24dp)), + object : TapTargetView.Listener() { + override fun onTargetClick(view: TapTargetView) { + super.onTargetClick(view) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "target clicked") + } + + tapTargetView = null + fab.callOnClick() + } + + override fun onTargetDismissed(view: TapTargetView?, userInitiated: Boolean) { + super.onTargetDismissed(view, userInitiated) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "target dismissed") + } + + tapTargetView = null + shouldHighlight.value = false + } + }) + } + } else { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "dismissing tap target view; view == null: ${tapTargetView == null}") + } + + tapTargetView?.let { + if (it.isLaidOut) { + it.dismiss(false) + } + } + + tapTargetView = null + } + } + + val isParentAuthenticated = authenticatedUser.map { it != null && it.second.type == UserType.Parent } + val shouldShowFab = (isParentAuthenticated.invert()).and(doesSupportAuth) + + val showFabObserver = Observer { + if (it == true) { + fab.show() + } else { + fab.hide() + } + } + + shouldHighlight.observe(fragment, highlightObserver) + shouldShowFab.observe(fragment, showFabObserver) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/main/FragmentWithCustomTitle.kt b/app/src/main/java/io/timelimit/android/ui/main/FragmentWithCustomTitle.kt new file mode 100644 index 0000000..c425b9d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/main/FragmentWithCustomTitle.kt @@ -0,0 +1,22 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.main + +import androidx.lifecycle.LiveData + +interface FragmentWithCustomTitle { + fun getCustomTitle(): LiveData +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/ManageCategoryFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/ManageCategoryFragment.kt new file mode 100644 index 0000000..fdf1b5e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/ManageCategoryFragment.kt @@ -0,0 +1,127 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import androidx.navigation.Navigation +import androidx.viewpager.widget.ViewPager +import io.timelimit.android.R +import io.timelimit.android.data.model.Category +import io.timelimit.android.data.model.User +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.mergeLiveData +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.main.AuthenticationFab +import io.timelimit.android.ui.main.FragmentWithCustomTitle +import kotlinx.android.synthetic.main.fragment_manage_category.* + +class ManageCategoryFragment : Fragment(), FragmentWithCustomTitle { + private val params: ManageCategoryFragmentArgs by lazy { ManageCategoryFragmentArgs.fromBundle(arguments!!) } + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val category: LiveData by lazy { + logic.database.category() + .getCategoryByChildIdAndId(params.childId, params.categoryId) + } + private val user: LiveData by lazy { + logic.database.user().getUserByIdLive(params.childId) + } + private val adapter: PagerAdapter by lazy { PagerAdapter(childFragmentManager, params) } + private val activity: ActivityViewModelHolder by lazy { getActivity() as ActivityViewModelHolder } + private var wereViewsCreated = false + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_manage_category, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + AuthenticationFab.manageAuthenticationFab( + fab = fab, + fragment = this, + doesSupportAuth = liveDataFromValue(true), + authenticatedUser = activity.getActivityViewModel().authenticatedUser, + shouldHighlight = activity.getActivityViewModel().shouldHighlightAuthenticationButton + ) + + fab.setOnClickListener { activity.showAuthenticationScreen() } + + val navigation = Navigation.findNavController(view) + + pager.adapter = adapter + + bottom_navigation_view.setOnNavigationItemSelectedListener { + menuItem -> + + pager.currentItem = when(menuItem.itemId) { + R.id.manage_category_tab_apps -> 0 + R.id.manage_category_tab_time_limit_rules -> 1 + R.id.manage_category_tab_blocked_time_areas -> 2 + R.id.manage_category_tab_usage_log -> 3 + R.id.manage_category_tab_settings -> 4 + else -> 0 + } + + true + } + + pager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener { + override fun onPageScrollStateChanged(state: Int) { + // ignore + } + + override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { + // ignore + } + + override fun onPageSelected(position: Int) { + bottom_navigation_view.selectedItemId = when(position) { + 0 -> R.id.manage_category_tab_apps + 1 -> R.id.manage_category_tab_time_limit_rules + 2 -> R.id.manage_category_tab_blocked_time_areas + 3 -> R.id.manage_category_tab_usage_log + 4 -> R.id.manage_category_tab_settings + else -> throw IllegalStateException() + } + } + }) + + if (!wereViewsCreated) { + wereViewsCreated = true + + category.observe(this, Observer { + if (it == null) { + navigation.popBackStack() + } + }) + } + } + + override fun getCustomTitle(): LiveData = mergeLiveData(user, category).map { + (user, category) -> + + "${category?.title} - ${user?.name}" + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/PagerAdapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/PagerAdapter.kt new file mode 100644 index 0000000..58a0041 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/PagerAdapter.kt @@ -0,0 +1,38 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category + +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentManager +import androidx.fragment.app.FragmentStatePagerAdapter +import io.timelimit.android.ui.manage.category.apps.CategoryAppsFragment +import io.timelimit.android.ui.manage.category.blocked_times.BlockedTimeAreasFragment +import io.timelimit.android.ui.manage.category.settings.CategorySettingsFragment +import io.timelimit.android.ui.manage.category.timelimit_rules.CategoryTimeLimitRulesFragment +import io.timelimit.android.ui.manage.category.usagehistory.UsageHistoryFragment + +class PagerAdapter(fragmentManager: FragmentManager, private val params: ManageCategoryFragmentArgs): FragmentStatePagerAdapter(fragmentManager) { + override fun getCount() = 5 + + override fun getItem(position: Int): Fragment = when (position) { + 0 -> CategoryAppsFragment.newInstance(params) + 1 -> CategoryTimeLimitRulesFragment.newInstance(params) + 2 -> BlockedTimeAreasFragment.newInstance(params) + 3 -> UsageHistoryFragment.newInstance(params) + 4 -> CategorySettingsFragment.newInstance(params) + else -> throw IllegalStateException() + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/apps/AppAdapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/AppAdapter.kt new file mode 100644 index 0000000..cb91f58 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/AppAdapter.kt @@ -0,0 +1,120 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.apps + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.R +import io.timelimit.android.databinding.AddItemViewBinding +import io.timelimit.android.databinding.FragmentCategoryAppsItemBinding +import io.timelimit.android.logic.DefaultAppLogic +import kotlin.properties.Delegates + +class AppAdapter: RecyclerView.Adapter() { + companion object { + private const val TYPE_ITEM = 1 + private const val TYPE_ADD = 2 + } + + var data: List? by Delegates.observable(null as List?) { _, _, _ -> notifyDataSetChanged() } + var handlers: Handlers? by Delegates.observable(null as Handlers?) { _, _, _ -> notifyDataSetChanged() } + + init { + setHasStableIds(true) + } + + private fun getItem(position: Int): AppEntry { + return data!![position] + } + + override fun getItemId(position: Int) = when { + position == data!!.size -> 1 + else -> getItem(position).hashCode().toLong() + } + + override fun getItemCount(): Int { + val data = this.data + + if (data == null) { + return 0 + } else { + return data.size + 1 + } + } + + override fun getItemViewType(position: Int) = when { + position == data!!.size -> TYPE_ADD + else -> TYPE_ITEM + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = when (viewType) { + TYPE_ADD -> { + ViewHolder( + AddItemViewBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ).apply { + label = parent.context.getString(R.string.category_apps_add_dialog_btn_positive) + wide = true + + root.setOnClickListener { handlers?.onAddAppsClicked() } + }.root + ) + } + TYPE_ITEM -> { + AppViewHolder( + FragmentCategoryAppsItemBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + } + else -> throw IllegalStateException() + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + if (position == data!!.size) { + // nothing to do + } else { + val item = getItem(position) + val binding = (holder as AppViewHolder).binding + + binding.item = item + binding.handlers = handlers + binding.executePendingBindings() + + // TODO: bind icon more modular + binding.icon.setImageDrawable( + DefaultAppLogic.with(binding.root.context) + .platformIntegration.getAppIcon(item.packageName) + ) + } + } +} + +open class ViewHolder(view: View): RecyclerView.ViewHolder(view) +class AppViewHolder(val binding: FragmentCategoryAppsItemBinding): ViewHolder(binding.root) + +data class AppEntry(val title: String, val packageName: String) + +interface Handlers { + fun onAppClicked(app: AppEntry) + fun onAddAppsClicked() +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/apps/CategoryAppsFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/CategoryAppsFragment.kt new file mode 100644 index 0000000..fccbd27 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/CategoryAppsFragment.kt @@ -0,0 +1,95 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.apps + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.recyclerview.widget.LinearLayoutManager +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.data.Database +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.AddCategoryAppsAction +import io.timelimit.android.sync.actions.RemoveCategoryAppsAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.category.ManageCategoryFragmentArgs +import io.timelimit.android.ui.manage.category.apps.add.AddCategoryAppsFragment +import kotlinx.android.synthetic.main.fragment_category_apps.* + +class CategoryAppsFragment : Fragment() { + companion object { + fun newInstance(params: ManageCategoryFragmentArgs): CategoryAppsFragment = CategoryAppsFragment().apply { + arguments = params.toBundle() + } + } + + private val params: ManageCategoryFragmentArgs by lazy { ManageCategoryFragmentArgs.fromBundle(arguments!!) } + private val database: Database by lazy { DefaultAppLogic.with(context!!).database } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val model: CategoryAppsModel by lazy { + ViewModelProviders.of(this).get(CategoryAppsModel::class.java) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_category_apps, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + val adapter = AppAdapter() + + adapter.handlers = object: Handlers { + override fun onAppClicked(app: AppEntry) { + if (auth.tryDispatchParentAction( + RemoveCategoryAppsAction( + categoryId = params.categoryId, + packageNames = listOf(app.packageName) + ) + )) { + Snackbar.make(view, getString(R.string.category_apps_item_removed_toast, app.title), Snackbar.LENGTH_SHORT) + .setAction(R.string.generic_undo) { + auth.tryDispatchParentAction( + AddCategoryAppsAction( + categoryId = params.categoryId, + packageNames = listOf(app.packageName) + ) + ) + } + .show() + } + } + + override fun onAddAppsClicked() { + if (auth.requestAuthenticationOrReturnTrue()) { + AddCategoryAppsFragment.newInstance(params).show(fragmentManager!!) + } + } + } + + recycler.layoutManager = LinearLayoutManager(context!!) + recycler.adapter = adapter + + model.init(params) + model.appEntries.observe(this, Observer { adapter.data = it }) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/apps/CategoryAppsModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/CategoryAppsModel.kt new file mode 100644 index 0000000..eb79ca4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/CategoryAppsModel.kt @@ -0,0 +1,59 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.apps + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.manage.category.ManageCategoryFragmentArgs +import java.util.* + +class CategoryAppsModel(application: Application): AndroidViewModel(application) { + private val logic = DefaultAppLogic.with(application) + private val database = logic.database + private val args = MutableLiveData() + + fun init(args: ManageCategoryFragmentArgs) { + if (this.args.value != args) { + this.args.value = args + } + } + + private val installedApps = database.app().getAllApps() + + private val appsOfThisCategory = args.switchMap { database.categoryApp().getCategoryApps(it.categoryId) } + + private val appsOfCategoryWithNames = installedApps.switchMap { allApps -> + appsOfThisCategory.map { apps -> + apps.map { categoryApp -> + categoryApp to allApps.find { app -> app.packageName == categoryApp.packageName } + } + } + } + + val appEntries = appsOfCategoryWithNames.map { apps -> + apps.map { (app, appEntry) -> + if (appEntry != null) { + AppEntry(appEntry.title, app.packageName) + } else { + AppEntry("app not found", app.packageName) + } + }.sortedBy { it.title.toLowerCase(Locale.US) } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/apps/add/AddAppAdapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/add/AddAppAdapter.kt new file mode 100644 index 0000000..0faa167 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/add/AddAppAdapter.kt @@ -0,0 +1,91 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.apps.add + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.data.model.App +import io.timelimit.android.databinding.FragmentAddCategoryAppsItemBinding +import io.timelimit.android.extensions.toggle +import io.timelimit.android.logic.DefaultAppLogic +import kotlin.properties.Delegates + +class AddAppAdapter: RecyclerView.Adapter() { + var data: List? by Delegates.observable(null as List?) { _, _, _ -> notifyDataSetChanged() } + var categoryTitleByPackageName: Map by Delegates.observable(emptyMap()) { _, _, _ -> notifyDataSetChanged() } + val selectedApps = mutableSetOf() + + private val itemHandlers = object: ItemHandlers { + override fun onAppClicked(app: App) { + selectedApps.toggle(app.packageName) + + notifyDataSetChanged() + } + } + + init { + setHasStableIds(true) + } + + private fun getItem(position: Int): App { + return data!![position] + } + + override fun getItemId(position: Int): Long { + return getItem(position).hashCode().toLong() + } + + override fun getItemCount(): Int { + val data = this.data + + if (data == null) { + return 0 + } else { + return data.size + } + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( + FragmentAddCategoryAppsItemBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ).apply { handlers = itemHandlers } + ) + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val item = getItem(position) + + holder.apply { + binding.item = item + binding.checked = selectedApps.contains(item.packageName) + binding.currentCategoryTitle = categoryTitleByPackageName[item.packageName] + binding.executePendingBindings() + + binding.icon.setImageDrawable( + DefaultAppLogic.with(holder.itemView.context) + .platformIntegration.getAppIcon(item.packageName) + ) + } + } +} + +class ViewHolder(val binding: FragmentAddCategoryAppsItemBinding): RecyclerView.ViewHolder(binding.root) + +interface ItemHandlers { + fun onAppClicked(app: App) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/apps/add/AddCategoryAppsFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/add/AddCategoryAppsFragment.kt new file mode 100644 index 0000000..3945e6b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/add/AddCategoryAppsFragment.kt @@ -0,0 +1,209 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.apps.add + + +import android.app.Dialog +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Observer +import androidx.recyclerview.widget.LinearLayoutManager +import io.timelimit.android.R +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.FragmentAddCategoryAppsBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.AddCategoryAppsAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.category.ManageCategoryFragmentArgs +import io.timelimit.android.ui.view.AppFilterView + +class AddCategoryAppsFragment : DialogFragment() { + companion object { + private const val DIALOG_TAG = "x" + private const val STATUS_PACKAGE_NAMES = "d" + + fun newInstance(params: ManageCategoryFragmentArgs) = AddCategoryAppsFragment().apply { + arguments = params.toBundle() + } + } + + private val params: ManageCategoryFragmentArgs by lazy { ManageCategoryFragmentArgs.fromBundle(arguments!!) } + private val database: Database by lazy { DefaultAppLogic.with(context!!).database } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val adapter = AddAppAdapter() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it == null || it.second.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + if (savedInstanceState != null) { + adapter.selectedApps.addAll( + savedInstanceState.getStringArrayList(STATUS_PACKAGE_NAMES)!! + ) + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + + outState.putStringArrayList(STATUS_PACKAGE_NAMES, ArrayList(adapter.selectedApps)) + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val binding = FragmentAddCategoryAppsBinding.inflate(LayoutInflater.from(context)) + val filter = AppFilterView.getFilterLive(binding.filter) + val isLocalMode = database.config().getDeviceAuthTokenAsync().map { it.isEmpty() } + val showAppsFromOtherDevicesChecked = MutableLiveData().apply { + value = binding.showAppsFromUnassignedDevices.isChecked + } + val realShowAppsFromAllDevices = isLocalMode.switchMap { localMode -> + if (localMode) { + liveDataFromValue(true) + } else { + showAppsFromOtherDevicesChecked + } + } + + binding.showAppsFromUnassignedDevices.setOnCheckedChangeListener { _, isChecked -> + showAppsFromOtherDevicesChecked.value = isChecked + } + + isLocalMode.observe(this, Observer { + binding.showAppsFromUnassignedDevices.visibility = if (it) View.GONE else View.VISIBLE + }) + + val showAppsFromOtherCategories = MutableLiveData().apply { value = binding.showOtherCategoriesApps.isChecked } + binding.showOtherCategoriesApps.setOnCheckedChangeListener { _, isChecked -> showAppsFromOtherCategories.value = isChecked } + + binding.recycler.layoutManager = LinearLayoutManager(context) + binding.recycler.adapter = adapter + + val appsAtAssignedDevices = database.device().getDevicesByUserId(params.childId) + .map { devices -> devices.map { it.id } } + .ignoreUnchanged() + .switchMap { database.app().getAppsByDeviceIds(it) } + + val appsAtAllDevices = database.app().getAllApps() + + val installedApps = realShowAppsFromAllDevices.switchMap { appsFromAllDevices -> + if (appsFromAllDevices) appsAtAllDevices else appsAtAssignedDevices + }.map { apps -> apps.distinctBy { app -> app.packageName } } + + + val childCategories = database.category().getCategoriesByChildId(params.childId) + val childCategoriesWithApps = childCategories.switchMap { categories -> + database.categoryApp().getCategoryApps(categories.map { it.id }) + .map { categoyApps -> categories to categoyApps } + } + + val packageNamesAssignedToOtherCategories = childCategoriesWithApps.map { (_, apps) -> + apps.filter { it.categoryId != params.categoryId }.map { it.packageName }.toSet() + }.ignoreUnchanged() + + filter.switchMap { filter -> + installedApps.map { filter to it } + }.map { (search, apps) -> + apps.filter { search.matches(it) } + }.switchMap { apps -> + showAppsFromOtherCategories.switchMap { showOtherCategeories -> + if (showOtherCategeories) { + liveDataFromValue(apps) + } else { + packageNamesAssignedToOtherCategories.map { packagesFromOtherCategories -> + apps.filterNot { packagesFromOtherCategories.contains(it.packageName) } + } + } + } + }.map { apps -> + apps.sortedBy { app -> app.title.toLowerCase() } + }.observe(this, Observer { + val selectedPackageNames = adapter.selectedApps + val visiblePackageNames = it.map { it.packageName }.toSet() + val hiddenSelectedPackageNames = selectedPackageNames.toMutableSet().apply { removeAll(visiblePackageNames) }.size + + adapter.data = it + binding.hiddenEntries = if (hiddenSelectedPackageNames == 0) + null + else + resources.getQuantityString(R.plurals.category_apps_add_dialog_hidden_entries, hiddenSelectedPackageNames, hiddenSelectedPackageNames) + }) + + childCategoriesWithApps.map { (categories, apps) -> + val categoryById = categories.associateBy { it.id } + val categoryTitleByCategoryId = mutableMapOf() + + apps.forEach { + categoryTitleByCategoryId[it.packageName] = categoryById[it.categoryId]?.title ?: "" + } + + categoryTitleByCategoryId + }.observe(this, Observer { + adapter.categoryTitleByPackageName = it + }) + + binding.addAppsButton.setOnClickListener { + val packageNames = adapter.selectedApps.toList() + + if (packageNames.isNotEmpty()) { + auth.tryDispatchParentAction( + AddCategoryAppsAction( + categoryId = params.categoryId, + packageNames = packageNames + ) + ) + } + + dismiss() + } + + binding.cancelButton.setOnClickListener { + dismiss() + } + + binding.selectAllButton.setOnClickListener { + adapter.selectedApps.addAll( + adapter.data?.map { it.packageName } ?: emptySet() + ) + + adapter.notifyDataSetChanged() + } + + return AlertDialog.Builder(context!!, R.style.AppTheme) + .setView(binding.root) + .create() + } + + fun show(manager: FragmentManager) { + showSafe(manager, DIALOG_TAG) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/Adapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/Adapter.kt new file mode 100644 index 0000000..7d6da85 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/Adapter.kt @@ -0,0 +1,180 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.blocked_times + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.databinding.ViewDataBinding +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentBlockedTimeAreasMinuteTileBinding +import io.timelimit.android.databinding.GenericBigListHeaderBinding +import io.timelimit.android.databinding.GenericListHeaderBinding +import java.util.* +import kotlin.properties.Delegates + +class Adapter(items: BlockedTimeItems): RecyclerView.Adapter() { + var blockedTimeAreas: BitSet? by Delegates.observable(null as BitSet?) { _, _, _ -> notifyDataSetChanged() } + var selectedMinuteOfWeek: Int? by Delegates.observable(null as Int?) { _, _, _ -> notifyDataSetChanged() } + var handlers: Handlers? by Delegates.observable(null as Handlers?) { _, _, _ -> notifyDataSetChanged() } + var items: BlockedTimeItems by Delegates.observable(items) { _, _, _ -> notifyDataSetChanged() } + + init { + setHasStableIds(true) + } + + override fun getItemId(position: Int): Long { + val item = getItem(position) + + return when (item) { + is DayHeader -> "day ${item.day}" + is HourHeader -> "hour ${item.day}-${item.hour}" + is MinuteTile -> "minute ${item.minuteOfWeek}" + }.hashCode().toLong() + } + + override fun getItemCount(): Int = items.itemsPerWeek + + private fun getItem(position: Int): Item = items.getItemAtPosition(position) + + private fun getViewType(item: Item): ViewType = when(item) { + is DayHeader -> ViewType.Day + is HourHeader -> ViewType.Hour + is MinuteTile -> ViewType.Minute + } + + override fun getItemViewType(position: Int): Int { + return getViewType(getItem(position)).ordinal + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = when(viewType) { + ViewType.Day.ordinal -> + DayHeaderViewHolder( + GenericBigListHeaderBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + ViewType.Hour.ordinal -> + HourHeaderViewHolder( + GenericListHeaderBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + ViewType.Minute.ordinal -> MinuteTileViewHolder( + FragmentBlockedTimeAreasMinuteTileBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + else -> throw IllegalStateException() + } + + private fun timeToString(time: Int) = if (time == 0) { + "00" + } else if (time <= 9) { + "0$time" + } else { + time.toString() + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val item = getItem(position) + + when(item) { + is DayHeader -> { + if (holder !is DayHeaderViewHolder) { + throw IllegalStateException() + } + + holder.view.text = holder.view.root.context.resources.getStringArray(R.array.days_of_week_array)[item.day] + } + is HourHeader -> { + if (holder !is HourHeaderViewHolder) { + throw IllegalStateException() + } + + holder.view.text = timeToString(item.hour) + ":00" + } + is MinuteTile -> { + if (holder !is MinuteTileViewHolder) { + throw IllegalStateException() + } + + holder.view.item = item + holder.view.handlers = handlers + holder.view.text = if (items.hasHourHeaders) { + timeToString(item.minute) + } else { + timeToString(item.hour) + ":" + timeToString(item.minute) + } + + val blockedTimeAreas = blockedTimeAreas + + if (blockedTimeAreas == null) { + holder.view.mode = MinuteTileMode.Allowed + } else { + var setBits = 0 + val maxBits = item.lengthInMinutes + + for (i in 0..(maxBits-1)) { + if (blockedTimeAreas[item.minuteOfWeek + i]) { + setBits++ + } + } + + holder.view.mode = when (setBits) { + 0 -> MinuteTileMode.Allowed + maxBits -> MinuteTileMode.Blocked + else -> MinuteTileMode.Mixed + } + } + + holder.view.selected = selectedMinuteOfWeek == item.minuteOfWeek + } + } + + holder.baseView.executePendingBindings() + } +} + +class SpanSizeLookup(private val items: BlockedTimeItems): GridLayoutManager.SpanSizeLookup() { + override fun getSpanSize(position: Int): Int { + return if (items.getItemAtPosition(position) is MinuteTile) { + 1 + } else { + items.recommendColumns + } + } +} + +sealed class ViewHolder(val baseView: ViewDataBinding): RecyclerView.ViewHolder(baseView.root) +class DayHeaderViewHolder(val view: GenericBigListHeaderBinding): ViewHolder(view) +class HourHeaderViewHolder(val view: GenericListHeaderBinding): ViewHolder(view) +class MinuteTileViewHolder(val view: FragmentBlockedTimeAreasMinuteTileBinding): ViewHolder(view) + +enum class ViewType { + Day, Hour, Minute +} + +interface Handlers { + fun onMinuteTileClick(time: MinuteTile) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/BlockedTimeAreasFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/BlockedTimeAreasFragment.kt new file mode 100644 index 0000000..84f6584 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/BlockedTimeAreasFragment.kt @@ -0,0 +1,249 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.blocked_times + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.AdapterView +import android.widget.ArrayAdapter +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Observer +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.RecyclerView +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.data.Database +import io.timelimit.android.data.customtypes.ImmutableBitmask +import io.timelimit.android.data.model.Category +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.UpdateCategoryBlockedTimesAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.category.ManageCategoryFragmentArgs +import io.timelimit.android.ui.manage.category.blocked_times.copy.CopyBlockedTimeAreasDialogFragment +import kotlinx.android.synthetic.main.fragment_blocked_time_areas.* +import java.util.* + +class BlockedTimeAreasFragment : Fragment() { + companion object { + fun newInstance(params: ManageCategoryFragmentArgs): BlockedTimeAreasFragment { + val result = BlockedTimeAreasFragment() + result.arguments = params.toBundle() + return result + } + } + + private val params: ManageCategoryFragmentArgs by lazy { ManageCategoryFragmentArgs.fromBundle(arguments!!) } + private val database: Database by lazy { DefaultAppLogic.with(context!!).database } + private val category: LiveData by lazy { database.category().getCategoryByChildIdAndId(params.childId, params.categoryId) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val items = MutableLiveData() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + items.value = MinuteOfWeekItems + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_blocked_time_areas, container, false) + } + + fun updateBlockedTimes(oldMask: BitSet, newMask: BitSet) { + if ( + auth.tryDispatchParentAction( + UpdateCategoryBlockedTimesAction( + categoryId = params.categoryId, + blockedTimes = ImmutableBitmask(newMask) + ) + ) + ) { + Snackbar.make(coordinator, R.string.blocked_time_areas_snackbar_modified, Snackbar.LENGTH_SHORT) + .setAction(R.string.generic_undo) { + auth.tryDispatchParentAction( + UpdateCategoryBlockedTimesAction( + categoryId = params.categoryId, + blockedTimes = ImmutableBitmask(oldMask) + ) + ) + } + .show() + } + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + val layoutManager = GridLayoutManager(context, items.value!!.recommendColumns) + layoutManager.spanSizeLookup = SpanSizeLookup(items.value!!) + + val adapter = Adapter(items.value!!) + + items.observe(this, Observer { + layoutManager.spanCount = it.recommendColumns + layoutManager.spanSizeLookup = SpanSizeLookup(it) + adapter.items = it + }) + + recycler.adapter = adapter + recycler.layoutManager = layoutManager + + category.observe(this, Observer { adapter.blockedTimeAreas = it?.blockedMinutesInWeek?.dataNotToModify }) + + btn_help.setOnClickListener { + BlockedTimeAreasHelpDialog().show(fragmentManager!!) + } + + btn_copy_to_other_days.setOnClickListener { + if (auth.requestAuthenticationOrReturnTrue()) { + CopyBlockedTimeAreasDialogFragment.newInstance(params).apply { + setTargetFragment(this@BlockedTimeAreasFragment, 0) + }.show(fragmentManager!!) + } + } + + adapter.handlers = object: Handlers { + override fun onMinuteTileClick(time: MinuteTile) { + if (auth.requestAuthenticationOrReturnTrue()) { + val selectedMinuteOfWeek = adapter.selectedMinuteOfWeek + val blockedTimeAreas = adapter.blockedTimeAreas + + if (blockedTimeAreas == null) { + // nothing to work with + } else if (selectedMinuteOfWeek == null) { + adapter.selectedMinuteOfWeek = time.minuteOfWeek + } else if (selectedMinuteOfWeek == time.minuteOfWeek) { + adapter.selectedMinuteOfWeek = null + + val newBlockMask = blockedTimeAreas.clone() as BitSet + newBlockMask.set( + selectedMinuteOfWeek, + selectedMinuteOfWeek + items.value!!.minutesPerTile, + !newBlockMask[selectedMinuteOfWeek] + ) + + updateBlockedTimes(blockedTimeAreas, newBlockMask) + } else { + var times = selectedMinuteOfWeek to time.minuteOfWeek + adapter.selectedMinuteOfWeek = null + + // sort selected times + if (times.first > times.second) { + times = times.second to times.first + } + + // mark until the end + times = times.first to (times.second + items.value!!.minutesPerTile - 1) + + // get majority of current value + var allowed = 0 + var blocked = 0 + + for (i in times.first..times.second) { + if (blockedTimeAreas[i]) { + blocked++ + } else { + allowed++ + } + } + + val isMajorityBlocked = blocked > allowed + val shouldBlock = !isMajorityBlocked + + val newBlockMask = blockedTimeAreas.clone() as BitSet + newBlockMask.set(times.first, times.second + 1, shouldBlock) + + updateBlockedTimes(blockedTimeAreas, newBlockMask) + } + } + } + } + + run { + val spinnerAdapter = ArrayAdapter.createFromResource(context!!, R.array.days_of_week_array, android.R.layout.simple_spinner_item) + spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) + spinner_day.adapter = spinnerAdapter + spinner_day.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { + val selectedDay = items.value!!.getDayOfPosition( + layoutManager.findFirstVisibleItemPosition() + ) + + if (selectedDay != position) { + layoutManager.scrollToPositionWithOffset( + items.value!!.getPositionOfItem( + DayHeader(position) + ), + 0 + ) + } + } + + override fun onNothingSelected(parent: AdapterView<*>?) { + // ignore + } + } + } + + recycler.addOnScrollListener(object: RecyclerView.OnScrollListener() { + override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { + super.onScrollStateChanged(recyclerView, newState) + + if (newState == RecyclerView.SCROLL_STATE_IDLE) { + val selectedDay = items.value!!.getDayOfPosition( + layoutManager.findFirstVisibleItemPosition() + ) + + if (selectedDay != spinner_day.selectedItemPosition) { + spinner_day.setSelection(selectedDay, true) + } + } + } + }) + + // bind detailed mode + items.value = when (detailed_mode.isChecked) { + true -> MinuteOfWeekItems + false -> FifteenMinutesOfWeekItems + } + + detailed_mode.setOnCheckedChangeListener { _, isChecked -> + val oldValue = items.value + val newValue = when (isChecked) { + true -> MinuteOfWeekItems + false -> FifteenMinutesOfWeekItems + } + + if (oldValue != newValue) { + val currentlyVisiblePosition = layoutManager.findFirstVisibleItemPosition() + + if (currentlyVisiblePosition == RecyclerView.NO_POSITION) { + items.value = newValue + } else { + val currentlyVisibleItem = oldValue!!.getItemAtPosition(currentlyVisiblePosition) + val newVisiblePosition = newValue.getPositionOfItem(currentlyVisibleItem) + + items.value = newValue + layoutManager.scrollToPositionWithOffset(newVisiblePosition, 0) + } + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/BlockedTimeAreasHelpDialog.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/BlockedTimeAreasHelpDialog.kt new file mode 100644 index 0000000..ebcb3eb --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/BlockedTimeAreasHelpDialog.kt @@ -0,0 +1,40 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.blocked_times + + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.FragmentManager +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.R +import io.timelimit.android.extensions.showSafe + +class BlockedTimeAreasHelpDialog : BottomSheetDialogFragment() { + companion object { + private const val DIALOG_TAG = "r" + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_blocked_time_areas_help_dialog, container, false) + } + + fun show(manager: FragmentManager) { + showSafe(manager, DIALOG_TAG) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/FifteenMinutesOfWeekItems.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/FifteenMinutesOfWeekItems.kt new file mode 100644 index 0000000..7e3925c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/FifteenMinutesOfWeekItems.kt @@ -0,0 +1,56 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.blocked_times + +object FifteenMinutesOfWeekItems: BlockedTimeItems() { + private const val unitsPerHour = 4 + private const val itemsPerHour = unitsPerHour + 0 + private const val hoursPerDay = 24 + private const val itemsPerDay = 1 + (hoursPerDay * itemsPerHour) + override val itemsPerWeek = 7 * itemsPerDay + override val recommendColumns: Int = 4 + override val hasHourHeaders = false + override val minutesPerTile = 15 + + override fun getItemAtPosition(position: Int): Item { + if (position < 0 || position >= itemsPerWeek) { + throw IllegalStateException() + } + + val day = position / itemsPerDay + val itemInDay = position % itemsPerDay + + if (itemInDay == 0) { + return DayHeader(day) + } + + val itemWithinDay = itemInDay - 1 + val hour = itemWithinDay / itemsPerHour + val itemInHour = itemWithinDay % itemsPerHour + + return MinuteTile(day, hour, itemInHour * minutesPerTile, minutesPerTile) + } + + override fun getDayOfPosition(position: Int): Int { + return position / itemsPerDay + } + + override fun getPositionOfItem(item: Item) = when(item) { + is DayHeader -> item.day * itemsPerDay + is HourHeader -> item.day * itemsPerDay + 1 + itemsPerHour * item.hour + is MinuteTile -> item.day * itemsPerDay + 1 + itemsPerHour * item.hour + 0 + item.minute / minutesPerTile + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/Items.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/Items.kt new file mode 100644 index 0000000..c5cc244 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/Items.kt @@ -0,0 +1,33 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.blocked_times + +sealed class Item +data class DayHeader(val day: Int): Item() +data class HourHeader(val day: Int, val hour: Int): Item() +data class MinuteTile(val day: Int, val hour: Int, val minute: Int, val lengthInMinutes: Int): Item() { + val minuteOfWeek = (24 * 60 * day) + (60 * hour) + minute +} + +abstract class BlockedTimeItems { + abstract fun getItemAtPosition(position: Int): Item + abstract fun getDayOfPosition(position: Int): Int + abstract fun getPositionOfItem(item: Item): Int + abstract val recommendColumns: Int + abstract val itemsPerWeek: Int + abstract val hasHourHeaders: Boolean + abstract val minutesPerTile: Int +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/MinuteOfWeekItems.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/MinuteOfWeekItems.kt new file mode 100644 index 0000000..f8c74e9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/MinuteOfWeekItems.kt @@ -0,0 +1,62 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.blocked_times + +object MinuteOfWeekItems: BlockedTimeItems() { + private const val minutesPerHour = 60 + private const val itemsPerHour = minutesPerHour + 1 + private const val hoursPerDay = 24 + private const val itemsPerDay = 1 + (hoursPerDay * itemsPerHour) + override val itemsPerWeek = 7 * itemsPerDay + override val recommendColumns = 10 + override val hasHourHeaders = true + override val minutesPerTile = 1 + + override fun getItemAtPosition(position: Int): Item { + if (position < 0 || position >= itemsPerWeek) { + throw IllegalStateException() + } + + val day = position / itemsPerDay + val itemInDay = position % itemsPerDay + + if (itemInDay == 0) { + return DayHeader(day) + } + + val itemWithinDay = itemInDay - 1 + val hour = itemWithinDay / itemsPerHour + val itemInHour = itemWithinDay % itemsPerHour + + if (itemInHour == 0) { + return HourHeader(day, hour) + } + + val minute = itemInHour - 1 + + return MinuteTile(day, hour, minute, 1) + } + + override fun getDayOfPosition(position: Int): Int { + return position / itemsPerDay + } + + override fun getPositionOfItem(item: Item) = when(item) { + is DayHeader -> item.day * itemsPerDay + is HourHeader -> item.day * itemsPerDay + 1 + itemsPerHour * item.hour + is MinuteTile -> item.day * itemsPerDay + 1 + itemsPerHour * item.hour + 1 + item.minute + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/MinuteTileMode.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/MinuteTileMode.kt new file mode 100644 index 0000000..cb1cffd --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/MinuteTileMode.kt @@ -0,0 +1,22 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.blocked_times + +enum class MinuteTileMode { + Allowed, + Blocked, + Mixed +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/copy/CopyBlockedTimeAreasDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/copy/CopyBlockedTimeAreasDialogFragment.kt new file mode 100644 index 0000000..ee90c25 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/copy/CopyBlockedTimeAreasDialogFragment.kt @@ -0,0 +1,170 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.blocked_times.copy + + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.CheckedTextView +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.Observer +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.Category +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.CopyBlockedTimeAreasDialogFragmentBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.manage.category.ManageCategoryFragmentArgs +import io.timelimit.android.ui.manage.category.blocked_times.BlockedTimeAreasFragment +import java.util.* + +class CopyBlockedTimeAreasDialogFragment : BottomSheetDialogFragment() { + companion object { + private const val TAG = "cbtadf" + private const val SELECTED_START_DAY = "ssd" + + fun newInstance(params: ManageCategoryFragmentArgs) = CopyBlockedTimeAreasDialogFragment().apply { + arguments = params.toBundle() + } + } + + val params: ManageCategoryFragmentArgs by lazy { ManageCategoryFragmentArgs.fromBundle(arguments!!) } + var selectedStartDayIndex = -1 + val auth: ActivityViewModel by lazy { + (activity as ActivityViewModelHolder).getActivityViewModel() + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + if (savedInstanceState != null) { + selectedStartDayIndex = savedInstanceState.getInt(SELECTED_START_DAY) + } + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + + outState.putInt(SELECTED_START_DAY, selectedStartDayIndex) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = CopyBlockedTimeAreasDialogFragmentBinding.inflate(inflater, container, false) + val dayNames = resources.getStringArray(R.array.days_of_week_array) + + val dayCheckboxes = listOf( + binding.toMonday, + binding.toTuesday, + binding.toWednesday, + binding.toThursday, + binding.toFriday, + binding.toSaturday, + binding.toSunday + ) + + fun bindSecondPage() { + dayCheckboxes.forEach { it.isEnabled = true } + + if (selectedStartDayIndex != -1) { + dayCheckboxes[selectedStartDayIndex].isEnabled = false + dayCheckboxes[selectedStartDayIndex].isChecked = false + + binding.sourceDayName = dayNames[selectedStartDayIndex] + } + } + + // init first page + dayNames.forEachIndexed { index, dayName -> + binding.selectSourceDay.addView( + (LayoutInflater.from(context!!).inflate( + android.R.layout.simple_list_item_single_choice, + binding.selectSourceDay, + false + ) as CheckedTextView).let { dayView -> + dayView.text = dayName + dayView.setOnClickListener { + selectedStartDayIndex = index + bindSecondPage() + + binding.flipper.setInAnimation(context!!, R.anim.wizard_open_step_in) + binding.flipper.setOutAnimation(context!!, R.anim.wizard_open_step_out) + binding.flipper.displayedChild = 1 + } + + dayView + } + ) + } + + // init second page + bindSecondPage() + + binding.saveButton.setOnClickListener { + val logic = DefaultAppLogic.with(context!!) + + runAsync { + val current = logic.database.category().getCategoryByChildIdAndId(params.childId, params.categoryId).waitForNullableValue() + ?: return@runAsync + + val newBlockedTimes = current.blockedMinutesInWeek.dataNotToModify.clone() as BitSet + + val configForSelectedDay = newBlockedTimes.get( + selectedStartDayIndex * Category.MINUTES_PER_DAY, + (selectedStartDayIndex + 1) * Category.MINUTES_PER_DAY + ) + + // update all days + dayCheckboxes.forEachIndexed { day, checkBox -> + if (checkBox.isChecked) { + val startWriteIndex = day * Category.MINUTES_PER_DAY + + for (i in 0..(Category.MINUTES_PER_DAY - 1)) { + newBlockedTimes[startWriteIndex + i] = configForSelectedDay[i] + } + } + } + + // apply + val target = targetFragment as BlockedTimeAreasFragment + target.updateBlockedTimes(current.blockedMinutesInWeek.dataNotToModify, newBlockedTimes) + } + + dismissAllowingStateLoss() + } + + // continue + if (selectedStartDayIndex != -1) { + binding.flipper.displayedChild = 1 + } + + return binding.root + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/settings/CategorySettingsFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/CategorySettingsFragment.kt new file mode 100644 index 0000000..faec10f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/CategorySettingsFragment.kt @@ -0,0 +1,120 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.settings + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentCategorySettingsBinding +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.SetCategoryExtraTimeAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.category.ManageCategoryFragmentArgs +import io.timelimit.android.ui.payment.RequiresPurchaseDialogFragment + +class CategorySettingsFragment : Fragment() { + companion object { + fun newInstance(params: ManageCategoryFragmentArgs): CategorySettingsFragment { + val result = CategorySettingsFragment() + result.arguments = params.toBundle() + return result + } + } + + private val params: ManageCategoryFragmentArgs by lazy { ManageCategoryFragmentArgs.fromBundle(arguments!!) } + private val appLogic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentCategorySettingsBinding.inflate(inflater, container, false) + + val categoryEntry = appLogic.database.category().getCategoryByChildIdAndId(params.childId, params.categoryId) + + ManageCategoryForUnassignedApps.bind( + binding = binding.categoryForUnassignedApps, + lifecycleOwner = this, + categoryId = params.categoryId, + childId = params.childId, + database = appLogic.database, + auth = auth + ) + + ParentCategoryView.bind( + binding = binding.parentCategory, + lifecycleOwner = this, + categoryId = params.categoryId, + childId = params.childId, + database = appLogic.database, + fragmentManager = fragmentManager!!, + auth = auth + ) + + binding.btnDeleteCategory.setOnClickListener { deleteCategory() } + binding.editCategoryTitleGo.setOnClickListener { renameCategory() } + + categoryEntry.observe(this, Observer { + if (it != null) { + val roundedCurrentTimeInMillis = (it.extraTimeInMillis / (1000 * 60)) * (1000 * 60) + + if (binding.extraTimeSelection.timeInMillis != roundedCurrentTimeInMillis) { + binding.extraTimeSelection.timeInMillis = roundedCurrentTimeInMillis + } + } + }) + + appLogic.fullVersion.shouldProvideFullVersionFunctions.observe(this, Observer { hasFullVersion -> + binding.extraTimeBtnOk.setOnClickListener { + if (hasFullVersion) { + val newExtraTime = binding.extraTimeSelection.timeInMillis + + if ( + auth.tryDispatchParentAction( + SetCategoryExtraTimeAction( + categoryId = params.categoryId, + newExtraTime = newExtraTime + ) + ) + ) { + Snackbar.make(binding.root, R.string.category_settings_extra_time_change_toast, Snackbar.LENGTH_SHORT).show() + } + } else { + RequiresPurchaseDialogFragment().show(fragmentManager!!) + } + } + }) + + return binding.root + } + + private fun renameCategory() { + if (auth.requestAuthenticationOrReturnTrue()) { + RenameCategoryDialogFragment.newInstance(params).show(fragmentManager!!) + } + } + + private fun deleteCategory() { + if (auth.requestAuthenticationOrReturnTrue()) { + DeleteCategoryDialogFragment.newInstance(params).show(fragmentManager!!) + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/settings/DeleteCategoryDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/DeleteCategoryDialogFragment.kt new file mode 100644 index 0000000..0a729db --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/DeleteCategoryDialogFragment.kt @@ -0,0 +1,88 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.settings + +import android.os.Bundle +import android.view.View +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.data.model.Category +import io.timelimit.android.data.model.UserType +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.DeleteCategoryAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.category.ManageCategoryFragmentArgs +import io.timelimit.android.ui.util.ConfirmDeleteDialogFragment + +class DeleteCategoryDialogFragment: ConfirmDeleteDialogFragment() { + companion object { + private const val TAG = "DeleteCategoryDialogFragment" + + fun newInstance(args: ManageCategoryFragmentArgs) = DeleteCategoryDialogFragment().apply { + arguments = args.toBundle() + } + } + + private val params: ManageCategoryFragmentArgs by lazy { ManageCategoryFragmentArgs.fromBundle(arguments!!) } + private val appLogic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + + val categoryEntry: LiveData by lazy { + appLogic.database.category().getCategoryByChildIdAndId( + categoryId = params.categoryId, + childId = params.childId + ) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + categoryEntry.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + categoryEntry.observe(this, Observer { + binding.text = getString(R.string.category_settings_delete_dialog, it?.title) + }) + } + + override fun onConfirmDeletion() { + auth.tryDispatchParentAction(DeleteCategoryAction( + categoryId = params.categoryId + )) + + dismiss() + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/settings/ManageCategoryForUnassignedApps.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/ManageCategoryForUnassignedApps.kt new file mode 100644 index 0000000..b77b15d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/ManageCategoryForUnassignedApps.kt @@ -0,0 +1,61 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.settings + +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.Observer +import io.timelimit.android.data.Database +import io.timelimit.android.databinding.ManageCategoryForUnassignedAppsBinding +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.map +import io.timelimit.android.sync.actions.SetCategoryForUnassignedApps +import io.timelimit.android.ui.main.ActivityViewModel + +object ManageCategoryForUnassignedApps { + fun bind( + binding: ManageCategoryForUnassignedAppsBinding, + categoryId: String, + childId: String, + auth: ActivityViewModel, + database: Database, + lifecycleOwner: LifecycleOwner + ) { + val userEntry = database.user().getUserByIdLive(childId) + val isCurrentlyChosen = userEntry.map { it?.categoryForNotAssignedApps == categoryId }.ignoreUnchanged() + + isCurrentlyChosen.observe(lifecycleOwner, Observer { binding.isThisCategoryUsed = it }) + + binding.changeModeButton.setOnClickListener { + val chosen = isCurrentlyChosen.value + + if (chosen == true) { + auth.tryDispatchParentAction( + SetCategoryForUnassignedApps( + childId = childId, + categoryId = "" + ) + ) + } else if (chosen == false) { + auth.tryDispatchParentAction( + SetCategoryForUnassignedApps( + childId = childId, + categoryId = categoryId + ) + ) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/settings/ParentCategoryView.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/ParentCategoryView.kt new file mode 100644 index 0000000..42d0e43 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/ParentCategoryView.kt @@ -0,0 +1,53 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.settings + +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.Observer +import io.timelimit.android.data.Database +import io.timelimit.android.databinding.ManageParentCategoryBinding +import io.timelimit.android.ui.main.ActivityViewModel + +object ParentCategoryView { + fun bind( + binding: ManageParentCategoryBinding, + auth: ActivityViewModel, + lifecycleOwner: LifecycleOwner, + categoryId: String, + childId: String, + database: Database, + fragmentManager: FragmentManager + ) { + database.category().getCategoriesByChildId(childId).observe(lifecycleOwner, Observer { categories -> + val ownCategory = categories.find { it.id == categoryId } + val parentCategory = categories.find { it.id == ownCategory?.parentCategoryId } + val hasSubCategories = categories.find { it.parentCategoryId == categoryId } != null + + binding.parentCategoryTitle = parentCategory?.title + binding.isParentCategory = hasSubCategories + }) + + binding.selectParentButton.setOnClickListener { + if (auth.requestAuthenticationOrReturnTrue()) { + SelectParentCategoryDialogFragment.newInstance( + childId = childId, + categoryId = categoryId + ).show(fragmentManager) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/settings/RenameCategoryDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/RenameCategoryDialogFragment.kt new file mode 100644 index 0000000..7dbc2c8 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/RenameCategoryDialogFragment.kt @@ -0,0 +1,107 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.settings + +import android.os.Bundle +import android.view.View +import android.widget.Toast +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.Category +import io.timelimit.android.data.model.UserType +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.UpdateCategoryTitleAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.category.ManageCategoryFragmentArgs +import io.timelimit.android.ui.util.EditTextBottomSheetDialog + +class RenameCategoryDialogFragment: EditTextBottomSheetDialog() { + companion object { + private const val TAG = "RenameCategoryDialogFragment" + + fun newInstance(args: ManageCategoryFragmentArgs) = RenameCategoryDialogFragment().apply { + arguments = args.toBundle() + } + } + + private val params: ManageCategoryFragmentArgs by lazy { ManageCategoryFragmentArgs.fromBundle(arguments!!) } + private val appLogic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + + val categoryEntry: LiveData by lazy { + appLogic.database.category().getCategoryByChildIdAndId( + categoryId = params.categoryId, + childId = params.childId + ) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + categoryEntry.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + binding.title = getString(R.string.category_settings_rename) + + if (savedInstanceState == null) { + runAsync { + categoryEntry.waitForNullableValue()?.let { entry -> + binding.editText.setText(entry.title) + didInitField() + } + } + } + } + + override fun go() { + val newTitle = binding.editText.text.toString() + + if (newTitle.isBlank()) { + Toast.makeText(context!!, R.string.category_settings_rename_empty, Toast.LENGTH_SHORT).show() + } else { + auth.tryDispatchParentAction( + UpdateCategoryTitleAction( + categoryId = params.categoryId, + newTitle = newTitle + ) + ) + } + + dismiss() + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/settings/SelectParentCategoryDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/SelectParentCategoryDialogFragment.kt new file mode 100644 index 0000000..3d2b332 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/SelectParentCategoryDialogFragment.kt @@ -0,0 +1,151 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.settings + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.CheckedTextView +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.R +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.Category +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.BottomSheetSelectionListBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.SetParentCategory +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder + +class SelectParentCategoryDialogFragment: BottomSheetDialogFragment() { + companion object { + private const val DIALOG_TAG = "SelectParentCategoryDialogFragment" + private const val CATEGORY_ID = "categoryId" + private const val CHILD_ID = "childId" + + fun newInstance(childId: String, categoryId: String) = SelectParentCategoryDialogFragment().apply { + arguments = Bundle().apply { + putString(CHILD_ID, childId) + putString(CATEGORY_ID, categoryId) + } + } + } + + val childId: String by lazy { arguments!!.getString(CHILD_ID) } + val categoryId: String by lazy { arguments!!.getString(CATEGORY_ID) } + + val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + val database: Database by lazy { logic.database } + val auth: ActivityViewModel by lazy { (activity as ActivityViewModelHolder).getActivityViewModel() } + + val childCategoryEntries: LiveData> by lazy { + database.category().getCategoriesByChildId(childId) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + childCategoryEntries.observe(this, Observer { categories -> + val ownCategory = categories.find { it.id == categoryId } + val hasSubCategories = categories.find { it.parentCategoryId == categoryId } != null + + if (ownCategory == null || hasSubCategories) { + dismissAllowingStateLoss() + } + }) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = BottomSheetSelectionListBinding.inflate(inflater, container, false) + + binding.title = getString(R.string.category_settings_parent_category_title) + + val list = binding.list + + childCategoryEntries.observe(this, Observer { categories -> + list.removeAllViews() + + val ownCategory = categories.find { it.id == categoryId } + val ownParentCategory = categories.find { it.id == ownCategory?.parentCategoryId } + + fun buildRow(): CheckedTextView = LayoutInflater.from(context!!).inflate( + android.R.layout.simple_list_item_single_choice, + list, + false + ) as CheckedTextView + + categories.forEach { category -> + if (category.id != categoryId) { + val row = buildRow() + + row.text = category.title + row.isChecked = category.id == ownCategory?.parentCategoryId + row.isEnabled = categories.find { it.id == category.parentCategoryId } == null + row.setOnClickListener { + if (!row.isChecked) { + auth.tryDispatchParentAction( + SetParentCategory( + categoryId = categoryId, + parentCategory = category.id + ) + ) + } + + dismiss() + } + + list.addView(row) + } + } + + buildRow().let { row -> + row.setText(R.string.category_settings_parent_category_none) + row.isChecked = ownParentCategory == null + + row.setOnClickListener { + if (!row.isChecked) { + auth.tryDispatchParentAction( + SetParentCategory( + categoryId = categoryId, + parentCategory = "" + ) + ) + } + + dismiss() + } + + list.addView(row) + } + }) + + return binding.root + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, DIALOG_TAG) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/Adapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/Adapter.kt new file mode 100644 index 0000000..f64bedf --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/Adapter.kt @@ -0,0 +1,152 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.timelimit_rules + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.R +import io.timelimit.android.data.model.TimeLimitRule +import io.timelimit.android.databinding.AddItemViewBinding +import io.timelimit.android.databinding.FragmentCategoryTimeLimitRuleItemBinding +import io.timelimit.android.databinding.TimeLimitRuleIntroductionBinding +import io.timelimit.android.util.JoinUtil +import io.timelimit.android.util.TimeTextUtil +import kotlin.properties.Delegates + +class Adapter: RecyclerView.Adapter() { + companion object { + private const val TYPE_ITEM = 1 + private const val TYPE_ADD = 2 + private const val TYPE_INTRO = 3 + } + + var data: List by Delegates.observable(emptyList()) { _, _, _ -> notifyDataSetChanged() } + var usedTimes: List? by Delegates.observable(null as List?) { _, _, _ -> notifyDataSetChanged() } + var handlers: Handlers? = null + + init { + setHasStableIds(true) + } + + private fun getItem(position: Int): TimeLimitRuleItem = data[position] + + override fun getItemId(position: Int): Long { + val item = getItem(position) + + return if (item is TimeLimitRuleRuleItem) { + item.rule.id.hashCode() + } else { + item.hashCode() + }.toLong() + } + + override fun getItemCount(): Int = data.size + + override fun getItemViewType(position: Int) = when (getItem(position)) { + AddTimeLimitRuleItem -> TYPE_ADD + is TimeLimitRuleRuleItem -> TYPE_ITEM + TimeLimitRuleIntroductionItem -> TYPE_INTRO + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) { + TYPE_ITEM -> { + ItemViewHolder( + FragmentCategoryTimeLimitRuleItemBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + } + TYPE_ADD -> { + ViewHolder( + AddItemViewBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ).apply { + label = parent.context.getString(R.string.category_time_limit_rule_dialog_new) + root.setOnClickListener { handlers?.onAddTimeLimitRuleClicked() } + }.root + ) + } + TYPE_INTRO -> { + ViewHolder( + TimeLimitRuleIntroductionBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ).apply { + okButton.setOnClickListener { + handlers?.onConfirmIntroduction() + } + }.root + ) + } + else -> throw IllegalStateException() + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val item = getItem(position) + + when (item) { + AddTimeLimitRuleItem -> { + // nothing to do + } + is TimeLimitRuleIntroductionItem -> { + // nothing to do + } + is TimeLimitRuleRuleItem -> { + val rule = item.rule + val binding = (holder as ItemViewHolder).view + val dayNames = binding.root.resources.getStringArray(R.array.days_of_week_array) + val usedTime = usedTimes?.mapIndexed { index, value -> + if (rule.dayMask.toInt() and (1 shl index) != 0) { + value + } else { + 0 + } + }?.sum()?.toInt() ?: 0 + + binding.maxTimeString = TimeTextUtil.time(rule.maximumTimeInMillis, binding.root.context) + binding.usageAsText = TimeTextUtil.used(usedTime, binding.root.context) + binding.usageProgressInPercent = if (rule.maximumTimeInMillis > 0) + (usedTime * 100 / rule.maximumTimeInMillis) + else + 100 + binding.daysString = JoinUtil.join( + dayNames.filterIndexed { index, _ -> (rule.dayMask.toInt() and (1 shl index)) != 0 }, + binding.root.context + ) + binding.appliesToExtraTime = rule.applyToExtraTimeUsage + binding.card.setOnClickListener { handlers?.onTimeLimitRuleClicked(rule) } + + binding.executePendingBindings() + } + }.let { /* require handling all paths */ } + } +} + +open class ViewHolder(view: View): RecyclerView.ViewHolder(view) +class ItemViewHolder(val view: FragmentCategoryTimeLimitRuleItemBinding): ViewHolder(view.root) + +interface Handlers { + fun onTimeLimitRuleClicked(rule: TimeLimitRule) + fun onAddTimeLimitRuleClicked() + fun onConfirmIntroduction() +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/CategoryTimeLimitRulesFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/CategoryTimeLimitRulesFragment.kt new file mode 100644 index 0000000..3772931 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/CategoryTimeLimitRulesFragment.kt @@ -0,0 +1,160 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.timelimit_rules + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import androidx.recyclerview.widget.LinearLayoutManager +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.data.Database +import io.timelimit.android.data.extensions.getDateLive +import io.timelimit.android.data.model.HintsToShow +import io.timelimit.android.data.model.TimeLimitRule +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.CreateTimeLimitRuleAction +import io.timelimit.android.sync.actions.UpdateTimeLimitRuleAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.category.ManageCategoryFragmentArgs +import io.timelimit.android.ui.manage.category.timelimit_rules.edit.EditTimeLimitRuleDialogFragment +import io.timelimit.android.ui.manage.category.timelimit_rules.edit.EditTimeLimitRuleDialogFragmentListener +import kotlinx.android.synthetic.main.fragment_category_time_limit_rules.* + +class CategoryTimeLimitRulesFragment : Fragment(), EditTimeLimitRuleDialogFragmentListener { + companion object { + fun newInstance(params: ManageCategoryFragmentArgs): CategoryTimeLimitRulesFragment { + val result = CategoryTimeLimitRulesFragment() + result.arguments = params.toBundle() + return result + } + } + + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val params: ManageCategoryFragmentArgs by lazy { ManageCategoryFragmentArgs.fromBundle(arguments!!) } + private val database: Database by lazy { logic.database } + private val rules: LiveData> by lazy { database.timeLimitRules().getTimeLimitRulesByCategory(params.categoryId) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_category_time_limit_rules, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + val adapter = Adapter() + + recycler.layoutManager = LinearLayoutManager(context!!) + recycler.adapter = adapter + + val userDate = database.user().getUserByIdLive(params.childId).getDateLive(logic.realTimeLogic) + + val usedTimeItems = userDate.switchMap { + date -> + + database.usedTimes().getUsedTimesOfWeek( + categoryId = params.categoryId, + firstDayOfWeekAsEpochDay = date.dayOfEpoch - date.dayOfWeek + ) + } + + val hasHiddenIntro = database.config().wereHintsShown(HintsToShow.TIME_LIMIT_RULE_INTRODUCTION) + + rules.map { rules -> + rules.sortedBy { it.dayMask }.map { TimeLimitRuleRuleItem(it) } + }.switchMap { + val baseList = it + listOf(AddTimeLimitRuleItem) + + hasHiddenIntro.map { hasHiddenIntro -> + if (hasHiddenIntro) { + baseList + } else { + listOf(TimeLimitRuleIntroductionItem) + baseList + } + } + }.observe(this, Observer { + adapter.data = it + }) + + usedTimeItems.observe(this, Observer { + usedTimes -> + + adapter.usedTimes = (0..6).map { usedTimes[it]?.usedMillis ?: 0 } } + ) + + adapter.handlers = object: Handlers { + override fun onTimeLimitRuleClicked(rule: TimeLimitRule) { + if (auth.requestAuthenticationOrReturnTrue()) { + EditTimeLimitRuleDialogFragment.newInstance(rule, this@CategoryTimeLimitRulesFragment).show(fragmentManager!!) + } + } + + override fun onAddTimeLimitRuleClicked() { + if (auth.requestAuthenticationOrReturnTrue()) { + EditTimeLimitRuleDialogFragment.newInstance(params.categoryId, this@CategoryTimeLimitRulesFragment).show(fragmentManager!!) + } + } + + override fun onConfirmIntroduction() { + Threads.database.execute { + database.config().setHintsShownSync(HintsToShow.TIME_LIMIT_RULE_INTRODUCTION) + } + } + } + } + + override fun notifyRuleCreated() { + Snackbar.make(view!!, R.string.category_time_limit_rules_snackbar_created, Snackbar.LENGTH_SHORT) + .show() + } + + override fun notifyRuleDeleted(oldRule: TimeLimitRule) { + Snackbar.make(view!!, R.string.category_time_limit_rules_snackbar_deleted, Snackbar.LENGTH_SHORT) + .setAction(R.string.generic_undo) { + auth.tryDispatchParentAction( + CreateTimeLimitRuleAction( + rule = oldRule + ) + ) + } + .show() + } + + override fun notifyRuleUpdated(oldRule: TimeLimitRule, newRule: TimeLimitRule) { + Snackbar.make(view!!, R.string.category_time_limit_rules_snackbar_updated, Snackbar.LENGTH_SHORT) + .setAction(R.string.generic_undo) { + auth.tryDispatchParentAction( + UpdateTimeLimitRuleAction( + ruleId = oldRule.id, + applyToExtraTimeUsage = oldRule.applyToExtraTimeUsage, + maximumTimeInMillis = oldRule.maximumTimeInMillis, + dayMask = oldRule.dayMask + ) + ) + } + .show() + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/TimeLimitRuleItem.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/TimeLimitRuleItem.kt new file mode 100644 index 0000000..7efd719 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/TimeLimitRuleItem.kt @@ -0,0 +1,23 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.timelimit_rules + +import io.timelimit.android.data.model.TimeLimitRule + +sealed class TimeLimitRuleItem +object AddTimeLimitRuleItem: TimeLimitRuleItem() +object TimeLimitRuleIntroductionItem: TimeLimitRuleItem() +data class TimeLimitRuleRuleItem(val rule: TimeLimitRule): TimeLimitRuleItem() \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/edit/EditTimeLimitRuleDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/edit/EditTimeLimitRuleDialogFragment.kt new file mode 100644 index 0000000..ab7693b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/edit/EditTimeLimitRuleDialogFragment.kt @@ -0,0 +1,282 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.timelimit_rules.edit + +import android.app.Dialog +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.Observer +import com.google.android.material.R +import com.google.android.material.bottomsheet.BottomSheetBehavior +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.model.TimeLimitRule +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.FragmentEditTimeLimitRuleDialogBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.CreateTimeLimitRuleAction +import io.timelimit.android.sync.actions.DeleteTimeLimitRuleAction +import io.timelimit.android.sync.actions.UpdateTimeLimitRuleAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.view.SelectDayViewHandlers +import io.timelimit.android.ui.view.SelectTimeSpanViewListener +import java.nio.ByteBuffer +import java.util.* + + +class EditTimeLimitRuleDialogFragment : BottomSheetDialogFragment() { + companion object { + private const val PARAM_EXISTING_RULE = "a" + private const val PARAM_CATEGORY_ID = "b" + private const val DIALOG_TAG = "t" + private const val STATE_RULE = "c" + + fun newInstance(existingRule: TimeLimitRule, listener: Fragment) = EditTimeLimitRuleDialogFragment() + .apply { + arguments = Bundle().apply { + putParcelable(PARAM_EXISTING_RULE, existingRule) + } + + setTargetFragment(listener, 0) + } + + fun newInstance(categoryId: String, listener: Fragment) = EditTimeLimitRuleDialogFragment() + .apply { + arguments = Bundle().apply { + putString(PARAM_CATEGORY_ID, categoryId) + } + + setTargetFragment(listener, 0) + } + } + + var existingRule: TimeLimitRule? = null + var savedNewRule: TimeLimitRule? = null + + private val categoryId: String by lazy { + if (existingRule != null) { + existingRule!!.categoryId + } else { + arguments!!.getString(PARAM_CATEGORY_ID)!! + } + } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + existingRule = savedInstanceState?.getParcelable(PARAM_EXISTING_RULE) + ?: arguments?.getParcelable(PARAM_EXISTING_RULE) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val view = FragmentEditTimeLimitRuleDialogBinding.inflate(layoutInflater, container, false) + val listener = targetFragment as EditTimeLimitRuleDialogFragmentListener + var newRule: TimeLimitRule + + auth.authenticatedUser.observe(this, Observer { + if (it == null || it.second.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + if (existingRule == null) { + view.isNewRule = true + + newRule = TimeLimitRule( + id = IdGenerator.generateId(), + categoryId = categoryId, + applyToExtraTimeUsage = false, + dayMask = 0, + maximumTimeInMillis = 1000 * 60 * 60 * 5 / 2 // 2,5 (5/2) hours + ) + } else { + view.isNewRule = false + + newRule = existingRule!! + } + + run { + val restoredRule = savedInstanceState?.getParcelable(STATE_RULE) + + if (restoredRule != null) { + newRule = restoredRule + } + } + + fun bindRule() { + savedNewRule = newRule + + view.daySelection.selectedDays = BitSet.valueOf( + ByteBuffer.allocate(1).put(newRule.dayMask).apply { + position(0) + } + ) + view.applyToExtraTime = newRule.applyToExtraTimeUsage + view.timeSpan.timeInMillis = newRule.maximumTimeInMillis.toLong() + + val affectedDays = Math.max(0, (0..6).map { (newRule.dayMask.toInt() shr it) and 1 }.sum()) + view.timeSpan.maxDays = affectedDays - 1 + view.affectsMultipleDays = affectedDays >= 2 + } + + bindRule() + view.daySelection.handlers = object: SelectDayViewHandlers { + override fun updateDayChecked(day: Int) { + newRule = newRule.copy( + dayMask = (newRule.dayMask.toInt() xor (1 shl day)).toByte() + ) + + bindRule() + } + } + + view.handlers = object: Handlers { + override fun updateApplyToExtraTime(apply: Boolean) { + newRule = newRule.copy( + applyToExtraTimeUsage = apply + ) + + bindRule() + } + + override fun onSaveRule() { + if (existingRule != null) { + if (existingRule != newRule) { + if (!auth.tryDispatchParentAction( + UpdateTimeLimitRuleAction( + ruleId = newRule.id, + maximumTimeInMillis = newRule.maximumTimeInMillis, + dayMask = newRule.dayMask, + applyToExtraTimeUsage = newRule.applyToExtraTimeUsage + ) + )) { + return + } + } + + listener.notifyRuleUpdated(existingRule!!, newRule) + } else { + if (!auth.tryDispatchParentAction( + CreateTimeLimitRuleAction( + rule = newRule + ) + )) { + return + } + + listener.notifyRuleCreated() + } + + dismissAllowingStateLoss() + } + + override fun onDeleteRule() { + if (!auth.tryDispatchParentAction( + DeleteTimeLimitRuleAction( + ruleId = existingRule!!.id + ) + )) { + return + } + + listener.notifyRuleDeleted(existingRule!!) + + dismissAllowingStateLoss() + } + } + + view.timeSpan.listener = object: SelectTimeSpanViewListener { + override fun onTimeSpanChanged(newTimeInMillis: Long) { + if (newTimeInMillis.toInt() != newRule.maximumTimeInMillis) { + newRule = newRule.copy(maximumTimeInMillis = newTimeInMillis.toInt()) + + bindRule() + } + } + } + + if (existingRule != null) { + DefaultAppLogic.with(context!!).database.timeLimitRules() + .getTimeLimitRuleByIdLive(existingRule!!.id).observe(this, Observer { + if (it == null) { + // rule was deleted + dismissAllowingStateLoss() + } else { + if (it != existingRule) { + existingRule = it + newRule = it + + bindRule() + } + } + }) + } + + return view.root + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val dialog = super.onCreateDialog(savedInstanceState) + + // from https://stackoverflow.com/a/43602359 + dialog.setOnShowListener { + BottomSheetBehavior.from( + dialog.findViewById(R.id.design_bottom_sheet) + ).setState(BottomSheetBehavior.STATE_EXPANDED) + } + + return dialog + } + + fun show(manager: FragmentManager) { + showSafe(manager, DIALOG_TAG) + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + + val rule = savedNewRule + + if (rule != null) { + outState.putParcelable(STATE_RULE, rule) + } + + existingRule.let { existingRule -> + if (existingRule != null) { + outState.putParcelable(PARAM_EXISTING_RULE, existingRule) + } + } + } +} + +interface Handlers { + fun updateApplyToExtraTime(apply: Boolean) + fun onSaveRule() + fun onDeleteRule() +} + +interface EditTimeLimitRuleDialogFragmentListener { + fun notifyRuleCreated() + fun notifyRuleDeleted(oldRule: TimeLimitRule) + fun notifyRuleUpdated(oldRule: TimeLimitRule, newRule: TimeLimitRule) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/usagehistory/UsageHistoryAdapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/usagehistory/UsageHistoryAdapter.kt new file mode 100644 index 0000000..8963d90 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/usagehistory/UsageHistoryAdapter.kt @@ -0,0 +1,68 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.usagehistory + +import android.text.format.DateFormat +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.paging.PagedListAdapter +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.data.model.UsedTimeItem +import io.timelimit.android.databinding.FragmentUsageHistoryItemBinding +import io.timelimit.android.util.TimeTextUtil +import org.threeten.bp.LocalDate +import org.threeten.bp.ZoneOffset +import java.util.* + +class UsageHistoryAdapter: PagedListAdapter(diffCallback) { + companion object { + private val diffCallback = object: DiffUtil.ItemCallback() { + override fun areContentsTheSame(oldItem: UsedTimeItem, newItem: UsedTimeItem) = oldItem == newItem + override fun areItemsTheSame(oldItem: UsedTimeItem, newItem: UsedTimeItem) = + (oldItem.dayOfEpoch == newItem.dayOfEpoch) && (oldItem.categoryId == newItem.categoryId) + } + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = UsageHistoryViewHolder( + FragmentUsageHistoryItemBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + + override fun onBindViewHolder(holder: UsageHistoryViewHolder, position: Int) { + val item = getItem(position) + val binding = holder.binding + val context = binding.root.context + + if (item == null) { + binding.date = "" + binding.usedTime = "" + } else { + val date = LocalDate.ofEpochDay(item.dayOfEpoch.toLong()) + + binding.date = DateFormat.getDateFormat(context).apply { + timeZone = TimeZone.getTimeZone("UTC") + }.format(Date(date.atStartOfDay().toEpochSecond(ZoneOffset.UTC) * 1000L)) + + binding.usedTime = TimeTextUtil.used(item.usedMillis.toInt(), context) + } + } +} + +class UsageHistoryViewHolder(val binding: FragmentUsageHistoryItemBinding): RecyclerView.ViewHolder(binding.root) diff --git a/app/src/main/java/io/timelimit/android/ui/manage/category/usagehistory/UsageHistoryFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/category/usagehistory/UsageHistoryFragment.kt new file mode 100644 index 0000000..b23e7cf --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/usagehistory/UsageHistoryFragment.kt @@ -0,0 +1,59 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.category.usagehistory + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.paging.LivePagedListBuilder +import androidx.recyclerview.widget.LinearLayoutManager +import io.timelimit.android.databinding.FragmentUsageHistoryBinding +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.manage.category.ManageCategoryFragmentArgs + +class UsageHistoryFragment : Fragment() { + companion object { + fun newInstance(params: ManageCategoryFragmentArgs) = UsageHistoryFragment().apply { + arguments = params.toBundle() + } + } + + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentUsageHistoryBinding.inflate(inflater, container, false) + val params = ManageCategoryFragmentArgs.fromBundle(arguments!!) + val database = DefaultAppLogic.with(context!!).database + val adapter = UsageHistoryAdapter() + + LivePagedListBuilder( + database.usedTimes().getUsedTimesByCategoryId(params.categoryId), + 10 + ) + .build() + .observe(this, Observer { + binding.isEmpty = it.isEmpty() + adapter.submitList(it) + }) + + binding.recycler.adapter = adapter + binding.recycler.layoutManager = LinearLayoutManager(context) + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/ManageChildFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/ManageChildFragment.kt new file mode 100644 index 0000000..2ac4209 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/ManageChildFragment.kt @@ -0,0 +1,113 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import androidx.navigation.Navigation +import androidx.viewpager.widget.ViewPager +import io.timelimit.android.R +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.main.AuthenticationFab +import io.timelimit.android.ui.main.FragmentWithCustomTitle +import kotlinx.android.synthetic.main.fragment_manage_child.* + +class ManageChildFragment : Fragment(), FragmentWithCustomTitle { + private val params: ManageChildFragmentArgs by lazy { ManageChildFragmentArgs.fromBundle(arguments!!) } + private val adapter: PagerAdapter by lazy { PagerAdapter(childFragmentManager, params) } + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val child: LiveData by lazy { logic.database.user().getUserByIdLive(params.childId) } + private val activity: ActivityViewModelHolder by lazy { getActivity() as ActivityViewModelHolder } + private var wereViewsCreated = false + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_manage_child, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + AuthenticationFab.manageAuthenticationFab( + fab = fab, + fragment = this, + doesSupportAuth = liveDataFromValue(true), + authenticatedUser = activity.getActivityViewModel().authenticatedUser, + shouldHighlight = activity.getActivityViewModel().shouldHighlightAuthenticationButton + ) + + fab.setOnClickListener { activity.showAuthenticationScreen() } + + val navigation = Navigation.findNavController(view) + + // leave if the child does not exist + if (!wereViewsCreated) { + wereViewsCreated = true + + child.observe(this, Observer { + if (it == null || it.type != UserType.Child) { + navigation.popBackStack(R.id.overviewFragment, false) + } + }) + } + + pager.adapter = adapter + + bottom_navigation_view.setOnNavigationItemSelectedListener { + menuItem -> + + pager.currentItem = when (menuItem.itemId) { + R.id.manage_child_tab_categories -> 0 + R.id.manage_child_tab_apps -> 1 + R.id.manage_child_tab_manage -> 2 + else -> 0 + } + + true + } + + pager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener { + override fun onPageScrollStateChanged(state: Int) { + // ignore + } + + override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { + // ignore + } + + override fun onPageSelected(position: Int) { + bottom_navigation_view.selectedItemId = when(position) { + 0 -> R.id.manage_child_tab_categories + 1 -> R.id.manage_child_tab_apps + 2 -> R.id.manage_child_tab_manage + else -> throw IllegalStateException() + } + } + }) + } + + override fun getCustomTitle() = child.map { it?.name } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/PagerAdapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/PagerAdapter.kt new file mode 100644 index 0000000..c6bf673 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/PagerAdapter.kt @@ -0,0 +1,33 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child + +import androidx.fragment.app.FragmentManager +import androidx.fragment.app.FragmentStatePagerAdapter +import io.timelimit.android.ui.manage.child.advanced.ManageChildAdvancedFragment +import io.timelimit.android.ui.manage.child.apps.ChildAppsFragment +import io.timelimit.android.ui.manage.child.category.ManageChildCategoriesFragment + +class PagerAdapter(fragmentManager: FragmentManager, private val params: ManageChildFragmentArgs): FragmentStatePagerAdapter(fragmentManager) { + override fun getCount() = 3 + + override fun getItem(position: Int) = when(position) { + 0 -> ManageChildCategoriesFragment.newInstance(params) + 1 -> ChildAppsFragment.newInstance(params) + 2 -> ManageChildAdvancedFragment.newInstance(params) + else -> throw IllegalStateException() + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/DeleteChildDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/DeleteChildDialogFragment.kt new file mode 100644 index 0000000..19cec3b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/DeleteChildDialogFragment.kt @@ -0,0 +1,89 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced + +import android.os.Bundle +import android.view.View +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.RemoveUserAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.util.ConfirmDeleteDialogFragment + +class DeleteChildDialogFragment: ConfirmDeleteDialogFragment() { + companion object { + private const val DIALOG_TAG = "DeleteChildDialogFragment" + private const val CHILD_ID = "childId" + + fun newInstance(childId: String) = DeleteChildDialogFragment().apply { + arguments = Bundle().apply { + putString(CHILD_ID, childId) + } + } + } + + val auth: ActivityViewModel by lazy { + (activity as ActivityViewModelHolder).getActivityViewModel() + } + val childId: String by lazy { arguments!!.getString(CHILD_ID) } + val userEntry: LiveData by lazy { + DefaultAppLogic.with(context!!).database.user().getChildUserByIdLive(childId) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + userEntry.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + userEntry.observe(this, Observer { + binding.text = getString(R.string.delete_child_text, it?.name) + }) + } + + override fun onConfirmDeletion() { + auth.tryDispatchParentAction( + RemoveUserAction( + userId = childId, + authentication = null + ) + ) + + dismiss() + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, DIALOG_TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/ManageChildAdvancedFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/ManageChildAdvancedFragment.kt new file mode 100644 index 0000000..aa8058c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/ManageChildAdvancedFragment.kt @@ -0,0 +1,185 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.CheckBox +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.data.model.User +import io.timelimit.android.databinding.FragmentManageChildAdvancedBinding +import io.timelimit.android.livedata.liveDataFromFunction +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.mergeLiveData +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.UpdateCategoryTemporarilyBlockedAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.child.ManageChildFragmentArgs +import io.timelimit.android.ui.manage.child.advanced.managedisabletimelimits.ManageDisableTimelimitsViewHelper +import io.timelimit.android.ui.manage.child.advanced.password.ManageChildPassword +import io.timelimit.android.ui.manage.child.advanced.timezone.SetChildTimezoneDialogFragment +import io.timelimit.android.ui.manage.child.primarydevice.PrimaryDeviceView +import io.timelimit.android.ui.payment.RequiresPurchaseDialogFragment +import java.util.* + +class ManageChildAdvancedFragment : Fragment() { + companion object { + private const val LOG_TAG = "ManageChildAdvanced" + + fun newInstance(params: ManageChildFragmentArgs) = ManageChildAdvancedFragment().apply { + arguments = params.toBundle() + } + } + + private val params: ManageChildFragmentArgs by lazy { ManageChildFragmentArgs.fromBundle(arguments!!) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val childEntry: LiveData by lazy { logic.database.user().getChildUserByIdLive(params.childId) } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentManageChildAdvancedBinding.inflate(layoutInflater, container, false) + + run { + // blocked categories + + val categoriesLive = logic.database.category().getCategoriesByChildId(params.childId) + + mergeLiveData(categoriesLive, logic.fullVersion.shouldProvideFullVersionFunctions).observe(this, Observer { + (categories, hasFullVersion) -> + + binding.blockedCategoriesCheckboxContainer.removeAllViews() + + categories?.forEach { + category -> + + val checkbox = CheckBox(context) + + checkbox.isChecked = category.temporarilyBlocked + checkbox.text = category.title + + checkbox.setOnCheckedChangeListener { _, isChecked -> + if (isChecked != category.temporarilyBlocked) { + if (isChecked) { + if (hasFullVersion != true) { + checkbox.isChecked = false + + RequiresPurchaseDialogFragment().show(fragmentManager!!) + + return@setOnCheckedChangeListener + } + } + + if (!auth.tryDispatchParentAction( + UpdateCategoryTemporarilyBlockedAction( + categoryId = category.id, + blocked = !category.temporarilyBlocked + ) + )) { + checkbox.isChecked = category.temporarilyBlocked + } + } + } + + binding.blockedCategoriesCheckboxContainer.addView(checkbox) + } + }) + } + + run { + // disable time limits + + mergeLiveData(childEntry, logic.fullVersion.shouldProvideFullVersionFunctions).observe(this, Observer { + (child, hasFullVersion) -> + + if (child != null) { + binding.disableTimeLimits.handlers = ManageDisableTimelimitsViewHelper.createHandlers( + childId = params.childId, + childTimezone = child.timeZone, + activity = activity!!, + hasFullVersion = hasFullVersion == true + ) + + binding.disableTimeLimits.userName = child.name + } + }) + + mergeLiveData(childEntry, liveDataFromFunction { logic.realTimeLogic.getCurrentTimeInMillis() }).map { + (child, time) -> + + if (time == null || child == null) { + null + } else { + ManageDisableTimelimitsViewHelper.getDisabledUntilString(child, time, context!!) + } + }.observe(this, Observer { + binding.disableTimeLimits.disableTimeLimitsUntilString = it + }) + } + + run { + // timezone + childEntry.observe(this, Observer { + binding.timezone = TimeZone.getTimeZone(it?.timeZone ?: "").displayName + }) + + binding.changeTimezoneButton.setOnClickListener { + if (auth.requestAuthenticationOrReturnTrue()) { + SetChildTimezoneDialogFragment.newInstance( + childId = params.childId + ).show(fragmentManager!!) + } + } + } + + binding.renameChildButton.setOnClickListener { + if (auth.requestAuthenticationOrReturnTrue()) { + UpdateChildNameDialogFragment.newInstance(params.childId).show(fragmentManager!!) + } + } + + binding.deleteUserButton.setOnClickListener { + if (auth.requestAuthenticationOrReturnTrue()) { + DeleteChildDialogFragment.newInstance(params.childId).show(fragmentManager!!) + } + } + + PrimaryDeviceView.bind( + view = binding.primaryDeviceView, + fragmentManager = fragmentManager!!, + childId = params.childId, + lifecycleOwner = this, + logic = logic, + auth = auth + ) + + ManageChildPassword.bind( + view = binding.password, + childId = params.childId, + childEntry = childEntry, + lifecycleOwner = this, + auth = auth, + fragmentManager = fragmentManager!! + ) + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/UpdateChildNameDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/UpdateChildNameDialogFragment.kt new file mode 100644 index 0000000..5d5ced9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/UpdateChildNameDialogFragment.kt @@ -0,0 +1,109 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced + +import android.os.Bundle +import android.view.View +import android.widget.Toast +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.RenameChildAction +import io.timelimit.android.sync.actions.UpdateDeviceNameAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.util.EditTextBottomSheetDialog + +class UpdateChildNameDialogFragment: EditTextBottomSheetDialog() { + companion object { + private const val TAG = "UpdateChildNameDialogFragment" + private const val EXTRA_USER_ID = "userId" + + fun newInstance(userId: String) = UpdateChildNameDialogFragment().apply { + arguments = Bundle().apply { + putString(EXTRA_USER_ID, userId) + } + } + } + + val userId: String by lazy { arguments!!.getString(EXTRA_USER_ID) } + val auth: ActivityViewModel by lazy { + (activity as ActivityViewModelHolder).getActivityViewModel() + } + val userEntry: LiveData by lazy { + DefaultAppLogic.with(context!!).database.user().getChildUserByIdLive(userId) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + userEntry.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + if (savedInstanceState == null) { + runAsync { + userEntry.waitForNullableValue()?.let { userEntry -> + binding.editText.setText(userEntry.name) + didInitField() + } + } + } + + binding.title = getString(R.string.rename_child_title) + } + + override fun go() { + val newDeviceTitle = binding.editText.text.toString() + + if (newDeviceTitle.isBlank()) { + dismiss() + } else { + if ( + auth.tryDispatchParentAction( + RenameChildAction( + childId = userId, + newName = newDeviceTitle + ) + ) + ) { + dismiss() + } + } + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/DisableTimelimitsUntilDateDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/DisableTimelimitsUntilDateDialogFragment.kt new file mode 100644 index 0000000..0a9c7b7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/DisableTimelimitsUntilDateDialogFragment.kt @@ -0,0 +1,136 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced.managedisabletimelimits + +import android.app.Dialog +import android.os.Bundle +import android.widget.DatePicker +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.User +import io.timelimit.android.date.DateInTimezone +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.logic.RealTime +import io.timelimit.android.sync.actions.SetUserDisableLimitsUntilAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import org.threeten.bp.LocalDate +import org.threeten.bp.ZoneId +import java.util.* + +class DisableTimelimitsUntilDateDialogFragment: DialogFragment() { + companion object { + fun newInstance(childId: String) = DisableTimelimitsUntilDateDialogFragment().apply { + arguments = buildArguments(childId) + } + + fun buildArguments(childId: String) = Bundle().apply { + putString(CHILD_ID, childId) + } + + private const val CHILD_ID = "a" + private const val DIALOG_TAG = "v" + } + + private val childId: String by lazy { arguments!!.getString(CHILD_ID) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val logic: AppLogic by lazy { DefaultAppLogic.with(activity!!) } + private val childEntry: LiveData by lazy { logic.database.user().getChildUserByIdLive(childId) } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + childEntry.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + + auth.authenticatedUser.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + private fun getCurrentTime() = RealTime.newInstance().apply { + logic.realTimeLogic.getRealTime(this) + }.timeInMillis + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val view = DatePicker(context) + view.id = R.id.disable_time_limits + + if (savedInstanceState == null) { + runAsync { + val child = childEntry.waitForNullableValue() + + if (child != null) { + val dayOfEpoch = DateInTimezone.newInstance(getCurrentTime(), TimeZone.getTimeZone(child.timeZone)).dayOfEpoch.toLong() + + val nextDayStart = LocalDate.ofEpochDay(dayOfEpoch) + .plusDays(1) + .atStartOfDay(ZoneId.of(child.timeZone)) + .toEpochSecond() * 1000 + + view.minDate = nextDayStart + } + } + } + + return AlertDialog.Builder(context!!, theme) + .setTitle(R.string.manage_disable_time_limits_dialog_until) + .setView(view) + .setPositiveButton(R.string.generic_ok) { + _, _ -> + + val child = childEntry.value + val now = getCurrentTime() + + if (child != null) { + val timestamp = LocalDate.of(view.year, view.month + 1, view.dayOfMonth) + .atStartOfDay(ZoneId.of(child.timeZone)) + .toEpochSecond() * 1000 + + if (timestamp <= now) { + Toast.makeText(context!!, R.string.manage_disable_time_limits_toast_time_in_past, Toast.LENGTH_SHORT).show() + } else { + auth.tryDispatchParentAction( + SetUserDisableLimitsUntilAction( + childId = childId, + timestamp = timestamp + ) + ) + } + } + } + .setNegativeButton(R.string.generic_cancel, null) + .create() + } + + fun show(manager: FragmentManager) { + showSafe(manager, DIALOG_TAG) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/DisableTimelimitsUntilTimeDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/DisableTimelimitsUntilTimeDialogFragment.kt new file mode 100644 index 0000000..a5e8ade --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/DisableTimelimitsUntilTimeDialogFragment.kt @@ -0,0 +1,140 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced.managedisabletimelimits + +import android.app.Dialog +import android.os.Bundle +import android.widget.TimePicker +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.User +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.logic.RealTime +import io.timelimit.android.sync.actions.SetUserDisableLimitsUntilAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import org.threeten.bp.Instant +import org.threeten.bp.LocalDateTime +import org.threeten.bp.ZoneId + +class DisableTimelimitsUntilTimeDialogFragment: DialogFragment() { + companion object { + fun newInstance(childId: String) = DisableTimelimitsUntilTimeDialogFragment().apply { + arguments = buildArguments(childId) + } + + fun buildArguments(childId: String) = Bundle().apply { + putString(CHILD_ID, childId) + } + + private const val CHILD_ID = "a" + private const val DIALOG_TAG = "r" + } + + private val childId: String by lazy { arguments!!.getString(CHILD_ID) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val logic: AppLogic by lazy { DefaultAppLogic.with(activity!!) } + private val childEntry: LiveData by lazy { logic.database.user().getChildUserByIdLive(childId) } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + childEntry.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + + auth.authenticatedUser.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + private fun getCurrentTime() = RealTime.newInstance().apply { + logic.realTimeLogic.getRealTime(this) + }.timeInMillis + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val view = TimePicker(context) + view.id = R.id.disable_time_limits + + if (savedInstanceState == null) { + runAsync { + val child = childEntry.waitForNullableValue() + + if (child != null) { + val now = LocalDateTime.ofInstant( + Instant.ofEpochMilli(getCurrentTime()), + ZoneId.of(child.timeZone) + ).toLocalTime().plusMinutes(30) + + view.currentHour = now.hour + view.currentMinute = now.minute + } + } + } + + return AlertDialog.Builder(context!!, theme) + .setTitle(R.string.manage_disable_time_limits_dialog_until) + .setView(view) + .setPositiveButton(R.string.generic_ok) { + _, _ -> + + val child = childEntry.value + val now = getCurrentTime() + + if (child != null) { + val timestamp = LocalDateTime.ofInstant( + Instant.ofEpochMilli(now), + ZoneId.of(child.timeZone) + ) + .toLocalDate() + .atStartOfDay(ZoneId.of(child.timeZone)) + .plusHours(view.currentHour.toLong()) + .plusMinutes(view.currentMinute.toLong()) + .toEpochSecond() * 1000 + + if (timestamp <= now) { + Toast.makeText(context!!, R.string.manage_disable_time_limits_toast_time_in_past, Toast.LENGTH_SHORT).show() + } else { + auth.tryDispatchParentAction( + SetUserDisableLimitsUntilAction( + childId = childId, + timestamp = timestamp + ) + ) + } + } + } + .setNegativeButton(R.string.generic_cancel, null) + .create() + } + + fun show(manager: FragmentManager) { + showSafe(manager, DIALOG_TAG) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/ManageDisableTimelimitsViewHelper.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/ManageDisableTimelimitsViewHelper.kt new file mode 100644 index 0000000..96c7fdf --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/ManageDisableTimelimitsViewHelper.kt @@ -0,0 +1,124 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced.managedisabletimelimits + +import android.content.Context +import android.text.format.DateUtils +import androidx.fragment.app.FragmentActivity +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.date.DateInTimezone +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.logic.RealTime +import io.timelimit.android.sync.actions.SetUserDisableLimitsUntilAction +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.payment.RequiresPurchaseDialogFragment +import io.timelimit.android.ui.view.ManageDisableTimelimitsViewHandlers +import org.threeten.bp.LocalDate +import org.threeten.bp.ZoneId +import java.util.* + +object ManageDisableTimelimitsViewHelper { + fun createHandlers(childId: String, childTimezone: String, activity: FragmentActivity, hasFullVersion: Boolean): ManageDisableTimelimitsViewHandlers { + val auth = getActivityViewModel(activity) + val logic = DefaultAppLogic.with(activity) + + fun getCurrentTime() = RealTime.newInstance().apply { + logic.realTimeLogic.getRealTime(this) + }.timeInMillis + + return object : ManageDisableTimelimitsViewHandlers { + override fun disableTimeLimitsForDuration(duration: Long) { + if (!hasFullVersion) { + RequiresPurchaseDialogFragment().show(activity.supportFragmentManager) + return + } + + auth.tryDispatchParentAction( + SetUserDisableLimitsUntilAction( + childId = childId, + timestamp = getCurrentTime() + duration + ) + ) + } + + override fun disableTimeLimitsForToday() { + if (!hasFullVersion) { + RequiresPurchaseDialogFragment().show(activity.supportFragmentManager) + return + } + + val dayOfEpoch = DateInTimezone.newInstance(getCurrentTime(), TimeZone.getTimeZone(childTimezone)).dayOfEpoch.toLong() + + val nextDayStart = LocalDate.ofEpochDay(dayOfEpoch) + .plusDays(1) + .atStartOfDay(ZoneId.of(childTimezone)) + .toEpochSecond() * 1000 + + auth.tryDispatchParentAction( + SetUserDisableLimitsUntilAction( + childId = childId, + timestamp = nextDayStart + ) + ) + } + + override fun disableTimeLimitsUntilSelectedDate() { + if (!hasFullVersion) { + RequiresPurchaseDialogFragment().show(activity.supportFragmentManager) + return + } + + if (auth.requestAuthenticationOrReturnTrue()) { + DisableTimelimitsUntilDateDialogFragment.newInstance(childId).show(activity.supportFragmentManager) + } + } + + override fun disableTimeLimitsUntilSelectedTimeOfToday() { + if (!hasFullVersion) { + RequiresPurchaseDialogFragment().show(activity.supportFragmentManager) + return + } + + if (auth.requestAuthenticationOrReturnTrue()) { + DisableTimelimitsUntilTimeDialogFragment.newInstance(childId).show(activity.supportFragmentManager) + } + } + + override fun enableTimeLimits() { + auth.tryDispatchParentAction( + SetUserDisableLimitsUntilAction( + childId = childId, + timestamp = 0 + ) + ) + } + } + } + + fun getDisabledUntilString(child: User?, currentTime: Long, context: Context): String? { + if (child == null || child.type != UserType.Child || child.disableLimitsUntil == 0L || child.disableLimitsUntil < currentTime) { + return null + } else { + return DateUtils.formatDateTime( + context, + child.disableLimitsUntil, + DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or + DateUtils.FORMAT_SHOW_YEAR or DateUtils.FORMAT_SHOW_WEEKDAY + ) + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/ManageChildPassword.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/ManageChildPassword.kt new file mode 100644 index 0000000..3de9b26 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/ManageChildPassword.kt @@ -0,0 +1,49 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced.password + +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.data.model.User +import io.timelimit.android.databinding.ManageChildPasswordBinding +import io.timelimit.android.ui.main.ActivityViewModel + +object ManageChildPassword { + fun bind( + view: ManageChildPasswordBinding, + lifecycleOwner: LifecycleOwner, + childId: String, + childEntry: LiveData, + auth: ActivityViewModel, + fragmentManager: FragmentManager + ) { + childEntry.observe(lifecycleOwner, Observer { + view.hasPassword = it?.password?.isNotEmpty() ?: false + }) + + view.setPasswordButton.setOnClickListener { + if (auth.requestAuthenticationOrReturnTrue()) { + SetChildPasswordDialogFragment.newInstance(childId).show(fragmentManager) + } + } + + view.changePasswordButton.setOnClickListener { + UpdateChildPasswordDialogFragment.newInstance(childId).show(fragmentManager) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/SetChildPasswordDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/SetChildPasswordDialogFragment.kt new file mode 100644 index 0000000..c63d8fd --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/SetChildPasswordDialogFragment.kt @@ -0,0 +1,93 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced.password + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.Observer +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.SetChildPasswordDialogFragmentBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.sync.actions.SetChildPasswordAction +import io.timelimit.android.sync.network.ParentPassword +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel + +class SetChildPasswordDialogFragment: BottomSheetDialogFragment() { + companion object { + private const val EXTRA_CHILD_ID = "childId" + private const val DIALOG_TAG = "scpdf" + + fun newInstance(childId: String) = SetChildPasswordDialogFragment().apply { + arguments = Bundle().apply { + putString(EXTRA_CHILD_ID, childId) + } + } + } + + val childId: String by lazy { arguments!!.getString(EXTRA_CHILD_ID) } + val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + auth.logic.database.user().getChildUserByIdLive(childId).observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = SetChildPasswordDialogFragmentBinding.inflate(inflater, container, false) + + binding.passwordView.passwordOk.observe(this, Observer { + binding.saveButton.isEnabled = it + }) + + binding.saveButton.setOnClickListener { + val childId = childId + val password = binding.passwordView.password.value!! + val auth = auth + + dismissAllowingStateLoss() + + runAsync { + auth.tryDispatchParentAction( + SetChildPasswordAction( + childId = childId, + newPassword = ParentPassword.createCoroutine(password) + ) + ) + } + } + + return binding.root + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, DIALOG_TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/UpdateChildPasswordDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/UpdateChildPasswordDialogFragment.kt new file mode 100644 index 0000000..e10a2f3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/UpdateChildPasswordDialogFragment.kt @@ -0,0 +1,106 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced.password + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.R +import io.timelimit.android.data.Database +import io.timelimit.android.databinding.ChangePasswordViewBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.logic.DefaultAppLogic + +class UpdateChildPasswordDialogFragment: BottomSheetDialogFragment() { + companion object { + private const val CHILD_ID = "childId" + private const val DIALOG_TAG = "ucpdf" + + fun newInstance(childId: String) = UpdateChildPasswordDialogFragment().apply { + arguments = Bundle().apply { + putString(CHILD_ID, childId) + } + } + } + + val childId: String by lazy { arguments!!.getString(CHILD_ID) } + val databae: Database by lazy { DefaultAppLogic.with(context!!).database } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + databae.user().getChildUserByIdLive(childId).observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = ChangePasswordViewBinding.inflate(inflater, container, false) + val model = ViewModelProviders.of(this).get(UpdateChildPasswordViewModel::class.java) + + binding.newPassword.passwordOk.observe(this, Observer { + binding.canConfirm = it + }) + + binding.saveButton.setOnClickListener { + model.changePassword( + childUserId = childId, + newPassword = binding.newPassword.password.value!!, + oldPassword = binding.oldPassword.text.toString() + ) + } + + model.status.observe(this, Observer { status -> + when (status!!) { + ChangeChildPasswordViewModelStatus.Idle -> { + binding.isWorking = false + } + ChangeChildPasswordViewModelStatus.Working -> { + binding.isWorking = true + } + ChangeChildPasswordViewModelStatus.Failed -> { + Toast.makeText(context!!, R.string.error_general, Toast.LENGTH_SHORT).show() + + model.confirmError() + } + ChangeChildPasswordViewModelStatus.WrongPassword -> { + Toast.makeText(context!!, R.string.manage_parent_change_password_toast_wrong_password, Toast.LENGTH_SHORT).show() + + model.confirmError() + } + ChangeChildPasswordViewModelStatus.Done -> { + Toast.makeText(context!!, R.string.manage_parent_change_password_toast_success, Toast.LENGTH_SHORT).show() + + dismissAllowingStateLoss() + + null + } + }.let { } + }) + + return binding.root + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, DIALOG_TAG) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/UpdateChildPasswordViewModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/UpdateChildPasswordViewModel.kt new file mode 100644 index 0000000..1967d7e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/password/UpdateChildPasswordViewModel.kt @@ -0,0 +1,114 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced.password + +import android.app.Application +import android.util.Log +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.crypto.PasswordHashing +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.ChildChangePasswordAction +import io.timelimit.android.sync.actions.apply.ApplyActionChildAuthentication +import io.timelimit.android.sync.actions.apply.ApplyActionUtil +import io.timelimit.android.sync.network.ParentPassword + +class UpdateChildPasswordViewModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "ChangeParentPassword" + } + + private val statusInternal = MutableLiveData().apply { + value = ChangeChildPasswordViewModelStatus.Idle + } + + private val logic = DefaultAppLogic.with(application) + + val status = statusInternal.castDown() + + fun confirmError() { + val value = statusInternal.value + + if (value == ChangeChildPasswordViewModelStatus.Failed || value == ChangeChildPasswordViewModelStatus.WrongPassword) { + statusInternal.value = ChangeChildPasswordViewModelStatus.Idle + } + } + + fun changePassword(childUserId: String, oldPassword: String, newPassword: String) { + runAsync { + try { + if (statusInternal.value != ChangeChildPasswordViewModelStatus.Idle) { + return@runAsync + } + + statusInternal.value = ChangeChildPasswordViewModelStatus.Working + + val userEntry = logic.database.user().getUserByIdLive(childUserId).waitForNullableValue() + + if (userEntry == null || userEntry.type != UserType.Child) { + statusInternal.value = ChangeChildPasswordViewModelStatus.Failed + return@runAsync + } + + val isOldPasswordCorrect = Threads.crypto.executeAndWait { + PasswordHashing.validateSync(oldPassword, userEntry.password) + } + + if (!isOldPasswordCorrect) { + statusInternal.value = ChangeChildPasswordViewModelStatus.WrongPassword + return@runAsync + } + + val oldPasswordSecondHash = Threads.crypto.executeAndWait { + PasswordHashing.hashSyncWithSalt(oldPassword, userEntry.secondPasswordSalt) + } + + val action = ChildChangePasswordAction( + password = ParentPassword.createCoroutine(newPassword) + ) + + ApplyActionUtil.applyChildAction( + action, + logic.database, + ApplyActionChildAuthentication( + childUserId = childUserId, + secondPasswordHash = oldPasswordSecondHash + ), + logic.syncUtil + ) + + statusInternal.value = ChangeChildPasswordViewModelStatus.Done + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "changing password failed", ex) + } + + statusInternal.value = ChangeChildPasswordViewModelStatus.Failed + } + } + } +} + +enum class ChangeChildPasswordViewModelStatus { + Idle, Working, Failed, WrongPassword, Done +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/timezone/SetChildTimezoneDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/timezone/SetChildTimezoneDialogFragment.kt new file mode 100644 index 0000000..df99643 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/timezone/SetChildTimezoneDialogFragment.kt @@ -0,0 +1,126 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced.timezone + +import android.app.Dialog +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.view.LayoutInflater +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Observer +import androidx.recyclerview.widget.LinearLayoutManager +import io.timelimit.android.R +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.SetChildTimezoneDialogFragmentBinding +import io.timelimit.android.extensions.readableName +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.map +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.SetUserTimezoneAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import java.util.* + +class SetChildTimezoneDialogFragment : DialogFragment() { + companion object { + private const val EXTRA_CHILD_ID = "childId" + private const val DIALOG_TAG = "SetChildTimezoneDialogFragment" + + fun newInstance(childId: String) = SetChildTimezoneDialogFragment().apply { + arguments = Bundle().apply { + putString(EXTRA_CHILD_ID, childId) + } + } + } + + val childId: String by lazy { + arguments!!.getString(EXTRA_CHILD_ID) + } + + val auth: ActivityViewModel by lazy { + getActivityViewModel(activity!!) + } + + val logic: AppLogic by lazy { + DefaultAppLogic.with(context!!) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val binding = SetChildTimezoneDialogFragmentBinding.inflate(LayoutInflater.from(context!!)) + val adapter = TimezoneAdapter() + + adapter.listener = object: TimezoneAdapterListener { + override fun onTimezoneClicked(timeZone: TimeZone) { + auth.tryDispatchParentAction( + SetUserTimezoneAction( + userId = childId, + timezone = timeZone.id + ) + ) + + dismiss() + } + } + + binding.recycler.layoutManager = LinearLayoutManager(context!!) + binding.recycler.adapter = adapter + + val searchTerm = MutableLiveData().apply { value = binding.searchField.text.toString() } + binding.searchField.addTextChangedListener(object: TextWatcher { + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { + searchTerm.value = binding.searchField.text.toString() + } + + override fun afterTextChanged(s: Editable?) { + // ignore + } + + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { + // ignore + } + }) + + val zones = listOf(logic.timeApi.getSystemTimeZone()) + (TimeZone.getAvailableIDs().map { zoneId -> TimeZone.getTimeZone(zoneId) }) + + searchTerm.map { term -> + zones.filter { it.readableName().contains(term, ignoreCase = true) } + }.observe(this, Observer { + adapter.timezones = it + }) + + return AlertDialog.Builder(context!!, R.style.AppTheme) + .setView(binding.root) + .setNegativeButton(R.string.generic_cancel, null) + .create() + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, DIALOG_TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/timezone/TimezoneAdapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/timezone/TimezoneAdapter.kt new file mode 100644 index 0000000..8c7aba1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/timezone/TimezoneAdapter.kt @@ -0,0 +1,57 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.advanced.timezone + +import android.view.LayoutInflater +import android.view.ViewGroup +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.R +import io.timelimit.android.extensions.readableName +import java.util.* +import kotlin.properties.Delegates + +class TimezoneAdapter: RecyclerView.Adapter() { + var timezones: List by Delegates.observable(emptyList()) { _, _, _ -> notifyDataSetChanged() } + var listener: TimezoneAdapterListener? = null + + override fun getItemCount(): Int = timezones.size + override fun getItemId(position: Int): Long = timezones[position].id.hashCode().toLong() + + init { + setHasStableIds(true) + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = TimezoneViewHolder( + LayoutInflater.from(parent.context) + .inflate(R.layout.simple_list_item, parent, false) as TextView + ) + + override fun onBindViewHolder(holder: TimezoneViewHolder, position: Int) { + val item = timezones[position] + + holder.view.text = item.readableName() + holder.view.setOnClickListener { + listener?.onTimezoneClicked(item) + } + } +} + +class TimezoneViewHolder(val view: TextView): RecyclerView.ViewHolder(view) + +interface TimezoneAdapterListener { + fun onTimezoneClicked(timeZone: TimeZone) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsAdapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsAdapter.kt new file mode 100644 index 0000000..7dd2d9e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsAdapter.kt @@ -0,0 +1,152 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.apps + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.R +import io.timelimit.android.data.model.App +import io.timelimit.android.databinding.FragmentChildAppsItemBinding +import io.timelimit.android.databinding.GenericBigListHeaderBinding +import io.timelimit.android.databinding.GenericListHeaderBinding +import io.timelimit.android.logic.DefaultAppLogic +import kotlin.properties.Delegates + +class ChildAppsAdapter: RecyclerView.Adapter() { + companion object { + private const val TYPE_CATEGORY_HEADER = 0 + private const val TYPE_APP = 1 + private const val TYPE_EMPTY = 2 + private const val TYPE_ASSIGN_ALL = 3 + } + + var data: List by Delegates.observable(emptyList()) { _, _, _ -> notifyDataSetChanged() } + var handlers: Handlers? = null + + init { + setHasStableIds(true) + } + + override fun getItemCount(): Int = data.size + override fun getItemViewType(position: Int): Int = when (data[position]) { + is ChildAppsCategoryHeader -> TYPE_CATEGORY_HEADER + is ChildAppsApp -> TYPE_APP + is ChildAppsEmptyCategory -> TYPE_EMPTY + is ChildAppsAssignAll -> TYPE_ASSIGN_ALL + } + + override fun getItemId(position: Int): Long { + val item = data[position] + + return when (item) { + is ChildAppsCategoryHeader -> (item.categoryId ?: "no category").hashCode().toLong() + is ChildAppsApp -> item.app.packageName.hashCode().toLong() + is ChildAppsEmptyCategory -> (item.categoryId ?: "no category").hashCode().toLong() + is ChildAppsAssignAll -> "assign all".hashCode().toLong() + } + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChildAppsHolder = when (viewType) { + TYPE_CATEGORY_HEADER -> CategoryHeaderHolder( + GenericBigListHeaderBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + TYPE_APP -> AppHolder( + FragmentChildAppsItemBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + TYPE_EMPTY -> CategoryEmptyHolder( + GenericListHeaderBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ).apply { + text = parent.context.getString(R.string.child_apps_empty_category) + executePendingBindings() + }.root + ) + TYPE_ASSIGN_ALL -> { + AssignAllAppsViewHolder( + Button(parent.context).apply { + setText(R.string.child_apps_assign_all) + } + ) + } + else -> throw IllegalArgumentException() + } + + override fun onBindViewHolder(holder: ChildAppsHolder, position: Int) { + val item = data[position] + + when (item) { + is ChildAppsCategoryHeader -> { + holder as CategoryHeaderHolder + + holder.binding.text = item.title + holder.binding.executePendingBindings() + + null + } + is ChildAppsApp -> { + holder as AppHolder + + holder.binding.item = item.app + holder.binding.currentCategoryTitle = item.shownCategoryName + holder.binding.icon.setImageDrawable( + DefaultAppLogic.with(holder.binding.root.context).platformIntegration.getAppIcon(item.app.packageName) + ) + holder.binding.handlers = handlers + holder.binding.executePendingBindings() + + null + } + is ChildAppsEmptyCategory -> { + holder as CategoryEmptyHolder + + // nothing to do + } + is ChildAppsAssignAll -> { + holder as AssignAllAppsViewHolder + + holder.itemView.setOnClickListener { + handlers?.onAssignAppsClicked(item.packageNames) + } + + null + } + }.let { /* require handling all paths */ } + } +} + +sealed class ChildAppsHolder(view: View): RecyclerView.ViewHolder(view) +class CategoryHeaderHolder(val binding: GenericBigListHeaderBinding): ChildAppsHolder(binding.root) +class AppHolder(val binding: FragmentChildAppsItemBinding): ChildAppsHolder(binding.root) +class CategoryEmptyHolder(view: View): ChildAppsHolder(view) +class AssignAllAppsViewHolder(view: View): ChildAppsHolder(view) + +interface Handlers { + fun onAppClicked(app: App) + fun onAssignAppsClicked(packageNames: List) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsFragment.kt new file mode 100644 index 0000000..206976d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsFragment.kt @@ -0,0 +1,104 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.apps + + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.recyclerview.widget.LinearLayoutManager +import io.timelimit.android.R +import io.timelimit.android.data.model.App +import io.timelimit.android.databinding.ChildAppsFragmentBinding +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.manage.child.ManageChildFragmentArgs +import io.timelimit.android.ui.manage.child.apps.assign.AssignAllAppsCategoryDialogFragment +import io.timelimit.android.ui.manage.child.apps.assign.AssignAppCategoryDialogFragment +import io.timelimit.android.ui.view.AppFilterView + +class ChildAppsFragment : Fragment() { + companion object { + fun newInstance(args: ManageChildFragmentArgs) = ChildAppsFragment().apply { + arguments = args.toBundle() + } + } + + val args: ManageChildFragmentArgs by lazy { + ManageChildFragmentArgs.fromBundle(arguments!!) + } + + val auth: ActivityViewModel by lazy { (activity as ActivityViewModelHolder).getActivityViewModel() } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = ChildAppsFragmentBinding.inflate(inflater, container, false) + val model = ViewModelProviders.of(this).get(ChildAppsModel::class.java) + val adapter = ChildAppsAdapter() + + fun getMode() = when (binding.sortSetting.checkedRadioButtonId) { + R.id.sort_by_category -> ChildAppsMode.SortByCategory + R.id.sort_by_title -> ChildAppsMode.SortByTitle + else -> throw IllegalArgumentException() + } + + model.childIdLive.value = args.childId + AppFilterView.getFilterLive(binding.appFilter).observe(this, Observer { model.appFilterLive.value = it }) + model.modeLive.value = getMode() + binding.sortSetting.setOnCheckedChangeListener { _, _ -> model.modeLive.value = getMode() } + + model.showAppsFromOtherDevicesChecked.value = binding.showAppsFromUnassignedDevices.isChecked + binding.showAppsFromUnassignedDevices.setOnCheckedChangeListener { _, isChecked -> + model.showAppsFromOtherDevicesChecked.value = isChecked + } + + model.listContentLive.observe(this, Observer { + adapter.data = it + }) + + model.isLocalMode.observe(this, Observer { + binding.showAppsFromUnassignedDevices.visibility = if (it) View.GONE else View.VISIBLE + }) + + binding.recycler.layoutManager = LinearLayoutManager(context) + binding.recycler.adapter = adapter + + adapter.handlers = object: Handlers { + override fun onAppClicked(app: App) { + if (auth.requestAuthenticationOrReturnTrue()) { + AssignAppCategoryDialogFragment.newInstance( + childId = args.childId, + appPackageName = app.packageName + ).show(fragmentManager!!) + } + } + + override fun onAssignAppsClicked(packageNames: List) { + if (auth.requestAuthenticationOrReturnTrue()) { + AssignAllAppsCategoryDialogFragment.newInstance( + childId = args.childId, + appPackageNames = packageNames + ).show(fragmentManager!!) + } + } + } + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsModel.kt new file mode 100644 index 0000000..3172dfb --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsModel.kt @@ -0,0 +1,155 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.apps + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.R +import io.timelimit.android.data.model.App +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.view.AppFilterView + +class ChildAppsModel(application: Application): AndroidViewModel(application) { + private val logic = DefaultAppLogic.with(application) + private val database = logic.database + + val childIdLive = MutableLiveData() + val modeLive = MutableLiveData().apply { value = ChildAppsMode.SortByCategory } + val appFilterLive = MutableLiveData().apply { value = AppFilterView.AppFilter.dummy } + val showAppsFromOtherDevicesChecked = MutableLiveData().apply { value = false } + + val isLocalMode = database.config().getDeviceAuthTokenAsync().map { it.isEmpty() } + private val realShowAppsFromAllDevices = isLocalMode.switchMap { localMode -> + if (localMode) { + liveDataFromValue(true) + } else { + showAppsFromOtherDevicesChecked + } + } + + private val childDevicesLive = childIdLive.ignoreUnchanged().switchMap { userId -> database.device().getDevicesByUserId(userId) } + private val childDeviceIdsLive = childDevicesLive.map { devices -> devices.map { it.id } }.ignoreUnchanged() + private val childAppsAssignedDevicesLive = childDeviceIdsLive.switchMap { deviceIds -> database.app().getAppsByDeviceIds(deviceIds) } + private val childAppsAllDevicesLive = database.app().getAllApps() + private val childAppsLive = realShowAppsFromAllDevices.switchMap { allDevices -> + if (allDevices) + childAppsAllDevicesLive + else + childAppsAssignedDevicesLive + } + + private val childCategoriesLive = childIdLive.switchMap { userId -> database.category().getCategoriesByChildId(userId) } + private val childCategoryIdsLive = childCategoriesLive.map { categories -> categories.map { it.id } }.ignoreUnchanged() + private val childCategoryAppsLive = childCategoryIdsLive.switchMap { categoryIds -> database.categoryApp().getCategoryApps(categoryIds) } + + val listContentLive = childAppsLive.switchMap { childApps -> + childCategoriesLive.switchMap { categories -> + childCategoryAppsLive.switchMap { categoryApps -> + appFilterLive.ignoreUnchanged().switchMap { appFilter -> + val filteredChildApps = childApps.filter { appFilter.matches(it) } + + modeLive.ignoreUnchanged().map { mode -> + when (mode!!) { + ChildAppsMode.SortByCategory -> { + val categoryAppByPackageName = categoryApps.associateBy { it.packageName } + val appsByCategoryId = filteredChildApps.groupBy { app -> + categoryAppByPackageName[app.packageName]?.categoryId + } + + val result = mutableListOf() + + fun handleCategory(categoryId: String?, title: String) { + result.add(ChildAppsCategoryHeader(title, categoryId)) + + val apps = appsByCategoryId[categoryId] + + if (apps.isNullOrEmpty()) { + result.add(ChildAppsEmptyCategory(categoryId)) + } else { + val sortedApps = apps + .distinctBy { it.packageName } + .sortedBy { it.title.toLowerCase() } + + if (categoryId == null) { + result.add(ChildAppsAssignAll( + packageNames = sortedApps.map { it.packageName } + )) + } + + result.addAll( + sortedApps.map { app -> + ChildAppsApp( + app = app, + // no category name shown when showing category headers + shownCategoryName = null + ) + } + ) + } + } + + categories.forEach { category -> + handleCategory( + categoryId = category.id, + title = category.title + ) + } + + handleCategory( + categoryId = null, + title = application.getString(R.string.child_apps_unassigned) + ) + + result + } + ChildAppsMode.SortByTitle -> { + val categoryById = categories.associateBy { it.id } + val categoryAppByPackageName = categoryApps.associateBy { it.packageName } + + filteredChildApps + .distinctBy { it.packageName } + .map { app -> + val categoryId = categoryAppByPackageName[app.packageName]?.categoryId + val category = categoryById[categoryId] + + ChildAppsApp( + app = app, + shownCategoryName = category?.title + ) + } + } + } + } + } + } + } + } +} + +enum class ChildAppsMode { + SortByCategory, SortByTitle +} + +sealed class ChildAppsEntry +data class ChildAppsCategoryHeader(val title: String, val categoryId: String?): ChildAppsEntry() +data class ChildAppsApp(val app: App, val shownCategoryName: String?): ChildAppsEntry() +data class ChildAppsEmptyCategory(val categoryId: String?): ChildAppsEntry() +data class ChildAppsAssignAll(val packageNames: List): ChildAppsEntry() diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/apps/assign/AssignAllAppsCategoryDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/assign/AssignAllAppsCategoryDialogFragment.kt new file mode 100644 index 0000000..964ca39 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/assign/AssignAllAppsCategoryDialogFragment.kt @@ -0,0 +1,121 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.apps.assign + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.CheckedTextView +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.R +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.Category +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.BottomSheetSelectionListBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.AddCategoryAppsAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder + +class AssignAllAppsCategoryDialogFragment: BottomSheetDialogFragment() { + companion object { + private const val EXTRA_CHILD_ID = "a" + private const val EXTRA_PACKAGE_NAMES = "b" + private const val TAG = "aaacdf" + + fun newInstance(childId: String, appPackageNames: List) = AssignAllAppsCategoryDialogFragment().apply { + arguments = Bundle().apply { + putString(EXTRA_CHILD_ID, childId) + putStringArray(EXTRA_PACKAGE_NAMES, appPackageNames.toTypedArray()) + } + } + } + + val childId: String by lazy { arguments!!.getString(EXTRA_CHILD_ID) } + val appPackageNames: Array by lazy { arguments!!.getStringArray(EXTRA_PACKAGE_NAMES) } + + val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + val database: Database by lazy { logic.database } + val auth: ActivityViewModel by lazy { (activity as ActivityViewModelHolder).getActivityViewModel() } + + val childCategoryEntries: LiveData> by lazy { + database.category().getCategoriesByChildId(childId) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + } + + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = BottomSheetSelectionListBinding.inflate(inflater, container, false) + val list = binding.list + + binding.title = resources.getQuantityString(R.plurals.generic_plural_app, appPackageNames.size, appPackageNames.size) + + childCategoryEntries.observe(this, Observer { categories -> + fun buildRow(): CheckedTextView = LayoutInflater.from(context!!).inflate( + android.R.layout.simple_list_item_single_choice, + list, + false + ) as CheckedTextView + + categories.forEach { category -> + buildRow().let { row -> + row.text = category.title + row.setOnClickListener { + auth.tryDispatchParentAction( + AddCategoryAppsAction( + categoryId = category.id, + packageNames = appPackageNames.toList() + ) + ) + + dismiss() + } + + list.addView(row) + } + } + + buildRow().let { row -> + row.setText(R.string.child_apps_unassigned) + row.isChecked = true + row.setOnClickListener { + dismiss() + } + + list.addView(row) + } + }) + + return binding.root + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/apps/assign/AssignAppCategoryDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/assign/AssignAppCategoryDialogFragment.kt new file mode 100644 index 0000000..2b84508 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/assign/AssignAppCategoryDialogFragment.kt @@ -0,0 +1,175 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.apps.assign + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.CheckedTextView +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.R +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.* +import io.timelimit.android.databinding.BottomSheetSelectionListBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.AddCategoryAppsAction +import io.timelimit.android.sync.actions.RemoveCategoryAppsAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder + +class AssignAppCategoryDialogFragment: BottomSheetDialogFragment() { + companion object { + private const val EXTRA_CHILD_ID = "a" + private const val EXTRA_PACKAGE_NAME = "b" + private const val TAG = "aacdf" + + fun newInstance(childId: String, appPackageName: String) = AssignAppCategoryDialogFragment().apply { + arguments = Bundle().apply { + putString(EXTRA_CHILD_ID, childId) + putString(EXTRA_PACKAGE_NAME, appPackageName) + } + } + } + + val childId: String by lazy { arguments!!.getString(EXTRA_CHILD_ID) } + val appPackageName: String by lazy { arguments!!.getString(EXTRA_PACKAGE_NAME) } + + val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + val database: Database by lazy { logic.database } + val auth: ActivityViewModel by lazy { (activity as ActivityViewModelHolder).getActivityViewModel() } + + val childDeviceEntries: LiveData> by lazy { + database.device().getDevicesByUserId(childId) + } + + val childDeviceIds: LiveData> by lazy { + childDeviceEntries.map { devices -> devices.map { it.id } }.ignoreUnchanged() + } + + val matchingAppEntries: LiveData> by lazy { + childDeviceIds.switchMap { deviceIds -> + database.app().getAppsByDeviceIdsAndPackageName(deviceIds, appPackageName) + } + } + + val childCategoryEntries: LiveData> by lazy { + database.category().getCategoriesByChildId(childId) + } + + val categoryAppEntry: LiveData by lazy { + childCategoryEntries.switchMap { childCategories -> + database.categoryApp().getCategoryApp( + categoryIds = childCategories.map { it.id }, + packageName = appPackageName + ) + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + matchingAppEntries.observe(this, Observer { + if (it.isEmpty()) { + dismissAllowingStateLoss() + } + }) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = BottomSheetSelectionListBinding.inflate(inflater, container, false) + + val list = binding.list + + childCategoryEntries.switchMap { categories -> + categoryAppEntry.map { appCategory -> + categories to appCategory + } + }.observe(this, Observer { (categories, appCategory) -> + list.removeAllViews() + + val hasCategory = appCategory != null && categories.find { it.id == appCategory.categoryId } != null + + fun buildRow(): CheckedTextView = LayoutInflater.from(context!!).inflate( + android.R.layout.simple_list_item_single_choice, + list, + false + ) as CheckedTextView + + categories.forEach { category -> + buildRow().let { row -> + row.text = category.title + row.isChecked = category.id == appCategory?.categoryId + row.setOnClickListener { + if (appCategory?.categoryId != category.id) { + auth.tryDispatchParentAction( + AddCategoryAppsAction( + categoryId = category.id, + packageNames = listOf(appPackageName) + ) + ) + } + + dismiss() + } + + list.addView(row) + } + } + + buildRow().let { row -> + row.setText(R.string.child_apps_unassigned) + row.isChecked = !hasCategory + row.setOnClickListener { + if (appCategory != null) { + auth.tryDispatchParentAction( + RemoveCategoryAppsAction( + categoryId = appCategory.categoryId, + packageNames = listOf(appPackageName) + ) + ) + } + + dismiss() + } + + list.addView(row) + } + }) + + matchingAppEntries.observe(this, Observer { + binding.title = it.firstOrNull()?.title + }) + + return binding.root + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/category/Adapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/category/Adapter.kt new file mode 100644 index 0000000..ba619f9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/category/Adapter.kt @@ -0,0 +1,156 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.category + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.R +import io.timelimit.android.data.model.Category +import io.timelimit.android.databinding.AddItemViewBinding +import io.timelimit.android.databinding.CategoryRichCardBinding +import io.timelimit.android.util.TimeTextUtil +import kotlin.properties.Delegates + +class Adapter: RecyclerView.Adapter() { + companion object { + private const val TYPE_ITEM = 0 + private const val TYPE_ADD = 1 + private const val TYPE_INTRO = 2 + private const val TYPE_MANIPULATION_WARNING = 3 + } + + var categories: List? by Delegates.observable(null as List?) { _, _, _ -> notifyDataSetChanged() } + var handlers: Handlers? by Delegates.observable(null as Handlers?) { _, _, _ -> notifyDataSetChanged() } + + init { + setHasStableIds(true) + } + + private fun getItem(position: Int) = categories!![position] + override fun getItemId(position: Int): Long { + val item = getItem(position) + + return when (item) { + is CategoryItem -> item.category.id.hashCode() + CreateCategoryItem -> item.hashCode() + CategoriesIntroductionHeader -> item.hashCode() + ManipulationWarningCategoryItem -> item.hashCode() + }.toLong() + } + + override fun getItemViewType(position: Int) = when (getItem(position)) { + is CategoryItem -> TYPE_ITEM + CreateCategoryItem -> TYPE_ADD + CategoriesIntroductionHeader -> TYPE_INTRO + ManipulationWarningCategoryItem -> TYPE_MANIPULATION_WARNING + } + + override fun getItemCount() = categories?.size ?: 0 + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when (viewType) { + TYPE_ADD -> + AddViewHolder( + AddItemViewBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ).apply { + label = parent.context.getString(R.string.create_category_title) + + root.setOnClickListener { + handlers?.onCreateCategoryClicked() + } + }.root + ) + + TYPE_ITEM -> + ItemViewHolder( + CategoryRichCardBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + + TYPE_INTRO -> + IntroViewHolder( + LayoutInflater.from(parent.context) + .inflate(R.layout.category_list_intro, parent, false) + ) + + TYPE_MANIPULATION_WARNING -> + ManipulationWarningViewHolder( + LayoutInflater.from(parent.context) + .inflate(R.layout.manage_child_manipulation_warning, parent, false) + ) + + else -> throw IllegalStateException() + } + + override fun onBindViewHolder(holder: ViewHolder, position: Int) { + val item = getItem(position) + + when (item) { + is CategoryItem -> { + holder as ItemViewHolder + + val binding = holder.binding + val context = binding.root.context + + binding.title = item.category.title + binding.isBlockedTimeNow = item.isBlockedTimeNow + binding.remainingTimeToday = if (item.remainingTimeToday != null) { + TimeTextUtil.remaining(item.remainingTimeToday.toInt(), context) + } else { + null + } + binding.usedTimeToday = if (item.usedTimeToday != 0L) { + TimeTextUtil.used(item.usedTimeToday.toInt(), context) + } else { + null + } + binding.usedForAppsWithoutCategory = item.usedForNotAssignedApps + binding.parentCategoryTitle = item.parentCategoryTitle + + binding.card.setOnClickListener { handlers?.onCategoryClicked(item.category) } + + binding.executePendingBindings() + } + CreateCategoryItem -> { + // nothing to do + } + CategoriesIntroductionHeader -> { + // nothing to do + } + ManipulationWarningCategoryItem -> { + // nothing to do + } + }.let { } + } +} + +sealed class ViewHolder(view: View): RecyclerView.ViewHolder(view) +class AddViewHolder(view: View): ViewHolder(view) +class IntroViewHolder(view: View): ViewHolder(view) +class ManipulationWarningViewHolder(view: View): ViewHolder(view) +class ItemViewHolder(val binding: CategoryRichCardBinding): ViewHolder(binding.root) + +interface Handlers { + fun onCategoryClicked(category: Category) + fun onCreateCategoryClicked() +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/category/Items.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/category/Items.kt new file mode 100644 index 0000000..b2a122c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/category/Items.kt @@ -0,0 +1,31 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.category + +import io.timelimit.android.data.model.Category + +sealed class ManageChildCategoriesListItem +object CategoriesIntroductionHeader: ManageChildCategoriesListItem() +object CreateCategoryItem: ManageChildCategoriesListItem() +object ManipulationWarningCategoryItem: ManageChildCategoriesListItem() +data class CategoryItem( + val category: Category, + val isBlockedTimeNow: Boolean, + val remainingTimeToday: Long?, + val usedTimeToday: Long, + val usedForNotAssignedApps: Boolean, + val parentCategoryTitle: String? +): ManageChildCategoriesListItem() diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/category/ManageChildCategoriesFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/category/ManageChildCategoriesFragment.kt new file mode 100644 index 0000000..c1bdcc1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/category/ManageChildCategoriesFragment.kt @@ -0,0 +1,113 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.category + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.Navigation +import androidx.recyclerview.widget.ItemTouchHelper +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.data.model.Category +import io.timelimit.android.data.model.HintsToShow +import io.timelimit.android.extensions.safeNavigate +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.child.ManageChildFragmentArgs +import io.timelimit.android.ui.manage.child.ManageChildFragmentDirections +import io.timelimit.android.ui.manage.child.category.create.CreateCategoryDialogFragment +import kotlinx.android.synthetic.main.fragment_manage_child_categories.* + +class ManageChildCategoriesFragment : Fragment() { + companion object { + fun newInstance(params: ManageChildFragmentArgs) = ManageChildCategoriesFragment().apply { + arguments = params.toBundle() + } + } + + private val params: ManageChildFragmentArgs by lazy { ManageChildFragmentArgs.fromBundle(arguments!!) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val model: ManageChildCategoriesModel by lazy { + ViewModelProviders.of(this).get(ManageChildCategoriesModel::class.java) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_manage_child_categories, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + val adapter = Adapter() + val navigation = Navigation.findNavController(view) + + adapter.handlers = object: Handlers { + override fun onCategoryClicked(category: Category) { + navigation.safeNavigate( + ManageChildFragmentDirections.actionManageChildFragmentToManageCategoryFragment( + params.childId, + category.id + ), + R.id.manageChildFragment + ) + } + + override fun onCreateCategoryClicked() { + if (auth.requestAuthenticationOrReturnTrue()) { + CreateCategoryDialogFragment.newInstance(params) + .show(fragmentManager!!) + } + } + } + + recycler.adapter = adapter + recycler.layoutManager = LinearLayoutManager(context) + + model.init(params.childId) + model.listContent.observe(this, Observer { adapter.categories = it }) + + ItemTouchHelper(object: ItemTouchHelper.Callback() { + override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { + if (adapter.categories!![viewHolder.adapterPosition] == CategoriesIntroductionHeader) { + return makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.END) or + makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END) + } else { + return 0 + } + } + + override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder) = throw IllegalStateException() + + override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { + val database = logic.database + + Threads.database.submit { + database.config().setHintsShownSync(HintsToShow.CATEGORIES_INTRODUCTION) + } + } + }).attachToRecyclerView(recycler) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/category/ManageChildCategoriesModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/category/ManageChildCategoriesModel.kt new file mode 100644 index 0000000..d866dde --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/category/ManageChildCategoriesModel.kt @@ -0,0 +1,145 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.category + +import android.app.Application +import android.util.SparseLongArray +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.data.extensions.mapToTimezone +import io.timelimit.android.data.model.HintsToShow +import io.timelimit.android.date.DateInTimezone +import io.timelimit.android.date.getMinuteOfWeek +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.liveDataFromFunction +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.logic.RemainingTime + +class ManageChildCategoriesModel(application: Application): AndroidViewModel(application) { + private val logic = DefaultAppLogic.with(application) + private val childId = MutableLiveData() + + fun init(childId: String) { + if (this.childId.value != childId) { + this.childId.value = childId + } + } + + private val childDevices = childId.switchMap { logic.database.device().getDevicesByUserId(it) } + + private val hasChildDevicesWithManipulation = childDevices.map { devices -> devices.find { device -> device.hasAnyManipulation } != null }.ignoreUnchanged() + + private val childEntry = childId.switchMap { logic.database.user().getChildUserByIdLive(it) } + + private val categoryForUnassignedAppsLive = childEntry.map { it?.categoryForNotAssignedApps }.ignoreUnchanged() + + private val childTimezone = childEntry.mapToTimezone() + + private val childMinuteOfWeek = childTimezone.switchMap { timeZone -> + liveDataFromFunction { getMinuteOfWeek(logic.realTimeLogic.getCurrentTimeInMillis(), timeZone) } + }.ignoreUnchanged() + + private val childDate = childTimezone.switchMap { timeZone -> + liveDataFromFunction { DateInTimezone.newInstance(logic.realTimeLogic.getCurrentTimeInMillis(), timeZone) } + }.ignoreUnchanged() + + private val categories = childId.switchMap { logic.database.category().getCategoriesByChildId(it) } + + private val usedTimeItemsForWeek = childDate.switchMap { date -> + categories.switchMap { categories -> + logic.database.usedTimes().getUsedTimesByDayAndCategoryIds( + categoryIds = categories.map { it.id }, + startingDayOfEpoch = date.dayOfEpoch - date.dayOfWeek, + endDayOfEpoch = date.dayOfEpoch - date.dayOfWeek + 6 + ) + } + } + + private val timeLimitRules = categories.switchMap { categories -> + logic.database.timeLimitRules().getTimeLimitRulesByCategories( + categories.map { category -> category.id } + ) + } + + private val categoryItems = categoryForUnassignedAppsLive.switchMap { categoryForUnassignedApps -> + categories.switchMap { categories -> + timeLimitRules.switchMap { timeLimitRules -> + childDate.switchMap { childDate -> + usedTimeItemsForWeek.switchMap { usedTimeItemsForWeek -> + childMinuteOfWeek.map { childMinuteOfWeek -> + val rulesByCategoryId = timeLimitRules.groupBy { rule -> rule.categoryId } + val usedTimesByCategory = usedTimeItemsForWeek.groupBy { item -> item.categoryId } + val firstDayOfWeek = childDate.dayOfEpoch - childDate.dayOfWeek + + categories.map { category -> + val rules = rulesByCategoryId[category.id] ?: emptyList() + val usedTimeItemsForCategory = usedTimesByCategory[category.id] + ?: emptyList() + val parentCategory = categories.find { it.id == category.parentCategoryId } + + CategoryItem( + category = category, + isBlockedTimeNow = category.blockedMinutesInWeek.read(childMinuteOfWeek), + remainingTimeToday = RemainingTime.getRemainingTime( + dayOfWeek = childDate.dayOfWeek, + usedTimes = SparseLongArray().apply { + usedTimeItemsForCategory.forEach { usedTimeItem -> + + val dayOfWeek = usedTimeItem.dayOfEpoch - firstDayOfWeek + + put(dayOfWeek, usedTimeItem.usedMillis) + } + }, + rules = rules, + extraTime = category.extraTimeInMillis + )?.includingExtraTime, + usedTimeToday = usedTimeItemsForCategory.find { item -> item.dayOfEpoch == childDate.dayOfEpoch }?.usedMillis + ?: 0, + usedForNotAssignedApps = categoryForUnassignedApps == category.id, + parentCategoryTitle = parentCategory?.title + ) + } + } + } + } + } + } + }.ignoreUnchanged() + + private val hasShownHint = logic.database.config().wereHintsShown(HintsToShow.CATEGORIES_INTRODUCTION) + + private val listContentStep1 = hasShownHint.switchMap { hasShownHint -> + categoryItems.map { categoryItems -> + if (hasShownHint) { + categoryItems + listOf(CreateCategoryItem) + } else { + listOf(CategoriesIntroductionHeader) + categoryItems + listOf(CreateCategoryItem) + } + } + } + + val listContent = hasChildDevicesWithManipulation.switchMap { hasChildDevicesWithManipulation -> + listContentStep1.map { listContent -> + if (hasChildDevicesWithManipulation) { + listOf(ManipulationWarningCategoryItem) + listContent + } else { + listContent + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/category/create/CreateCategoryDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/category/create/CreateCategoryDialogFragment.kt new file mode 100644 index 0000000..7e526ec --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/category/create/CreateCategoryDialogFragment.kt @@ -0,0 +1,68 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.category.create + +import android.os.Bundle +import android.view.View +import androidx.fragment.app.FragmentManager +import io.timelimit.android.R +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.sync.actions.CreateCategoryAction +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.manage.child.ManageChildFragmentArgs +import io.timelimit.android.ui.util.EditTextBottomSheetDialog + + +class CreateCategoryDialogFragment: EditTextBottomSheetDialog() { + companion object { + private const val DIALOG_TAG = "a" + + fun newInstance(params: ManageChildFragmentArgs) = CreateCategoryDialogFragment().apply { + arguments = params.toBundle() + } + } + + val params: ManageChildFragmentArgs by lazy { ManageChildFragmentArgs.fromBundle(arguments!!) } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + binding.title = getString(R.string.create_category_title) + binding.editText.hint = getString(R.string.create_category_hint) + } + + override fun go() { + val text = binding.editText.text.toString() + val auth = getActivityViewModel(activity!!) + + if (text.isNotEmpty()) { + auth.tryDispatchParentAction( + CreateCategoryAction( + categoryId = IdGenerator.generateId(), + title = text, + childId = params.childId + ) + ) + } + + dismiss() + } + + fun show(manager: FragmentManager) { + showSafe(manager, DIALOG_TAG) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/primarydevice/PrimaryDeviceView.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/primarydevice/PrimaryDeviceView.kt new file mode 100644 index 0000000..fa5b4e5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/primarydevice/PrimaryDeviceView.kt @@ -0,0 +1,99 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.primarydevice + +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.Observer +import io.timelimit.android.databinding.PrimaryDeviceViewBinding +import io.timelimit.android.livedata.mergeLiveData +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.sync.actions.SetRelaxPrimaryDeviceAction +import io.timelimit.android.sync.network.UpdatePrimaryDeviceRequestType +import io.timelimit.android.ui.main.ActivityViewModel + +object PrimaryDeviceView { + fun bind( + view: PrimaryDeviceViewBinding, + childId: String, + logic: AppLogic, + fragmentManager: FragmentManager, + lifecycleOwner: LifecycleOwner, + auth: ActivityViewModel + ) { + val userEntry = logic.database.user().getUserByIdLive(childId) + val ownDeviceId = logic.deviceId + val ownDeviceUser = logic.deviceUserId + val childDevices = logic.database.device().getDevicesByUserId(childId) + + ownDeviceUser.observe(lifecycleOwner, Observer { view.canAssignThisDevice = it == childId && childId.isNotEmpty() }) + + mergeLiveData(ownDeviceId, childDevices, userEntry, logic.fullVersion.isLocalMode).observe(lifecycleOwner, Observer { + (ownDeviceId, childDevices, userEntry, isLocalMode) -> + + if (ownDeviceId != null && childDevices != null && userEntry != null && isLocalMode != null) { + if (isLocalMode) { + view.status = PrimaryDeviceStatus.LocalMode + } else { + val currentDeviceEntry = childDevices.find { device -> device.id == userEntry.currentDevice } + + if (currentDeviceEntry == null) { + view.status = PrimaryDeviceStatus.NoDeviceSelected + } else if (currentDeviceEntry.id == ownDeviceId) { + view.status = PrimaryDeviceStatus.ThisDeviceSelected + } else { + view.status = PrimaryDeviceStatus.OtherDeviceSelected + view.primaryDeviceTitle = currentDeviceEntry.name + } + } + } + }) + + userEntry.observe(lifecycleOwner, Observer { + val checkboxStatus = it?.relaxPrimaryDevice ?: false + + view.relaxPrimaryDeviceCheckbox.setOnCheckedChangeListener { _, _ -> } + view.relaxPrimaryDeviceCheckbox.isChecked = checkboxStatus + view.relaxPrimaryDeviceCheckbox.setOnCheckedChangeListener { _, isChecked -> + if (isChecked != checkboxStatus) { + if (!auth.tryDispatchParentAction( + SetRelaxPrimaryDeviceAction( + userId = childId, + relax = isChecked + ) + )) { + view.relaxPrimaryDeviceCheckbox.isChecked = checkboxStatus + } + } + } + }) + + view.btnAssign.setOnClickListener { _ -> + UpdatePrimaryDeviceDialogFragment.newInstance(UpdatePrimaryDeviceRequestType.SetThisDevice).show(fragmentManager) + } + + view.btnUnassign.setOnClickListener { _ -> + UpdatePrimaryDeviceDialogFragment.newInstance(UpdatePrimaryDeviceRequestType.UnsetThisDevice).show(fragmentManager) + } + } +} + +enum class PrimaryDeviceStatus { + LocalMode, + NoDeviceSelected, + OtherDeviceSelected, + ThisDeviceSelected +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/primarydevice/UpdatePrimaryDeviceDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/primarydevice/UpdatePrimaryDeviceDialogFragment.kt new file mode 100644 index 0000000..7b19fc2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/primarydevice/UpdatePrimaryDeviceDialogFragment.kt @@ -0,0 +1,72 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.primarydevice + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.databinding.UpdatePrimaryDeviceDialogBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.sync.network.UpdatePrimaryDeviceRequestType + +class UpdatePrimaryDeviceDialogFragment: BottomSheetDialogFragment() { + companion object { + private const val ACTION_TYPE = "a" + private const val DIALOG_TAG = "upddf" + + fun newInstance(type: UpdatePrimaryDeviceRequestType) = UpdatePrimaryDeviceDialogFragment().apply { + arguments = Bundle().apply { + putSerializable(ACTION_TYPE, type) + } + } + } + + private val action: UpdatePrimaryDeviceRequestType by lazy { + arguments!!.getSerializable(ACTION_TYPE) as UpdatePrimaryDeviceRequestType + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = UpdatePrimaryDeviceDialogBinding.inflate(inflater, container, false) + val model = ViewModelProviders.of(this).get(UpdatePrimaryDeviceModel::class.java) + + model.start(action) + + model.status.observe(this, Observer { status -> + when (status) { + FailedGeneral -> binding.flipper.displayedChild = 0 + is FailedUserAssignedToOtherDevice -> { + binding.otherDeviceTitle = status.deviceTitle + binding.flipper.displayedChild = 1 + } + FailedPremium -> binding.flipper.displayedChild = 2 + WaitingForSync -> binding.flipper.displayedChild = 3 + Updating -> binding.flipper.displayedChild = 4 + Success -> dismissAllowingStateLoss() + }.let { } + }) + + return binding.root + } + + fun show(fragmentManager: FragmentManager) { + showSafe(fragmentManager, DIALOG_TAG) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/child/primarydevice/UpdatePrimaryDeviceModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/primarydevice/UpdatePrimaryDeviceModel.kt new file mode 100644 index 0000000..7d20301 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/primarydevice/UpdatePrimaryDeviceModel.kt @@ -0,0 +1,229 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.child.primarydevice + +import android.app.Application +import android.util.Log +import android.widget.Toast +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.transaction +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.livedata.waitUntilValueMatches +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.network.UpdatePrimaryDeviceRequest +import io.timelimit.android.sync.network.UpdatePrimaryDeviceRequestType +import io.timelimit.android.sync.network.UpdatePrimaryDeviceResponseType +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.withContext +import java.io.IOException + +class UpdatePrimaryDeviceModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "UpdatePrimaryDevice" + + suspend fun unsetPrimaryDeviceInBackground(logic: AppLogic) { + logic.syncUtil.requestImportantSyncAndWait() + + val ownDeviceId = logic.database.config().getOwnDeviceId().waitForNullableValue()!! + val ownDeviceEntry = logic.database.device().getDeviceById(ownDeviceId).waitForNullableValue()!! + val server = logic.serverLogic.getServerConfigCoroutine() + + if (!server.hasAuthToken) { + throw IOException("has not auth token") + } + + val response = server.api.updatePrimaryDevice(UpdatePrimaryDeviceRequest( + action = UpdatePrimaryDeviceRequestType.UnsetThisDevice, + currentUserId = ownDeviceEntry.currentUserId, + deviceAuthToken = server.deviceAuthToken + )) + + if (response.status != UpdatePrimaryDeviceResponseType.Success) { + throw IOException("server reported ${response.status}") + } + + Threads.database.executeAndWait { + logic.database.transaction().use { transaction -> + val userEntry = logic.database.user().getUserByIdSync(ownDeviceEntry.currentUserId)!! + + logic.database.user().updateUserSync(userEntry.copy(currentDevice = "")) + + transaction.setSuccess() + } + } + } + } + + private val logic = DefaultAppLogic.with(application) + private val job = Job() + private val otherAssignedDevice = logic.currentDeviceLogic.otherAssignedDevice + + private val statusInternal = MutableLiveData() + private var hasStarted = false + + val status = statusInternal.castDown() + + fun start(type: UpdatePrimaryDeviceRequestType) { + if (hasStarted) { + return + } + + hasStarted = true + + runAsync { + val server = logic.serverLogic.getServerConfigCoroutine() + + if (!server.hasAuthToken) { + statusInternal.value = FailedGeneral + return@runAsync + } + + withContext(job) { + suspend fun forceSync() { + statusInternal.value = WaitingForSync + logic.syncUtil.requestImportantSyncAndWait() + } + + suspend fun tryToDoAction() { + try { + statusInternal.value = Updating + + val ownDeviceId = logic.database.config().getOwnDeviceId().waitForNullableValue()!! + val ownDeviceEntry = logic.database.device().getDeviceById(ownDeviceId).waitForNullableValue()!! + + val response = server.api.updatePrimaryDevice(UpdatePrimaryDeviceRequest( + action = type, + currentUserId = ownDeviceEntry.currentUserId, + deviceAuthToken = server.deviceAuthToken + )) + + if (response.status == UpdatePrimaryDeviceResponseType.Success) { + Threads.database.executeAndWait { + logic.database.transaction().use { transaction -> + val userEntry = logic.database.user().getUserByIdSync(ownDeviceEntry.currentUserId)!! + + logic.database.user().updateUserSync( + userEntry.copy( + currentDevice = when (type) { + UpdatePrimaryDeviceRequestType.SetThisDevice -> ownDeviceId + UpdatePrimaryDeviceRequestType.UnsetThisDevice -> "" + } + ) + ) + + transaction.setSuccess() + } + } + + Toast.makeText(getApplication(), R.string.update_primary_device_toast_success, Toast.LENGTH_SHORT).show() + statusInternal.value = Success + } else { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "failed to set primary device, server reported ${response.status}") + } + + statusInternal.value = when (response.status) { + UpdatePrimaryDeviceResponseType.RequiresFullVersion -> FailedPremium + UpdatePrimaryDeviceResponseType.AssignedToOtherDevice -> FailedUserAssignedToOtherDevice( + otherAssignedDevice.waitForNullableValue()?.name + ) + else -> FailedGeneral + } + } + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "failed to set primary device", ex) + } + + statusInternal.value = FailedGeneral + } + } + + while (true) { + forceSync() + tryToDoAction() + + if (statusInternal.value is FailedUserAssignedToOtherDevice) { + // retry when it changed + otherAssignedDevice.waitUntilValueMatches { it != null } + + // this prevents that the current device is shown as null sometimes + statusInternal.value = FailedUserAssignedToOtherDevice( + otherAssignedDevice.waitForNullableValue()?.name + ) + + // send sign out requests + val signOutRequestJob = Job() + + try { + runAsync { + withContext(signOutRequestJob) { + while (this.isActive) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "send sign out request") + } + + try { + server.api.requestSignOutAtPrimaryDevice( + deviceAuthToken = server.deviceAuthToken + ) + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "sending sign out request failed", ex) + } + } + + delay(5000) // wait 5 seconds + } + } + } + + otherAssignedDevice.waitUntilValueMatches { it == null } + } finally { + signOutRequestJob.cancel() + } + } else { + break + } + } + } + } + } + + override fun onCleared() { + super.onCleared() + + job.cancel() + } +} + +sealed class UpdatePrimaryDeviceStatus() +object WaitingForSync: UpdatePrimaryDeviceStatus() +object Updating: UpdatePrimaryDeviceStatus() +object Success: UpdatePrimaryDeviceStatus() +object FailedGeneral: UpdatePrimaryDeviceStatus() +object FailedPremium: UpdatePrimaryDeviceStatus() +class FailedUserAssignedToOtherDevice(val deviceTitle: String?): UpdatePrimaryDeviceStatus() diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/add/AddDeviceFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/add/AddDeviceFragment.kt new file mode 100644 index 0000000..d219608 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/add/AddDeviceFragment.kt @@ -0,0 +1,73 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.add + + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentAddDeviceBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.ui.main.getActivityViewModel + +class AddDeviceFragment : BottomSheetDialogFragment() { + companion object { + private const val DIALOG_TAG = "adf" + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentAddDeviceBinding.inflate(inflater, container, false) + val model = ViewModelProviders.of(this).get(AddDeviceModel::class.java) + + model.status.observe(this, Observer { + when (it) { + Initializing -> { + binding.token = null + binding.message = null + } + Failed -> { + binding.token = null + binding.message = getString(R.string.error_network) + } + is ShowingToken -> { + binding.token = it.token + binding.message = null + } + is DidAddDevice -> { + binding.token = null + binding.message = getString(R.string.add_device_success, it.deviceName) + } + TokenExpired -> { + dismissAllowingStateLoss() + } + }.let { /* require handling all paths */ } + }) + + model.init(getActivityViewModel(activity!!)) + + return binding.root + } + + fun show(fragmentManager: FragmentManager) { + showSafe(fragmentManager, DIALOG_TAG) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/add/AddDeviceModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/add/AddDeviceModel.kt new file mode 100644 index 0000000..46835c3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/add/AddDeviceModel.kt @@ -0,0 +1,123 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.add + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.waitForNonNullValue +import io.timelimit.android.livedata.waitUntilValueMatches +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.apply.ApplyActionParentDeviceAuthentication +import io.timelimit.android.sync.actions.apply.ApplyActionParentPasswordAuthentication +import io.timelimit.android.ui.main.ActivityViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull + +class AddDeviceModel(application: Application): AndroidViewModel(application) { + private val statusInternal = MutableLiveData() + private val logic = DefaultAppLogic.with(application) + private var model: ActivityViewModel? = null + private val currentDeviceList = logic.database.device().getAllDevicesLive() + private val job = Job() + private var initialized = false + + val status = statusInternal.castDown() + + fun init(model: ActivityViewModel) { + if (this.model != null) { + return + } + + this.model = model + + if (!initialized) { + initialized = true + tryQuery() + } + } + + private fun tryQuery() { + runAsync { + statusInternal.value = Initializing + + val server = logic.serverLogic.getServerConfigCoroutine() + val user = model!!.authenticatedUser.value + + if ((!server.hasAuthToken) || user == null) { + statusInternal.value = Failed + } else { + try { + val auth = user.first + + val response = when (auth) { + ApplyActionParentDeviceAuthentication -> server.api.createAddDeviceToken( + deviceAuthToken = server.deviceAuthToken, + parentUserId = "", + parentPasswordSecondHash = "device" + ) + is ApplyActionParentPasswordAuthentication -> server.api.createAddDeviceToken( + deviceAuthToken = server.deviceAuthToken, + parentUserId = auth.parentUserId, + parentPasswordSecondHash = auth.secondPasswordHash + ) + } + + statusInternal.value = ShowingToken(response.token) + + withContext(job) { + val initialDeviceList = currentDeviceList.waitForNonNullValue() + val initialDeviceIdList = initialDeviceList.map { it.id }.toSet() + + // the dialog is hidden after 5 minutes + val newDeviceList = withTimeoutOrNull(1000 * 60 * 5) { + currentDeviceList.waitUntilValueMatches { deviceList -> + deviceList?.find { !initialDeviceIdList.contains(it.id) } != null + } + } ?: emptyList() + + val newDevices = newDeviceList.filterNot { initialDeviceIdList.contains(it.id) } + val newDevice = newDevices.firstOrNull() + + if (newDevice == null) { + statusInternal.value = TokenExpired + } else { + statusInternal.value = DidAddDevice(newDevice.name) + } + } + } catch (ex: Exception) { + statusInternal.value = Failed + } + } + } + } + + override fun onCleared() { + super.onCleared() + + job.cancel() + } +} + +sealed class Status +object Initializing: Status() +object Failed: Status() +data class ShowingToken(val token: String): Status() +data class DidAddDevice(val deviceName: String): Status() +object TokenExpired: Status() diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/DeviceUninstall.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/DeviceUninstall.kt new file mode 100644 index 0000000..bf1fa36 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/DeviceUninstall.kt @@ -0,0 +1,34 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.data.model.Device +import io.timelimit.android.databinding.ManageDeviceUninstallCardBinding + +object DeviceUninstall { + fun bind( + view: ManageDeviceUninstallCardBinding, + deviceEntry: LiveData, + lifecycleOwner: LifecycleOwner + ) { + deviceEntry.observe(lifecycleOwner, Observer { + view.showMessage = it?.didReportUninstall ?: false + }) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/DontAskPasswordOnDeviceView.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/DontAskPasswordOnDeviceView.kt new file mode 100644 index 0000000..1062f0e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/DontAskPasswordOnDeviceView.kt @@ -0,0 +1,56 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.Device +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.sync.actions.SetKeepSignedInAction +import io.timelimit.android.ui.main.ActivityViewModel + +object DontAskPasswordOnDeviceView { + fun bind( + view: io.timelimit.android.databinding.DontAskPasswordOnDeviceViewBinding, + lifecycleOwner: LifecycleOwner, + deviceEntry: LiveData, + activityViewModel: ActivityViewModel + ) { + activityViewModel.database.config().getDeviceAuthTokenAsync().map { it.isNotEmpty() }.observe(lifecycleOwner, Observer { + view.showCard = it + }) + + deviceEntry.observe(lifecycleOwner, Observer { + view.arePasswordPromptsEnabled = !(it?.isUserKeptSignedIn ?: false) + }) + + view.btnEnablePromptsAgain.setOnClickListener { + runAsync { + val device = deviceEntry.waitForNullableValue() + + if (device != null) { + activityViewModel.tryDispatchParentAction(SetKeepSignedInAction( + deviceId = device.id, + keepSignedIn = false + )) + } + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/InformAboutDeviceOwnerDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/InformAboutDeviceOwnerDialogFragment.kt new file mode 100644 index 0000000..758079f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/InformAboutDeviceOwnerDialogFragment.kt @@ -0,0 +1,58 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import android.app.Dialog +import android.app.admin.DevicePolicyManager +import android.content.ComponentName +import android.content.Intent +import android.os.Build +import android.os.Bundle +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.integration.platform.android.AdminReceiver + +class InformAboutDeviceOwnerDialogFragment: DialogFragment() { + companion object { + private const val TAG = "dod" + + val shouldShow = (!BuildConfig.storeCompilant) && + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = AlertDialog.Builder(context!!, theme) + .setTitle(R.string.inform_about_device_owner_title) + .setMessage(R.string.inform_about_device_owner_text) + .setPositiveButton(R.string.inform_about_device_owner_continue) { _, _ -> + startActivity( + Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN) + .putExtra( + DevicePolicyManager.EXTRA_DEVICE_ADMIN, + ComponentName(context!!, AdminReceiver::class.java) + ) + ) + } + .setNegativeButton(R.string.generic_cancel, null) + .create() + + fun show(manager: FragmentManager) { + showSafe(manager, TAG) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceFragment.kt new file mode 100644 index 0000000..8ffb3fd --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceFragment.kt @@ -0,0 +1,360 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import android.app.admin.DevicePolicyManager +import android.content.ComponentName +import android.content.Intent +import android.os.Build +import android.os.Bundle +import android.provider.Settings +import android.text.format.DateUtils +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.AdapterView +import android.widget.ArrayAdapter +import android.widget.Toast +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import androidx.navigation.Navigation +import io.timelimit.android.R +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.NetworkTime +import io.timelimit.android.databinding.FragmentManageDeviceBinding +import io.timelimit.android.integration.platform.ProtectionLevel +import io.timelimit.android.integration.platform.android.AdminReceiver +import io.timelimit.android.livedata.* +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.logic.RealTime +import io.timelimit.android.sync.actions.SetDeviceUserAction +import io.timelimit.android.sync.actions.UpdateNetworkTimeVerificationAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.main.AuthenticationFab +import io.timelimit.android.ui.main.FragmentWithCustomTitle +import io.timelimit.android.ui.manage.device.manage.defaultuser.ManageDeviceDefaultUser + +class ManageDeviceFragment : Fragment(), FragmentWithCustomTitle { + private val activity: ActivityViewModelHolder by lazy { getActivity() as ActivityViewModelHolder } + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val auth: ActivityViewModel by lazy { activity.getActivityViewModel() } + private val args: ManageDeviceFragmentArgs by lazy { ManageDeviceFragmentArgs.fromBundle(arguments!!) } + private val deviceEntry: LiveData by lazy { + logic.database.device().getDeviceById(args.deviceId) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val navigation = Navigation.findNavController(container!!) + val binding = FragmentManageDeviceBinding.inflate(inflater, container, false) + val userEntries = logic.database.user().getAllUsersLive() + + DeviceUninstall.bind( + view = binding.uninstall, + deviceEntry = deviceEntry, + lifecycleOwner = this + ) + + RemoveDevice.bind( + view = binding.removeDevice, + activityViewModel = auth, + fragmentManager = fragmentManager!!, + deviceId = args.deviceId, + database = logic.database, + lifecycleOwner = this + ) + + ManageDeviceManipulation.bindView( + binding = binding.manageManipulation, + deviceEntry = deviceEntry, + lifecycleOwner = this, + activityViewModel = auth + ) + + DontAskPasswordOnDeviceView.bind( + view = binding.dontAskPasswordAtDevice, + lifecycleOwner = this, + deviceEntry = deviceEntry, + activityViewModel = auth + ) + + ManageSendDeviceConnected.bind( + binding = binding.sendDeviceConnected, + deviceEntry = deviceEntry, + auth = auth, + lifecycleOwner = this + ) + + val userSpinnerAdapter = ArrayAdapter(context!!, android.R.layout.simple_spinner_item).apply { + setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) + } + + // auth + AuthenticationFab.manageAuthenticationFab( + fab = binding.fab, + shouldHighlight = auth.shouldHighlightAuthenticationButton, + authenticatedUser = auth.authenticatedUser, + fragment = this, + doesSupportAuth = liveDataFromValue(true) + ) + + // label, id + val userListItems = ArrayList>() + + fun bindUserListItems() { + userSpinnerAdapter.clear() + userSpinnerAdapter.addAll(userListItems.map { it.first }) + userSpinnerAdapter.notifyDataSetChanged() + } + + fun bindUserListSelection() { + val selectedUserId = deviceEntry.value?.currentUserId + + val selectedIndex = userListItems.indexOfFirst { it.second == selectedUserId } + + if (selectedIndex != -1) { + binding.userSpinner.setSelection(selectedIndex) + } else { + val fallbackSelectedIndex = userListItems.indexOfFirst { it.second == "" } + + if (fallbackSelectedIndex != -1) { + binding.userSpinner.setSelection(fallbackSelectedIndex) + } + } + } + + binding.handlers = object: ManageDeviceFragmentHandlers { + override fun changeNetworkTimeVerification(newValue: NetworkTime) { + val device = deviceEntry.value + + if (device != null) { + if (device.networkTime != newValue) { + if (!auth.tryDispatchParentAction( + UpdateNetworkTimeVerificationAction( + deviceId = device.id, + mode = newValue + ) + )) { + // revert it + + binding.networkTimeVerification = device.networkTime + } + } + } + } + + override fun openUsageStatsSettings() { + if (binding.isThisDevice == true) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + startActivity( + Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } + } + } + + override fun openNotificationAccessSettings() { + if (binding.isThisDevice == true) { + try { + startActivity( + Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS") + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } catch (ex: Exception) { + Toast.makeText( + context, + R.string.error_general, + Toast.LENGTH_SHORT + ).show() + } + } + } + + override fun manageDeviceAdmin() { + if (binding.isThisDevice == true) { + val protectionLevel = logic.platformIntegration.getCurrentProtectionLevel() + + if (protectionLevel == ProtectionLevel.None) { + if (InformAboutDeviceOwnerDialogFragment.shouldShow) { + InformAboutDeviceOwnerDialogFragment().show(fragmentManager!!) + } else { + startActivity( + Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN) + .putExtra( + DevicePolicyManager.EXTRA_DEVICE_ADMIN, + ComponentName(context!!, AdminReceiver::class.java) + ) + ) + } + } else { + startActivity( + Intent(Settings.ACTION_SECURITY_SETTINGS) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } + } + } + + override fun editDeviceTitle() { + if (auth.requestAuthenticationOrReturnTrue()) { + UpdateDeviceTitleDialogFragment.newInstance(args.deviceId).show(fragmentManager!!) + } + } + + override fun showAuthenticationScreen() { + activity.showAuthenticationScreen() + } + } + + binding.userSpinner.adapter = userSpinnerAdapter + binding.userSpinner.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { + val item = userListItems[position] + val userId = item.second + val device = deviceEntry.value + + if (device != null) { + if (device.currentUserId != userId) { + if (!auth.tryDispatchParentAction( + SetDeviceUserAction( + deviceId = args.deviceId, + userId = userId + ) + )) { + bindUserListSelection() + } + } + } + } + + override fun onNothingSelected(parent: AdapterView<*>?) { + // nothing to do + } + } + + deviceEntry.observe(this, Observer { + device -> + + if (device == null) { + navigation.popBackStack() + } else { + val now = RealTime.newInstance() + logic.realTimeLogic.getRealTime(now) + + binding.deviceTitle = device.name + binding.modelString = device.model + binding.addedAtString = getString(R.string.manage_device_added_at, DateUtils.getRelativeTimeSpanString( + device.addedAt, + now.timeInMillis, + DateUtils.HOUR_IN_MILLIS + + )) + binding.networkTimeVerification = device.networkTime + binding.usageStatsAccess = device.currentUsageStatsPermission + binding.notificationAccessPermission = device.currentNotificationAccessPermission + binding.protectionLevel = device.currentProtectionLevel + binding.didAppDowngrade = device.currentAppVersion < device.highestAppVersion + } + }) + + mergeLiveData(deviceEntry, userEntries).observe(this, Observer { + val (device, users) = it!! + + if (device != null && users != null) { + userListItems.clear() + userListItems.addAll( + users.map { user -> Pair(user.name, user.id) } + ) + userListItems.add(Pair(getString(R.string.manage_device_current_user_none), "")) + + bindUserListItems() + bindUserListSelection() + } + }) + + val isThisDevice = logic.deviceId.map { ownDeviceId -> ownDeviceId == args.deviceId }.ignoreUnchanged() + + isThisDevice.observe(this, Observer { + binding.isThisDevice = it + }) + + ManageDeviceIntroduction.bind( + view = binding.introduction, + database = logic.database, + lifecycleOwner = this + ) + + val userEntry = deviceEntry.switchMap { + device -> + + userEntries.map { users -> + users.find { user -> user.id == device?.currentUserId } + } + } + + UsageStatsAccessRequiredAndMissing.bind( + view = binding.usageStatsAccessMissing, + lifecycleOwner = this, + device = deviceEntry, + user = userEntry + ) + + ManageDeviceTroubleshooting.bind( + view = binding.troubleshootingView, + userEntry = userEntry, + lifecycleOwner = this + ) + + ManageDeviceDefaultUser.bind( + view = binding.defaultUser, + device = deviceEntry, + users = userEntries, + lifecycleOwner = this, + isThisDevice = isThisDevice, + auth = auth, + fragmentManager = fragmentManager!! + ) + + ManageDeviceRebootManipulationView.bind( + view = binding.deviceRebootManipulation, + lifecycleOwner = this, + deviceEntry = deviceEntry, + auth = auth + ) + + return binding.root + } + + override fun onResume() { + super.onResume() + + logic.backgroundTaskLogic.syncDeviceStatusAsync() + } + + override fun getCustomTitle() = deviceEntry.map { it?.name } +} + +interface ManageDeviceFragmentHandlers { + fun changeNetworkTimeVerification(newValue: NetworkTime) + fun openUsageStatsSettings() + fun openNotificationAccessSettings() + fun manageDeviceAdmin() + fun editDeviceTitle() + fun showAuthenticationScreen() +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceIntroduction.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceIntroduction.kt new file mode 100644 index 0000000..570e54b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceIntroduction.kt @@ -0,0 +1,39 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.Observer +import io.timelimit.android.async.Threads +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.HintsToShow +import io.timelimit.android.databinding.FragmentManageDeviceIntroductionBinding + +object ManageDeviceIntroduction { + fun bind( + view: FragmentManageDeviceIntroductionBinding, + database: Database, + lifecycleOwner: LifecycleOwner + ) { + database.config().wereHintsShown(HintsToShow.DEVICE_SCREEN_INTRODUCTION).observe(lifecycleOwner, Observer { view.showHint = !it }) + + view.confirmBtn.setOnClickListener { + Threads.database.submit { + database.config().setHintsShownSync(HintsToShow.DEVICE_SCREEN_INTRODUCTION) + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceManipulation.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceManipulation.kt new file mode 100644 index 0000000..97fafd2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceManipulation.kt @@ -0,0 +1,106 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import android.widget.CompoundButton +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.data.model.Device +import io.timelimit.android.databinding.ManageDeviceManipulationViewBinding +import io.timelimit.android.sync.actions.IgnoreManipulationAction +import io.timelimit.android.ui.main.ActivityViewModel + +object ManageDeviceManipulation { + fun bindView( + binding: ManageDeviceManipulationViewBinding, + deviceEntry: LiveData, + lifecycleOwner: LifecycleOwner, + activityViewModel: ActivityViewModel + ) { + deviceEntry.observe(lifecycleOwner, Observer { + device -> + + binding.hasTriedManipulatingDeviceAdmin = device?.manipulationTriedDisablingDeviceAdmin ?: false + binding.hasManipulatedAppVersion = device?.manipulationOfAppVersion ?: false + binding.hasManipulatedDeviceAdmin = device?.manipulationOfProtectionLevel ?: false + binding.hasManipulatedUsageStatsAccess = device?.manipulationOfUsageStats ?: false + binding.hasManipulatedNotificationAccess = device?.manipulationOfNotificationAccess ?: false + binding.hasManipulationReboot = device?.manipulationDidReboot ?: false + binding.hasHadManipulation = (device?.hadManipulation ?: false) and (! (device?.hasActiveManipulationWarning ?: false)) + binding.hasAnyManipulation = device?.hasAnyManipulation ?: false + }) + + val revertCheckedListener = object: CompoundButton.OnCheckedChangeListener { + override fun onCheckedChanged(checkbox: CompoundButton, isChecked: Boolean) { + if (isChecked) { + if (!activityViewModel.requestAuthenticationOrReturnTrue()) { + checkbox.isChecked = false + } + } + } + } + + val checkboxes = listOf( + binding.appVersionCheckbox, + binding.deviceAdminDisableAttemptCheckbox, + binding.deviceAdminDisabledCheckbox, + binding.usageAccessCheckbox, + binding.notificationAccessCheckbox, + binding.rebootCheckbox, + binding.hadManipulationCheckbox + ) + + checkboxes.forEach { checkbox -> checkbox.setOnCheckedChangeListener(revertCheckedListener) } + + binding.ignoreWarningsBtn.setOnClickListener { + val device = deviceEntry.value + + if (device == null) { + return@setOnClickListener + } + + val action = IgnoreManipulationAction( + ignoreUsageStatsAccessManipulation = binding.usageAccessCheckbox.isChecked && binding.hasManipulatedUsageStatsAccess == true, + ignoreNotificationAccessManipulation = binding.notificationAccessCheckbox.isChecked && binding.hasManipulatedNotificationAccess == true, + ignoreDeviceAdminManipulationAttempt = binding.deviceAdminDisableAttemptCheckbox.isChecked && binding.hasTriedManipulatingDeviceAdmin == true, + ignoreDeviceAdminManipulation = binding.deviceAdminDisabledCheckbox.isChecked && binding.hasManipulatedDeviceAdmin == true, + ignoreAppDowngrade = binding.appVersionCheckbox.isChecked && binding.hasManipulatedAppVersion == true, + ignoreReboot = binding.rebootCheckbox.isChecked && binding.hasManipulationReboot == true, + ignoreHadManipulation = binding.hadManipulationCheckbox.isChecked || ( + device.hadManipulation and device.hasActiveManipulationWarning + ), + deviceId = device.id + ) + + if (action.isEmpty) { + Snackbar.make( + binding.root, + R.string.manage_device_manipulation_toast_nothing_selected, + Snackbar.LENGTH_SHORT + ).show() + + return@setOnClickListener + } + + if (activityViewModel.tryDispatchParentAction(action)) { + checkboxes.forEach { checkbox -> checkbox.isChecked = false } + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceRebootManipulationView.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceRebootManipulationView.kt new file mode 100644 index 0000000..7855360 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceRebootManipulationView.kt @@ -0,0 +1,55 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.data.model.Device +import io.timelimit.android.databinding.ManageDeviceRebootManipulationViewBinding +import io.timelimit.android.sync.actions.SetConsiderRebootManipulationAction +import io.timelimit.android.ui.main.ActivityViewModel + +object ManageDeviceRebootManipulationView { + fun bind( + view: ManageDeviceRebootManipulationViewBinding, + deviceEntry: LiveData, + lifecycleOwner: LifecycleOwner, + auth: ActivityViewModel + ) { + deviceEntry.observe(lifecycleOwner, Observer { device -> + val checked = device?.considerRebootManipulation ?: false + + view.checkbox.setOnCheckedChangeListener { _, _ -> } + view.checkbox.isChecked = checked + view.checkbox.setOnCheckedChangeListener { _, isChecked -> + if (isChecked != checked) { + if ( + device != null && + !auth.tryDispatchParentAction( + SetConsiderRebootManipulationAction( + deviceId = device.id, + considerRebootManipulation = isChecked + ) + ) + ) { + view.checkbox.isChecked = checked + } + } + } + }) + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceTroubleshooting.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceTroubleshooting.kt new file mode 100644 index 0000000..6c2cdfc --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceTroubleshooting.kt @@ -0,0 +1,41 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import android.text.method.LinkMovementMethod +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.ManageDeviceTroubleshootingViewBinding + +object ManageDeviceTroubleshooting { + fun bind( + view: ManageDeviceTroubleshootingViewBinding, + userEntry: LiveData, + lifecycleOwner: LifecycleOwner + ) { + view.bateryOptimizationsText.movementMethod = LinkMovementMethod.getInstance() + + userEntry.observe(lifecycleOwner, Observer { + val isChild = it?.type == UserType.Child + + view.showBatteryOptimizations = isChild + view.showNoChildUser = !isChild + }) + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageSendDeviceConnected.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageSendDeviceConnected.kt new file mode 100644 index 0000000..a1791b3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageSendDeviceConnected.kt @@ -0,0 +1,68 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.data.model.Device +import io.timelimit.android.livedata.mergeLiveData +import io.timelimit.android.sync.actions.SetSendDeviceConnected +import io.timelimit.android.ui.main.ActivityViewModel + +object ManageSendDeviceConnected { + fun bind( + binding: io.timelimit.android.databinding.ManageSendDeviceConnectedBinding, + auth: ActivityViewModel, + deviceEntry: LiveData, + lifecycleOwner: LifecycleOwner + ) { + val ownDeviceIdLive = auth.logic.deviceId + + mergeLiveData(ownDeviceIdLive, deviceEntry).observe(lifecycleOwner, Observer { (ownDeviceId, device) -> + binding.isThisDevice = ownDeviceId == device?.id && device?.id != null + }) + + auth.database.config().getDeviceAuthTokenAsync().observe(lifecycleOwner, Observer { + binding.isConnectedMode = it.isNotEmpty() + }) + + deviceEntry.observe(lifecycleOwner, Observer { + val currentStatus = it?.showDeviceConnected ?: false + + binding.checkbox.setOnCheckedChangeListener { _, _ -> /* ignore */ } + binding.checkbox.isChecked = currentStatus + + binding.checkbox.setOnCheckedChangeListener { _, isChecked -> + if (isChecked != currentStatus) { + if ( + it != null && + auth.tryDispatchParentAction( + SetSendDeviceConnected( + deviceId = it.id, + enable = isChecked + ) + ) + ) { + // nothing to do + } else { + binding.checkbox.isChecked = currentStatus + } + } + } + }) + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/RemoveDevice.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/RemoveDevice.kt new file mode 100644 index 0000000..b671e63 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/RemoveDevice.kt @@ -0,0 +1,46 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.Observer +import io.timelimit.android.data.Database +import io.timelimit.android.databinding.RemoveDeviceViewBinding +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.manage.device.remove.ConfirmRemoveDeviceDialogFragment +import io.timelimit.android.ui.manage.device.remove.RemoveDeviceProgressDialog + +object RemoveDevice { + fun bind( + view: RemoveDeviceViewBinding, + activityViewModel: ActivityViewModel, + fragmentManager: FragmentManager, + deviceId: String, + database: Database, + lifecycleOwner: LifecycleOwner + ) { + view.removeBtn.setOnClickListener { + if (activityViewModel.requestAuthenticationOrReturnTrue()) { + ConfirmRemoveDeviceDialogFragment.newInstance(deviceId).show(fragmentManager) + } + } + + database.config().getDeviceAuthTokenAsync().observe(lifecycleOwner, Observer { + view.isLocalMode = it.isEmpty() + }) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/UpdateDeviceTitleDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/UpdateDeviceTitleDialogFragment.kt new file mode 100644 index 0000000..759df43 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/UpdateDeviceTitleDialogFragment.kt @@ -0,0 +1,105 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import android.os.Bundle +import android.view.View +import android.widget.Toast +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.UserType +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.UpdateDeviceNameAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.util.EditTextBottomSheetDialog + +class UpdateDeviceTitleDialogFragment: EditTextBottomSheetDialog() { + companion object { + private const val TAG = "UpdateDeviceTitleDialogFragment" + private const val EXTRA_DEVICE_ID = "deviceId" + + fun newInstance(deviceId: String) = UpdateDeviceTitleDialogFragment().apply { + arguments = Bundle().apply { + putString(EXTRA_DEVICE_ID, deviceId) + } + } + } + + val deviceId: String by lazy { arguments!!.getString(EXTRA_DEVICE_ID) } + val auth: ActivityViewModel by lazy { + (activity as ActivityViewModelHolder).getActivityViewModel() + } + val deviceEntry: LiveData by lazy { + DefaultAppLogic.with(context!!).database.device().getDeviceById(deviceId) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + deviceEntry.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + if (savedInstanceState == null) { + runAsync { + deviceEntry.waitForNullableValue()?.let { deviceEntry -> + binding.editText.setText(deviceEntry.name) + didInitField() + } + } + } + + binding.title = getString(R.string.manage_device_rename) + } + + override fun go() { + val newDeviceTitle = binding.editText.text.toString() + + if (newDeviceTitle.isBlank()) { + Toast.makeText(context!!, R.string.manage_device_rename_toast_empty, Toast.LENGTH_SHORT).show() + } else { + if (auth.tryDispatchParentAction( + UpdateDeviceNameAction( + deviceId = deviceId, + name = newDeviceTitle + ) + )) { + dismiss() + } + } + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/UsageStatsAccessRequiredAndMissing.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/UsageStatsAccessRequiredAndMissing.kt new file mode 100644 index 0000000..772aba7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/UsageStatsAccessRequiredAndMissing.kt @@ -0,0 +1,39 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage + +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.UsageStatsPermissionRequiredAndMissingBinding +import io.timelimit.android.integration.platform.RuntimePermissionStatus +import io.timelimit.android.livedata.mergeLiveData + +object UsageStatsAccessRequiredAndMissing { + fun bind( + view: UsageStatsPermissionRequiredAndMissingBinding, + user: LiveData, + device: LiveData, + lifecycleOwner: LifecycleOwner + ) { + mergeLiveData(user, device).observe(lifecycleOwner, Observer { (user, device) -> + view.showMessage = user?.type == UserType.Child && device?.currentUsageStatsPermission == RuntimePermissionStatus.NotGranted + }) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/defaultuser/ManageDeviceDefaultUser.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/defaultuser/ManageDeviceDefaultUser.kt new file mode 100644 index 0000000..43ac7da --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/defaultuser/ManageDeviceDefaultUser.kt @@ -0,0 +1,102 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage.defaultuser + +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.User +import io.timelimit.android.databinding.ManageDeviceDefaultUserBinding +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.sync.actions.SignOutAtDeviceAction +import io.timelimit.android.sync.actions.apply.ApplyActionUtil +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.payment.RequiresPurchaseDialogFragment +import io.timelimit.android.util.TimeTextUtil + +object ManageDeviceDefaultUser { + fun bind( + view: ManageDeviceDefaultUserBinding, + users: LiveData>, + lifecycleOwner: LifecycleOwner, + device: LiveData, + isThisDevice: LiveData, + auth: ActivityViewModel, + fragmentManager: FragmentManager + ) { + val context = view.root.context + + device.switchMap { deviceEntry -> + users.map { users -> + deviceEntry to users.find { it.id == deviceEntry?.defaultUser } + } + }.observe(lifecycleOwner, Observer { (deviceEntry, defaultUser) -> + view.hasDefaultUser = defaultUser != null + view.isAlreadyUsingDefaultUser = defaultUser != null && deviceEntry?.currentUserId == defaultUser.id + view.defaultUserTitle = defaultUser?.name + }) + + isThisDevice.observe(lifecycleOwner, Observer { + view.isCurrentDevice = it + }) + + device.observe(lifecycleOwner, Observer { deviceEntry -> + view.setDefaultUserButton.setOnClickListener { + if (deviceEntry != null && auth.requestAuthenticationOrReturnTrue()) { + SetDeviceDefaultUserDialogFragment.newInstance( + deviceId = deviceEntry.id + ).show(fragmentManager) + } + } + + view.configureAutoLogoutButton.setOnClickListener { + if (deviceEntry != null && auth.requestAuthenticationOrReturnTrue()) { + SetDeviceDefaultUserTimeoutDialogFragment + .newInstance(deviceId = deviceEntry.id) + .show(fragmentManager) + } + } + + val defaultUserTimeout = deviceEntry?.defaultUserTimeout ?: 0 + + view.isAutomaticallySwitchingToDefaultUserEnabled = defaultUserTimeout != 0 + view.defaultUserSwitchText = if (defaultUserTimeout == 0) + context.getString(R.string.manage_device_default_user_timeout_off) + else + context.getString(R.string.manage_device_default_user_timeout_on, TimeTextUtil.time(defaultUserTimeout, context)) + }) + + auth.logic.fullVersion.shouldProvideFullVersionFunctions.observe(lifecycleOwner, Observer { fullVersion -> + view.switchToDefaultUserButton.setOnClickListener { + if (fullVersion) { + runAsync { + ApplyActionUtil.applyAppLogicAction( + SignOutAtDeviceAction, + auth.logic + ) + } + } else { + RequiresPurchaseDialogFragment().show(fragmentManager) + } + } + }) + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/defaultuser/SetDeviceDefaultUserDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/defaultuser/SetDeviceDefaultUserDialogFragment.kt new file mode 100644 index 0000000..a551bba --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/defaultuser/SetDeviceDefaultUserDialogFragment.kt @@ -0,0 +1,131 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage.defaultuser + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.CheckedTextView +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.Observer +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.R +import io.timelimit.android.data.Database +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.BottomSheetSelectionListBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.SetDeviceDefaultUserAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder + +class SetDeviceDefaultUserDialogFragment: BottomSheetDialogFragment() { + companion object { + private const val EXTRA_DEVICE_ID = "deviceId" + private const val DIALOG_TAG = "sddudf" + + fun newInstance(deviceId: String) = SetDeviceDefaultUserDialogFragment().apply { + arguments = Bundle().apply { + putString(EXTRA_DEVICE_ID, deviceId) + } + } + } + + val deviceId: String by lazy { arguments!!.getString(EXTRA_DEVICE_ID) } + val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + val database: Database by lazy { logic.database } + val auth: ActivityViewModel by lazy { (activity as ActivityViewModelHolder).getActivityViewModel() } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = BottomSheetSelectionListBinding.inflate(inflater, container, false) + + binding.title = getString(R.string.manage_device_default_user_title) + + val list = binding.list + val users = database.user().getAllUsersLive() + val deviceEntry = database.device().getDeviceById(deviceId) + val currentDefaultUserId = deviceEntry.map { it?.defaultUser }.ignoreUnchanged() + + currentDefaultUserId.switchMap { v1 -> + users.map { v2 -> v1 to v2 } + }.observe(this, Observer { (defaultUserId, userList) -> + list.removeAllViews() + + fun buildRow(): CheckedTextView = LayoutInflater.from(context!!).inflate( + android.R.layout.simple_list_item_single_choice, + list, + false + ) as CheckedTextView + + val hasDefaultUser = userList.find { it.id == defaultUserId } != null + + userList.forEach { user -> + buildRow().let { row -> + row.text = user.name + row.isChecked = defaultUserId == user.id + row.setOnClickListener { + auth.tryDispatchParentAction( + SetDeviceDefaultUserAction( + deviceId = deviceId, + defaultUserId = user.id + ) + ) + + dismiss() + } + + list.addView(row) + } + } + + buildRow().let { row -> + row.setText(R.string.manage_device_default_user_selection_none) + row.isChecked = !hasDefaultUser + row.setOnClickListener { + auth.tryDispatchParentAction( + SetDeviceDefaultUserAction( + deviceId = deviceId, + defaultUserId = "" + ) + ) + + dismiss() + } + + list.addView(row) + } + }) + + return binding.root + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, DIALOG_TAG) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/manage/defaultuser/SetDeviceDefaultUserTimeoutDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/defaultuser/SetDeviceDefaultUserTimeoutDialogFragment.kt new file mode 100644 index 0000000..0f2cd18 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/defaultuser/SetDeviceDefaultUserTimeoutDialogFragment.kt @@ -0,0 +1,122 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.manage.defaultuser + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.CheckedTextView +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.R +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.BottomSheetSelectionListBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.SetDeviceDefaultUserTimeoutAction +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.util.TimeTextUtil + +class SetDeviceDefaultUserTimeoutDialogFragment: BottomSheetDialogFragment() { + companion object { + private const val EXTRA_DEVICE_ID = "deviceId" + private const val DIALOG_TAG = "sddutdf" + private val OPTIONS = listOf( + 0, + 1000 * 60, + 1000 * 60 * 5, + 1000 * 60 * 15, + 1000 * 60 * 30, + 1000 * 60 * 60 + ) + + fun newInstance(deviceId: String) = SetDeviceDefaultUserTimeoutDialogFragment().apply { + arguments = Bundle().apply { + putString(EXTRA_DEVICE_ID, deviceId) + } + } + } + + val deviceId: String by lazy { arguments!!.getString(EXTRA_DEVICE_ID) } + val deviceEntry: LiveData by lazy { + DefaultAppLogic.with(context!!).database.device().getDeviceById(deviceId) + } + val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + deviceEntry.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = BottomSheetSelectionListBinding.inflate(inflater, container, false) + binding.title = getString(R.string.manage_device_default_user_timeout_dialog_title) + val list = binding.list + + deviceEntry.observe(this, Observer { device -> + val timeout = device?.defaultUserTimeout ?: 0 + + fun buildRow(): CheckedTextView = LayoutInflater.from(context!!).inflate( + android.R.layout.simple_list_item_single_choice, + list, + false + ) as CheckedTextView + + list.removeAllViews() + + OPTIONS.forEach { option -> + buildRow().let { row -> + row.text = if (option == 0) + getString(R.string.manage_device_default_user_timeout_dialog_disable) + else + TimeTextUtil.time(option, context!!) + + row.isChecked = option == timeout + row.setOnClickListener { + auth.tryDispatchParentAction(SetDeviceDefaultUserTimeoutAction( + deviceId = deviceId, + timeout = option + )) + + dismiss() + } + + list.addView(row) + } + } + }) + + return binding.root + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, DIALOG_TAG) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/remove/ConfirmRemoveDeviceDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/remove/ConfirmRemoveDeviceDialogFragment.kt new file mode 100644 index 0000000..ba961f2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/remove/ConfirmRemoveDeviceDialogFragment.kt @@ -0,0 +1,85 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.remove + +import android.os.Bundle +import android.view.View +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.UserType +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.ui.util.ConfirmDeleteDialogFragment + +class ConfirmRemoveDeviceDialogFragment: ConfirmDeleteDialogFragment() { + companion object { + private const val DEVICE_ID = "deviceId" + private const val DIALOG_TAG = "ConfirmRemoveDeviceDialogFragment" + + fun newInstance(deviceId: String) = ConfirmRemoveDeviceDialogFragment().apply { + arguments = Bundle().apply { + putString(DEVICE_ID, deviceId) + } + } + } + + private val deviceId: String by lazy { arguments!!.getString(DEVICE_ID) } + private val appLogic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val deviceEntry: LiveData by lazy { + appLogic.database.device().getDeviceById(deviceId) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + auth.authenticatedUser.observe(this, Observer { + if (it?.second?.type != UserType.Parent) { + dismissAllowingStateLoss() + } + }) + + deviceEntry.observe(this, Observer { + if (it == null) { + dismissAllowingStateLoss() + } + }) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + deviceEntry.observe(this, Observer { + binding.text = getString(R.string.remove_device_confirmation, it?.name) + }) + } + + override fun onConfirmDeletion() { + RemoveDeviceProgressDialog + .newInstance(deviceId) + .show(fragmentManager!!) + + dismiss() + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, DIALOG_TAG) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/remove/RemoveDeviceModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/remove/RemoveDeviceModel.kt new file mode 100644 index 0000000..ddbc9b4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/remove/RemoveDeviceModel.kt @@ -0,0 +1,90 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.remove + +import android.app.Application +import android.util.Log +import android.widget.Toast +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.livedata.castDown +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.apply.ApplyActionParentDeviceAuthentication +import io.timelimit.android.sync.actions.apply.ApplyActionParentPasswordAuthentication +import io.timelimit.android.ui.main.ActivityViewModel + +class RemoveDeviceModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "RemoveDeviceModel" + } + + private val isDoneInternal = MutableLiveData().apply { value = false } + private var hasStarted = false + private val logic = DefaultAppLogic.with(application) + val isDone = isDoneInternal.castDown() + + fun start(deviceId: String, activityViewModel: ActivityViewModel) { + if (hasStarted) { + return + } + + hasStarted = true + + runAsync { + try { + val server = logic.serverLogic.getServerConfigCoroutine() + + if (!server.hasAuthToken) { + Toast.makeText(getApplication(), R.string.remove_device_local_mode, Toast.LENGTH_LONG).show() + } else { + val parent = activityViewModel.authenticatedUser.value?.first + + if (parent != null) { + try { + when (parent) { + ApplyActionParentDeviceAuthentication -> server.api.removeDevice( + deviceAuthToken = server.deviceAuthToken, + parentUserId = "", + parentPasswordSecondHash = "device", + deviceId = deviceId + ) + is ApplyActionParentPasswordAuthentication -> server.api.removeDevice( + deviceAuthToken = server.deviceAuthToken, + parentUserId = parent.parentUserId, + parentPasswordSecondHash = parent.secondPasswordHash, + deviceId = deviceId + ) + } + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "removing device failed", ex) + } + + Toast.makeText(getApplication(), R.string.error_general, Toast.LENGTH_LONG).show() + } + } else { + activityViewModel.requestAuthentication() + } + } + } finally { + isDoneInternal.value = true + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/device/remove/RemoveDeviceProgressDialog.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/remove/RemoveDeviceProgressDialog.kt new file mode 100644 index 0000000..01427f7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/remove/RemoveDeviceProgressDialog.kt @@ -0,0 +1,60 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.device.remove + +import android.app.ProgressDialog +import android.os.Bundle +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import io.timelimit.android.R +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.ui.main.ActivityViewModelHolder + +class RemoveDeviceProgressDialog: DialogFragment() { + companion object { + private const val DEVICE_ID = "deviceId" + private const val DIALOG_TAG = "RemoveDeviceProgressDialog" + + fun newInstance(deviceId: String) = RemoveDeviceProgressDialog().apply { + arguments = Bundle().apply { + putString(DEVICE_ID, deviceId) + } + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + val deviceId = arguments!!.getString(DEVICE_ID)!! + val model = ViewModelProviders.of(this).get(RemoveDeviceModel::class.java) + val activityModel = (activity as ActivityViewModelHolder).getActivityViewModel() + + model.start(deviceId, activityModel) + + model.isDone.observe(this, Observer { + dismissAllowingStateLoss() + }) + } + + override fun onCreateDialog(savedInstanceState: Bundle?) = ProgressDialog(context, theme).apply { + setMessage(getString(R.string.remove_device_progress)) + isIndeterminate = true + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, DIALOG_TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentFragment.kt new file mode 100644 index 0000000..502d5b5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentFragment.kt @@ -0,0 +1,150 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent + + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.Navigation +import io.timelimit.android.R +import io.timelimit.android.data.model.User +import io.timelimit.android.databinding.FragmentManageParentBinding +import io.timelimit.android.extensions.safeNavigate +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.main.AuthenticationFab +import io.timelimit.android.ui.main.FragmentWithCustomTitle +import io.timelimit.android.ui.manage.parent.delete.DeleteParentView + +class ManageParentFragment : Fragment(), FragmentWithCustomTitle { + private val activity: ActivityViewModelHolder by lazy { getActivity() as ActivityViewModelHolder } + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val params: ManageParentFragmentArgs by lazy { ManageParentFragmentArgs.fromBundle(arguments!!) } + private val parentUser: LiveData by lazy { logic.database.user().getParentUserByIdLive(params.parentId) } + private var wereViewsCreated = false + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentManageParentBinding.inflate(inflater, container, false) + val navigation = Navigation.findNavController(container!!) + val model = ViewModelProviders.of(this).get(ManageParentModel::class.java) + + AuthenticationFab.manageAuthenticationFab( + fab = binding.fab, + fragment = this, + doesSupportAuth = liveDataFromValue(true), + authenticatedUser = activity.getActivityViewModel().authenticatedUser, + shouldHighlight = activity.getActivityViewModel().shouldHighlightAuthenticationButton + ) + + binding.fab.setOnClickListener { activity.showAuthenticationScreen() } + + model.init( + activityViewModel = activity.getActivityViewModel(), + parentUserId = params.parentId + ) + + parentUser.observe(this, Observer { + user -> + + if (user != null) { + binding.username = user.name + binding.mail = user.mail + } + }) + + if (!wereViewsCreated) { + wereViewsCreated = true + + parentUser.observe(this, Observer { + user -> + + if (user == null) { + navigation.popBackStack() + } + }) + } + + logic.database.config().getDeviceAuthTokenAsync().map { it.isEmpty() }.observe(this, Observer { + isLocalMode -> + + binding.isUsingLocalMode = isLocalMode + }) + + DeleteParentView.bind( + view = binding.deleteParent, + lifecycleOwner = this, + model = model.deleteParentModel + ) + + ManageParentNotifications.bind( + view = binding.manageNotifications, + lifecycleOwner = this, + auth = activity.getActivityViewModel(), + userEntry = parentUser + ) + + binding.handlers = object: ManageParentFragmentHandlers { + override fun onChangePasswordClicked() { + navigation.safeNavigate( + ManageParentFragmentDirections. + actionManageParentFragmentToChangeParentPasswordFragment( + params.parentId + ), + R.id.manageParentFragment + ) + } + + override fun onRestorePasswordClicked() { + navigation.safeNavigate( + ManageParentFragmentDirections. + actionManageParentFragmentToRestoreParentPasswordFragment( + params.parentId + ), + R.id.manageParentFragment + ) + } + + override fun onLinkMailClicked() { + navigation.safeNavigate( + ManageParentFragmentDirections. + actionManageParentFragmentToLinkParentMailFragment( + params.parentId + ), + R.id.manageParentFragment + ) + } + } + + return binding.root + } + + override fun getCustomTitle() = parentUser.map { it?.name } +} + +interface ManageParentFragmentHandlers { + fun onChangePasswordClicked() + fun onRestorePasswordClicked() + fun onLinkMailClicked() +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentModel.kt new file mode 100644 index 0000000..9929f26 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentModel.kt @@ -0,0 +1,29 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.manage.parent.delete.DeleteParentModel + +class ManageParentModel(application: Application): AndroidViewModel(application) { + val deleteParentModel = DeleteParentModel(application) + + fun init(activityViewModel: ActivityViewModel, parentUserId: String) { + deleteParentModel.init(activityViewModel, parentUserId) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentNotifications.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentNotifications.kt new file mode 100644 index 0000000..dbbfb64 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentNotifications.kt @@ -0,0 +1,59 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent + +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import io.timelimit.android.data.model.User +import io.timelimit.android.databinding.ManageParentNotificationsBinding +import io.timelimit.android.sync.actions.UpdateParentNotificationFlagsAction +import io.timelimit.android.ui.main.ActivityViewModel + +object ManageParentNotifications { + fun bind( + view: ManageParentNotificationsBinding, + lifecycleOwner: LifecycleOwner, + auth: ActivityViewModel, + userEntry: LiveData + ) { + userEntry.observe(lifecycleOwner, Observer { user -> + view.hasMailAddress = user?.mail?.isNotEmpty() ?: false + + val manipulation = (user?.mailNotificationFlags ?: 0) and 1 == 1 + + view.manipulationCheckbox.setOnCheckedChangeListener { _, _ -> } + view.manipulationCheckbox.isChecked = manipulation + view.manipulationCheckbox.setOnCheckedChangeListener { _, isChecked -> + if (isChecked != manipulation) { + if ( + auth.tryDispatchParentAction( + UpdateParentNotificationFlagsAction( + parentId = user?.id!!, + flags = 1, + set = isChecked + ) + ) + ) { + // it worked + } else { + view.manipulationCheckbox.isChecked = manipulation + } + } + } + }) + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/delete/DeleteParentModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/delete/DeleteParentModel.kt new file mode 100644 index 0000000..abd10a9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/delete/DeleteParentModel.kt @@ -0,0 +1,146 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent.delete + +import android.app.Application +import android.widget.Toast +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.crypto.PasswordHashing +import io.timelimit.android.crypto.Sha512 +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.* +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.RemoveUserAction +import io.timelimit.android.ui.main.ActivityViewModel + +class DeleteParentModel(application: Application): AndroidViewModel(application) { + private val logic = DefaultAppLogic.with(application) + private val database = logic.database + + private val isWorkingInternal = MutableLiveData().apply { value = false } + private val parentUserIdLive = MutableLiveData() + private val activityViewModelLive = MutableLiveData() + + private val authenticatedUserLive = activityViewModelLive.switchMap { it.authenticatedUser } + private val isConnectedModeLive = database.config().getDeviceAuthTokenAsync().map { it.isNotEmpty() } + private val hasOtherLinkedParentsLive = parentUserIdLive.switchMap { parentUserId -> + database.user().getAllUsersLive().map { users -> + users.find { user -> + user.id != parentUserId && user.mail != "" + } != null + } + } + + private val statusIgnoringLinkingLive = parentUserIdLive.switchMap { parentUserId -> + authenticatedUserLive.map { authenticatedUser -> + if (authenticatedUser?.second?.type != UserType.Parent) { + Status.NotAuthenticated + } else { + if (authenticatedUser.second.id == parentUserId) { + Status.WrongAccount + } else { + Status.Ready + } + } + } + } + + val parentUserLive = parentUserIdLive.switchMap { parentUserId -> + database.user().getParentUserByIdLive(parentUserId) + } + + val statusLive = isConnectedModeLive.switchMap { isConnectedMode -> + if (isConnectedMode) { + hasOtherLinkedParentsLive.switchMap { hasOtherLinkedParents -> + if (hasOtherLinkedParents) { + statusIgnoringLinkingLive + } else { + liveDataFromValue(Status.LastLinked) + } + } + } else { + statusIgnoringLinkingLive + } + } + + val isWorking = isWorkingInternal.castDown() + + fun init(activityViewModel: ActivityViewModel, parentUserId: String) { + activityViewModelLive.value = activityViewModel + parentUserIdLive.value = parentUserId + } + + fun deleteUser(password: String) { + if (isWorkingInternal.value == true) { + return + } + + isWorkingInternal.value = true + + runAsync { + try { + if (statusLive.waitForNonNullValue() != Status.Ready) { + throw IllegalStateException() + } + + val userEntry = parentUserLive.waitForNullableValue() + + if (userEntry == null) { + Toast.makeText(getApplication(), R.string.error_general, Toast.LENGTH_SHORT).show() + + return@runAsync + } + + val isPasswordValid = Threads.crypto.executeAndWait { + PasswordHashing.validateSync(password, userEntry.password) + } + + if (!isPasswordValid) { + Toast.makeText(getApplication(), R.string.login_snackbar_wrong, Toast.LENGTH_SHORT).show() + + return@runAsync + } + + val authentication = Threads.crypto.executeAndWait { + val secondPasswordHash = PasswordHashing.hashSyncWithSalt(password, userEntry.secondPasswordSalt) + + Sha512.hashSync(userEntry.id + secondPasswordHash + "remove").substring(0, 16) + } + + activityViewModelLive.value!!.tryDispatchParentAction( + RemoveUserAction( + userId = userEntry.id, + authentication = authentication + ) + ) + } finally { + isWorkingInternal.value = false + } + } + } +} + +enum class Status { + LastLinked, + NotAuthenticated, + WrongAccount, + Ready +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/delete/DeleteParentView.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/delete/DeleteParentView.kt new file mode 100644 index 0000000..404216e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/delete/DeleteParentView.kt @@ -0,0 +1,55 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent.delete + +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.Observer +import io.timelimit.android.R +import io.timelimit.android.databinding.DeleteParentViewBinding +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.mergeLiveData + +object DeleteParentView { + fun bind( + view: DeleteParentViewBinding, + lifecycleOwner: LifecycleOwner, + model: DeleteParentModel + ) { + val context = view.root.context + + model.parentUserLive.observe(lifecycleOwner, Observer { user -> + view.userName = user?.name + }) + + mergeLiveData(model.statusLive, model.parentUserLive.map { it?.name }).observe(lifecycleOwner, Observer { (status, userName) -> + view.canDelete = status == Status.Ready + view.currentStatus = when (status) { + Status.LastLinked -> context.getString(R.string.manage_parent_remove_user_status_last_linked) + Status.NotAuthenticated -> context.getString(R.string.manage_parent_remove_user_status_not_authenticated, userName) + Status.WrongAccount -> context.getString(R.string.manage_parent_remove_user_status_wrong_account, userName) + Status.Ready -> context.getString(R.string.manage_parent_remove_user_status_ready, userName) + null -> "" + } + }) + + model.isWorking.observe(lifecycleOwner, Observer { view.isWorking = it }) + + view.confirmDeleteButton.setOnClickListener { + model.deleteUser(view.userPasswordField.text.toString()) + view.userPasswordField.setText("") + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/link/LinkParentMailFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/link/LinkParentMailFragment.kt new file mode 100644 index 0000000..90193a1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/link/LinkParentMailFragment.kt @@ -0,0 +1,97 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent.link + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.Navigation +import io.timelimit.android.R +import io.timelimit.android.databinding.LinkParentMailFragmentBinding +import io.timelimit.android.ui.authentication.AuthenticateByMailFragment +import io.timelimit.android.ui.authentication.AuthenticateByMailFragmentListener + +class LinkParentMailFragment : Fragment(), AuthenticateByMailFragmentListener { + companion object { + private const val PAGE_READY = 0 + private const val PAGE_LOGIN = 1 + private const val PAGE_BUSY = 2 + private const val PAGE_ALREADY_LINKED = 3 + } + + val model: LinkParentMailViewModel by lazy { + ViewModelProviders.of(this).get(LinkParentMailViewModel::class.java) + } + + val args: LinkParentMailFragmentArgs by lazy { + LinkParentMailFragmentArgs.fromBundle(arguments!!) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = LinkParentMailFragmentBinding.inflate(inflater, container, false) + val navigation = Navigation.findNavController(container!!) + + model.status.observe(this, Observer { + status -> + + when (status!!) { + LinkParentMailViewModelStatus.WaitForAuthentication -> binding.flipper.displayedChild = PAGE_LOGIN + LinkParentMailViewModelStatus.WaitForConfirmationWithPassword -> binding.flipper.displayedChild = PAGE_READY + LinkParentMailViewModelStatus.ShouldLeaveScreen -> { + navigation.popBackStack() + + null + } + LinkParentMailViewModelStatus.Working -> binding.flipper.displayedChild = PAGE_BUSY + LinkParentMailViewModelStatus.AlreadyLinked -> binding.flipper.displayedChild = PAGE_ALREADY_LINKED + }.let { } + }) + + model.mailAddress.observe(this, Observer { + mailAddress -> + + binding.mailAddress = mailAddress + binding.alreadyLinkedView.mailAddress = mailAddress + }) + + binding.linkButton.setOnClickListener { + model.doLinking( + password = binding.userPasswordField.text.toString(), + parentUserId = args.parentId + ) + } + + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + if (savedInstanceState == null) { + childFragmentManager.beginTransaction() + .replace(R.id.mail_auth_container, AuthenticateByMailFragment()) + .commit() + } + } + + override fun onLoginSucceeded(mailAuthToken: String) { + model.setMailAuthToken(mailAuthToken) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/link/LinkParentMailViewModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/link/LinkParentMailViewModel.kt new file mode 100644 index 0000000..537e4eb --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/link/LinkParentMailViewModel.kt @@ -0,0 +1,134 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent.link + +import android.app.Application +import android.util.Log +import android.widget.Toast +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.crypto.PasswordHashing +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.waitForNonNullValue +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.network.StatusOfMailAddress + +class LinkParentMailViewModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "LinkParentMailViewModel" + } + + private val logic = DefaultAppLogic.with(application) + + private val statusInternal = MutableLiveData().apply { + value = LinkParentMailViewModelStatus.WaitForAuthentication + } + private lateinit var mailAuthToken: String + private val mailAddressInternal = MutableLiveData() + + val status = statusInternal.castDown() + val mailAddress = mailAddressInternal.castDown() + + fun setMailAuthToken(mailAuthToken: String) { + if (statusInternal.value != LinkParentMailViewModelStatus.WaitForAuthentication) { + return + } + + this.mailAuthToken = mailAuthToken + statusInternal.value = LinkParentMailViewModelStatus.Working + + runAsync { + try { + val api = logic.serverLogic.getServerConfigCoroutine().api + val status = api.getStatusByMailToken(mailAuthToken) + + mailAddressInternal.value = status.mail + + statusInternal.value = when (status.status) { + StatusOfMailAddress.MailAddressWithFamily -> LinkParentMailViewModelStatus.AlreadyLinked + StatusOfMailAddress.MailAddressWithoutFamily-> LinkParentMailViewModelStatus.WaitForConfirmationWithPassword + } + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "failed to get status of the mail auth token", ex) + } + + Toast.makeText(getApplication(), R.string.error_general, Toast.LENGTH_SHORT).show() + + statusInternal.value = LinkParentMailViewModelStatus.ShouldLeaveScreen + } + } + } + + fun doLinking(password: String, parentUserId: String) { + if (statusInternal.value != LinkParentMailViewModelStatus.WaitForConfirmationWithPassword) { + return + } + + statusInternal.value = LinkParentMailViewModelStatus.Working + + runAsync { + try { + // check password locally + val userEntry = logic.database.user().getParentUserByIdLive(parentUserId).waitForNullableValue()!! + + if (userEntry.type != UserType.Parent) { + throw IllegalArgumentException() + } + + val isPasswordValid = Threads.crypto.executeAndWait { PasswordHashing.validateSync(password, userEntry.password) } + + if (!isPasswordValid) { + statusInternal.value = LinkParentMailViewModelStatus.WaitForConfirmationWithPassword + Toast.makeText(getApplication(), R.string.login_snackbar_wrong, Toast.LENGTH_SHORT).show() + return@runAsync + } + + val passwordSecondHash = Threads.crypto.executeAndWait { PasswordHashing.hashSyncWithSalt(password, userEntry.secondPasswordSalt) } + val api = logic.serverLogic.getServerConfigCoroutine().api + + api.linkParentMailAddress( + mailAuthToken = mailAuthToken, + deviceAuthToken = logic.database.config().getDeviceAuthTokenAsync().waitForNonNullValue(), + parentUserId = parentUserId, + secondPasswordHash = passwordSecondHash + ) + + statusInternal.value = LinkParentMailViewModelStatus.ShouldLeaveScreen + Toast.makeText(getApplication(), R.string.manage_parent_link_mail_screen_toast_confirm, Toast.LENGTH_SHORT).show() + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "failed to get status of the mail auth token", ex) + } + + Toast.makeText(getApplication(), R.string.error_general, Toast.LENGTH_SHORT).show() + + statusInternal.value = LinkParentMailViewModelStatus.WaitForConfirmationWithPassword + } + } + } +} + +enum class LinkParentMailViewModelStatus { + WaitForAuthentication, WaitForConfirmationWithPassword, Working, ShouldLeaveScreen, AlreadyLinked +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/password/change/ChangeParentPasswordFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/password/change/ChangeParentPasswordFragment.kt new file mode 100644 index 0000000..12e5654 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/password/change/ChangeParentPasswordFragment.kt @@ -0,0 +1,116 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent.password.change + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.Navigation +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.data.model.User +import io.timelimit.android.databinding.ChangeParentPasswordFragmentBinding +import io.timelimit.android.livedata.map +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.FragmentWithCustomTitle + +class ChangeParentPasswordFragment : Fragment(), FragmentWithCustomTitle { + val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + val params: ChangeParentPasswordFragmentArgs by lazy { + ChangeParentPasswordFragmentArgs.fromBundle(arguments!!) + } + val parentUser: LiveData by lazy { logic.database.user().getParentUserByIdLive(params.parentUserId) } + + val model: ChangeParentPasswordViewModel by lazy { + ViewModelProviders.of(this).get(ChangeParentPasswordViewModel::class.java) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val navigation = Navigation.findNavController(container!!) + val binding = ChangeParentPasswordFragmentBinding.inflate(inflater, container, false) + + parentUser.observe(this, Observer { + parentUser -> + + if (parentUser == null) { + navigation.popBackStack(R.id.overviewFragment, false) + } + }) + + binding.newPassword.passwordOk.observe(this, Observer { + isPasswordOk -> + + binding.canConfirm = isPasswordOk + }) + + binding.saveButton.setOnClickListener { + model.changePassword( + parentUserId = params.parentUserId, + oldPassword = binding.oldPassword.text.toString(), + newPassword = binding.newPassword.password.value!! + ) + } + + model.status.observe(this, Observer { + status -> + + when (status!!) { + ChangeParentPasswordViewModelStatus.Idle -> { + binding.isWorking = false + } + ChangeParentPasswordViewModelStatus.Working -> { + binding.isWorking = true + } + ChangeParentPasswordViewModelStatus.Failed -> { + Snackbar.make( + binding.saveButton, + R.string.error_general, + Snackbar.LENGTH_SHORT + ).show() + + model.confirmError() + } + ChangeParentPasswordViewModelStatus.WrongPassword -> { + Snackbar.make( + binding.saveButton, + R.string.manage_parent_change_password_toast_wrong_password, + Snackbar.LENGTH_SHORT + ).show() + + model.confirmError() + } + ChangeParentPasswordViewModelStatus.Done -> { + Toast.makeText(context!!, R.string.manage_parent_change_password_toast_success, Toast.LENGTH_SHORT).show() + + navigation.popBackStack() + + null + } + }.let { } + }) + + return binding.root + } + + override fun getCustomTitle() = parentUser.map { it?.name } +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/password/change/ChangeParentPasswordViewModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/password/change/ChangeParentPasswordViewModel.kt new file mode 100644 index 0000000..83e1a48 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/password/change/ChangeParentPasswordViewModel.kt @@ -0,0 +1,186 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent.password.change + +import android.app.Application +import android.util.Log +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.crypto.* +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.ChangeParentPasswordAction +import io.timelimit.android.sync.actions.apply.ApplyActionParentPasswordAuthentication +import io.timelimit.android.sync.actions.apply.ApplyActionUtil +import io.timelimit.android.sync.network.ParentPassword +import java.nio.charset.Charset +import javax.crypto.Cipher +import javax.crypto.spec.IvParameterSpec +import javax.crypto.spec.SecretKeySpec + +class ChangeParentPasswordViewModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "ChangeParentPassword" + } + + private val statusInternal = MutableLiveData().apply { + value = ChangeParentPasswordViewModelStatus.Idle + } + + private val logic = DefaultAppLogic.with(application) + + val status = statusInternal.castDown() + + fun confirmError() { + val value = statusInternal.value + + if (value == ChangeParentPasswordViewModelStatus.Failed || value == ChangeParentPasswordViewModelStatus.WrongPassword) { + statusInternal.value = ChangeParentPasswordViewModelStatus.Idle + } + } + + fun changePassword(parentUserId: String, oldPassword: String, newPassword: String) { + runAsync { + try { + if (statusInternal.value != ChangeParentPasswordViewModelStatus.Idle) { + return@runAsync + } + + statusInternal.value = ChangeParentPasswordViewModelStatus.Working + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "start changePassword()") + } + + val userEntry = logic.database.user().getUserByIdLive(parentUserId).waitForNullableValue() + + if (userEntry == null || userEntry.type != UserType.Parent) { + statusInternal.value = ChangeParentPasswordViewModelStatus.Failed + return@runAsync + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "got userEntry") + } + + val isOldPasswordCorrect = Threads.crypto.executeAndWait { + PasswordHashing.validateSync(oldPassword, userEntry.password) + } + + if (!isOldPasswordCorrect) { + statusInternal.value = ChangeParentPasswordViewModelStatus.WrongPassword + return@runAsync + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "old password is valid") + } + + val oldPasswordSecondHash = Threads.crypto.executeAndWait { + PasswordHashing.hashSyncWithSalt(oldPassword, userEntry.secondPasswordSalt) + } + + val newPasswordHash = ParentPassword.createCoroutine(newPassword) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "created hashs") + } + + val encryptedSecondHash = Threads.crypto.executeAndWait { + val salt = HexString.toHex(RandomBytes.randomBytes(16)) + + val keyData = Sha512.hashSync((oldPasswordSecondHash + salt).toByteArray(Charset.forName("UTF-8"))) + val keySpec = SecretKeySpec(keyData.slice(0..(AES.KEY_LENGTH_BYTES - 1)).toByteArray(), "AES") + val cipher = Cipher.getInstance("AES/CTR/NoPadding") + + cipher.init(Cipher.ENCRYPT_MODE, keySpec, IvParameterSpec(RandomBytes.randomBytes(AES.IV_LENGTH_BYTES))) + val iv = cipher.iv // 16 bytes + + val encryptedSecondHash = cipher.doFinal(newPasswordHash.parentPasswordSecondHash.toByteArray(Charset.forName("UTF-8"))) // unknown length + + // 32 chars IV, 32 chars salt, encrypted string as hex + val resultString = HexString.toHex(iv) + salt + HexString.toHex(encryptedSecondHash) + + resultString + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "encrypted data") + } + + val integrity = Threads.crypto.executeAndWait { + Sha512.hashSync(oldPasswordSecondHash + parentUserId + newPasswordHash.parentPasswordHash + newPasswordHash.parentPasswordSecondSalt + encryptedSecondHash) + } + + val action = ChangeParentPasswordAction( + parentUserId = parentUserId, + newPasswordFirstHash = newPasswordHash.parentPasswordHash, + newPasswordSecondSalt = newPasswordHash.parentPasswordSecondSalt, + newPasswordSecondHashEncrypted = encryptedSecondHash, + integrity = integrity + ) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "created action") + } + + val currentUserEntry = logic.database.user().getUserByIdLive(parentUserId).waitForNullableValue() + + if (currentUserEntry == null || currentUserEntry.password != userEntry.password || currentUserEntry.secondPasswordSalt != userEntry.secondPasswordSalt) { + statusInternal.value = ChangeParentPasswordViewModelStatus.Failed + return@runAsync + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "validated user a second time") + } + + ApplyActionUtil.applyParentAction( + action, + logic.database, + ApplyActionParentPasswordAuthentication( + parentUserId = parentUserId, + secondPasswordHash = oldPasswordSecondHash + ), + logic.syncUtil, + logic.platformIntegration + ) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "applied action") + } + + statusInternal.value = ChangeParentPasswordViewModelStatus.Done + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "changing password failed", ex) + } + + statusInternal.value = ChangeParentPasswordViewModelStatus.Failed + } + } + } +} + +enum class ChangeParentPasswordViewModelStatus { + Idle, Working, Failed, WrongPassword, Done +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/password/restore/RestoreParentPasswordFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/password/restore/RestoreParentPasswordFragment.kt new file mode 100644 index 0000000..2daf2ad --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/password/restore/RestoreParentPasswordFragment.kt @@ -0,0 +1,114 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent.password.restore + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.Fragment +import androidx.lifecycle.LiveData +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.Navigation +import io.timelimit.android.R +import io.timelimit.android.databinding.RestoreParentPasswordFragmentBinding +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.ui.authentication.AuthenticateByMailFragment +import io.timelimit.android.ui.authentication.AuthenticateByMailFragmentListener +import io.timelimit.android.ui.main.FragmentWithCustomTitle + +class RestoreParentPasswordFragment : Fragment(), AuthenticateByMailFragmentListener, FragmentWithCustomTitle { + companion object { + private const val PAGE_CHOSE_PASSWORD = 0 + private const val PAGE_AUTHENTICATE = 1 + private const val PAGE_WORKING = 2 + private const val PAGE_AUTH_INVALID = 3 + } + + val params: RestoreParentPasswordFragmentArgs by lazy { + RestoreParentPasswordFragmentArgs.fromBundle(arguments!!) + } + + val model: RestoreParentPasswordViewModel by lazy { + ViewModelProviders.of(this).get(RestoreParentPasswordViewModel::class.java) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = RestoreParentPasswordFragmentBinding.inflate(inflater, container, false) + val navigation = Navigation.findNavController(container!!) + + model.status.observe(this, Observer { + status -> + + when (status!!) { + RestoreParentPasswordStatus.WaitForAuthentication -> { + binding.flipper.displayedChild = PAGE_AUTHENTICATE + } + RestoreParentPasswordStatus.Working -> { + binding.flipper.displayedChild = PAGE_WORKING + } + RestoreParentPasswordStatus.ErrorCanNotRecover -> { + binding.flipper.displayedChild = PAGE_AUTH_INVALID + } + RestoreParentPasswordStatus.NetworkError -> { + Toast.makeText(context!!, R.string.error_network, Toast.LENGTH_SHORT).show() + + navigation.popBackStack() + + null + } + RestoreParentPasswordStatus.Done -> { + Toast.makeText(context!!, R.string.manage_parent_change_password_toast_success, Toast.LENGTH_SHORT).show() + + navigation.popBackStack() + + null + } + RestoreParentPasswordStatus.WaitForNewPassword -> { + binding.flipper.displayedChild = PAGE_CHOSE_PASSWORD + } + }.let { } + }) + + binding.newPassword.passwordOk.observe(this, Observer { + binding.changePasswordBtn.isEnabled = it!! + }) + + binding.changePasswordBtn.setOnClickListener { + model.changePassword(binding.newPassword.password.value!!) + } + + return binding.root + } + + override fun onLoginSucceeded(mailAuthToken: String) { + model.setParams(mailAuthToken, params.parentId) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + if (savedInstanceState == null) { + childFragmentManager.beginTransaction() + .replace(R.id.mail_auth_container, AuthenticateByMailFragment()) + .commit() + } + } + + override fun getCustomTitle(): LiveData = liveDataFromValue(getString(R.string.restore_parent_password_title)) +} diff --git a/app/src/main/java/io/timelimit/android/ui/manage/parent/password/restore/RestoreParentPasswordViewModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/password/restore/RestoreParentPasswordViewModel.kt new file mode 100644 index 0000000..5c56323 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/password/restore/RestoreParentPasswordViewModel.kt @@ -0,0 +1,114 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manage.parent.password.restore + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.UserType +import io.timelimit.android.data.transaction +import io.timelimit.android.livedata.castDown +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.network.ParentPassword + +class RestoreParentPasswordViewModel(application: Application): AndroidViewModel(application) { + private val logic = DefaultAppLogic.with(application) + + private val statusInternal = MutableLiveData().apply { + value = RestoreParentPasswordStatus.WaitForAuthentication + } + + private var mailAuthToken: String? = null + private var parentUserId: String? = null + + val status = statusInternal.castDown() + + fun setParams(mailAuthToken: String, parentUserId: String) { + if (this.mailAuthToken != null) { + return + } + + this.mailAuthToken = mailAuthToken + this.parentUserId = parentUserId + + statusInternal.value = RestoreParentPasswordStatus.Working + + runAsync { + try { + val api = logic.serverLogic.getServerConfigCoroutine().api + val canRecover = api.canRecoverPassword(mailAuthToken, parentUserId) + + if (canRecover) { + statusInternal.value = RestoreParentPasswordStatus.WaitForNewPassword + } else { + statusInternal.value = RestoreParentPasswordStatus.ErrorCanNotRecover + } + } catch (ex: Exception) { + statusInternal.value = RestoreParentPasswordStatus.NetworkError + } + } + } + + fun changePassword(newPassword: String) { + if (statusInternal.value != RestoreParentPasswordStatus.WaitForNewPassword) { + return + } + + statusInternal.value = RestoreParentPasswordStatus.Working + + runAsync { + try { + val parentPassword = ParentPassword.createCoroutine(newPassword) + val api = logic.serverLogic.getServerConfigCoroutine().api + + api.recoverPasswordByMailToken(mailAuthToken!!, parentPassword) + + // update the local database to make the new password work directly + Threads.database.executeAndWait { + logic.database.transaction().use { + transaction -> + + val user = logic.database.user().getUserByIdSync(parentUserId!!) + + if (user!!.type != UserType.Parent) { + throw IllegalStateException() + } + + logic.database.user().updateUserSync( + user.copy( + password = parentPassword.parentPasswordHash, + secondPasswordSalt = parentPassword.parentPasswordSecondSalt + ) + ) + + transaction.setSuccess() + } + } + + statusInternal.value = RestoreParentPasswordStatus.Done + } catch (ex: Exception) { + statusInternal.value = RestoreParentPasswordStatus.NetworkError + } + } + } +} + +enum class RestoreParentPasswordStatus { + WaitForAuthentication, ErrorCanNotRecover, WaitForNewPassword, Working, NetworkError, Done +} diff --git a/app/src/main/java/io/timelimit/android/ui/manipulation/UnlockAfterManipulationActivity.kt b/app/src/main/java/io/timelimit/android/ui/manipulation/UnlockAfterManipulationActivity.kt new file mode 100644 index 0000000..86850ce --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manipulation/UnlockAfterManipulationActivity.kt @@ -0,0 +1,85 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.manipulation + +import android.os.Build +import android.os.Bundle +import android.view.WindowManager +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.data.model.UserType +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.login.NewLoginFragment +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder +import kotlinx.android.synthetic.main.activity_unlock_after_manipulation.* + +class UnlockAfterManipulationActivity : AppCompatActivity(), ActivityViewModelHolder { + private val model: ActivityViewModel by lazy { + ViewModelProviders.of(this).get(ActivityViewModel::class.java) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_unlock_after_manipulation) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + startLockTask() + } else { + window.addFlags( + WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or + WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or + WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON + ) + } + + model.authenticatedUser.observe(this, Observer { + user -> + + if (user != null && user.second.type == UserType.Parent) { + onAuthSuccess() + } + }) + + auth_btn.setOnClickListener { showAuthenticationScreen() } + } + + override fun showAuthenticationScreen() { + NewLoginFragment().showSafe(supportFragmentManager, "nlf") + } + + override fun getActivityViewModel() = model + + private fun onAuthSuccess() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + stopLockTask() + } + + val appLogic = DefaultAppLogic.with(this@UnlockAfterManipulationActivity) + + Threads.database.execute { + appLogic.manipulationLogic.unlockDeviceSync() + } + + appLogic.manipulationLogic.showManipulationUnlockedScreen() + + finish() + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/overview/about/AboutFragment.kt b/app/src/main/java/io/timelimit/android/ui/overview/about/AboutFragment.kt new file mode 100644 index 0000000..1737fb0 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/about/AboutFragment.kt @@ -0,0 +1,103 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.overview.about + + +import android.os.Bundle +import android.text.format.DateUtils +import android.text.method.LinkMovementMethod +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import io.timelimit.android.databinding.FragmentAboutBinding +import io.timelimit.android.livedata.mergeLiveData +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic + +class AboutFragment : Fragment() { + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val listener: AboutFragmentParentHandlers by lazy { parentFragment as AboutFragmentParentHandlers } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentAboutBinding.inflate(inflater, container, false) + + mergeLiveData( + logic.database.config().getDeviceAuthTokenAsync(), logic.database.config().getFullVersionUntilAsync() + ).observe(this, Observer { + val (deviceAuthToken, fullVersionUntil) = it!! + + if (deviceAuthToken.isNullOrEmpty()) { + binding.fullVersionStatus = FullVersionStatus.InLocalMode + } else if (fullVersionUntil != null) { + if (fullVersionUntil == 0L) { + binding.fullVersionStatus = FullVersionStatus.Expired + } else { + binding.fullVersionStatus = FullVersionStatus.Available + binding.fullVersionEndDate = DateUtils.formatDateTime( + context, + fullVersionUntil, + DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_YEAR or DateUtils.FORMAT_SHOW_WEEKDAY + ) + } + } + }) + + logic.database.config().getCustomServerUrlAsync().observe(this, Observer { + binding.customServerUrl = it + }) + + binding.handlers = object: AboutFragmentHandlers { + override fun startFullVersionPurchase() { + val status = binding.fullVersionStatus + + if (status == FullVersionStatus.Expired || status == FullVersionStatus.Available) { + listener.onShowPurchaseScreen() + } + } + } + + binding.termsText1.movementMethod = LinkMovementMethod.getInstance() + binding.termsText2.movementMethod = LinkMovementMethod.getInstance() + binding.containedSoftwareText.movementMethod = LinkMovementMethod.getInstance() + + ResetShownHints.bind( + binding = binding.resetShownHintsView, + lifecycleOwner = this, + database = logic.database + ) + + binding.errorDiagnoseCard.setOnClickListener { + listener.onShowDiagnoseScreen() + } + + return binding.root + } +} + +interface AboutFragmentHandlers { + fun startFullVersionPurchase() +} + +enum class FullVersionStatus { + InLocalMode, Available, Expired +} + +interface AboutFragmentParentHandlers { + fun onShowPurchaseScreen() + fun onShowDiagnoseScreen() +} diff --git a/app/src/main/java/io/timelimit/android/ui/overview/about/ResetShownHints.kt b/app/src/main/java/io/timelimit/android/ui/overview/about/ResetShownHints.kt new file mode 100644 index 0000000..1557cc5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/about/ResetShownHints.kt @@ -0,0 +1,40 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.overview.about + +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.Observer +import io.timelimit.android.async.Threads +import io.timelimit.android.data.Database +import io.timelimit.android.databinding.ResetShownHintsBinding + +object ResetShownHints { + fun bind( + binding: ResetShownHintsBinding, + database: Database, + lifecycleOwner: LifecycleOwner + ) { + database.config().wereAnyHintsShown().observe(lifecycleOwner, Observer { + binding.canReshowHints = it + }) + + binding.reshowHintsBtn.setOnClickListener { + Threads.database.submit { + database.config().resetShownHintsSync() + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/overview/main/MainFragment.kt b/app/src/main/java/io/timelimit/android/ui/overview/main/MainFragment.kt new file mode 100644 index 0000000..6e010e3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/main/MainFragment.kt @@ -0,0 +1,208 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.overview.main + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Observer +import androidx.navigation.NavController +import androidx.navigation.Navigation +import androidx.viewpager.widget.ViewPager +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.UserType +import io.timelimit.android.extensions.safeNavigate +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.main.AuthenticationFab +import io.timelimit.android.ui.manage.device.add.AddDeviceFragment +import io.timelimit.android.ui.overview.about.AboutFragmentParentHandlers +import io.timelimit.android.ui.overview.overview.OverviewFragmentParentHandlers +import kotlinx.android.synthetic.main.fragment_main.* + +class MainFragment : Fragment(), OverviewFragmentParentHandlers, AboutFragmentParentHandlers { + private val adapter: PagerAdapter by lazy { PagerAdapter(childFragmentManager) } + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private lateinit var navigation: NavController + private val showAuthButtonLive = MutableLiveData() + private val activity: ActivityViewModelHolder by lazy { getActivity() as ActivityViewModelHolder } + private var wereViewsCreated = false + private var didRedirectToUserScreen = false + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + navigation = Navigation.findNavController(container!!) + + return inflater.inflate(R.layout.fragment_main, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + AuthenticationFab.manageAuthenticationFab( + fab = fab, + fragment = this, + shouldHighlight = activity.getActivityViewModel().shouldHighlightAuthenticationButton, + authenticatedUser = activity.getActivityViewModel().authenticatedUser, + doesSupportAuth = showAuthButtonLive + ) + + fab.setOnClickListener { activity.showAuthenticationScreen() } + + if (!wereViewsCreated) { + wereViewsCreated = true + logic.isInitialized.switchMap { isInitialized -> + if (isInitialized) { + logic.database.config().getOwnDeviceId().map { it == null } + } else { + liveDataFromValue(false) + } + }.observe(this, Observer { shouldShowSetup -> + if (shouldShowSetup == true) { + pager.post { + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToSetupTermsFragment(), + R.id.overviewFragment + ) + } + } else { + if (savedInstanceState == null && !didRedirectToUserScreen) { + didRedirectToUserScreen = true + + runAsync { + val user = logic.deviceUserEntry.waitForNullableValue() + + if (user?.type == UserType.Child) { + if (fragmentManager?.isStateSaved == false) { + openManageChildScreen(user.id) + } + } + } + } + } + }) + } + + pager.adapter = adapter + + bottom_navigation_view.setOnNavigationItemSelectedListener { + menuItem -> + + pager.currentItem = when(menuItem.itemId) { + R.id.main_tab_overview -> 0 + R.id.main_tab_uninstall -> 1 + R.id.main_tab_about -> 2 + else -> 0 + } + + true + } + + fun updateShowFab(selectedPage: Int) { + showAuthButtonLive.value = when (selectedPage) { + 0 -> true + 1 -> !BuildConfig.storeCompilant + 2 -> false + else -> throw IllegalStateException() + } + } + + updateShowFab(pager.currentItem) + + pager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener { + override fun onPageScrollStateChanged(state: Int) { + // ignore + } + + override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { + // ignore + } + + override fun onPageSelected(position: Int) { + updateShowFab(position) + + bottom_navigation_view.selectedItemId = when(pager.currentItem) { + 0 -> R.id.main_tab_overview + 1 -> R.id.main_tab_uninstall + 2 -> R.id.main_tab_about + else -> throw IllegalStateException() + } + } + }) + } + + override fun openAddDeviceScreen() { + AddDeviceFragment().show(fragmentManager!!) + } + + override fun openAddUserScreen() { + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToAddUserFragment(), + R.id.overviewFragment + ) + } + + override fun openManageChildScreen(childId: String) { + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToManageChildFragment(childId), + R.id.overviewFragment + ) + } + + override fun openManageDeviceScreen(deviceId: String) { + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToManageDeviceFragment(deviceId), + R.id.overviewFragment + ) + } + + override fun onShowPurchaseScreen() { + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToPurchaseFragment(), + R.id.overviewFragment + ) + } + + override fun openManageParentScreen(parentId: String) { + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToManageParentFragment(parentId), + R.id.overviewFragment + ) + } + + override fun openSetupDeviceScreen() { + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToSetupDeviceFragment(), + R.id.overviewFragment + ) + } + + override fun onShowDiagnoseScreen() { + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToDiagnoseMainFragment(), + R.id.overviewFragment + ) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/overview/main/PagerAdapter.kt b/app/src/main/java/io/timelimit/android/ui/overview/main/PagerAdapter.kt new file mode 100644 index 0000000..82420b7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/main/PagerAdapter.kt @@ -0,0 +1,33 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.overview.main + +import androidx.fragment.app.FragmentManager +import androidx.fragment.app.FragmentStatePagerAdapter +import io.timelimit.android.ui.overview.about.AboutFragment +import io.timelimit.android.ui.overview.overview.OverviewFragment +import io.timelimit.android.ui.overview.uninstall.UninstallFragment + +class PagerAdapter(fragmentManager: FragmentManager): FragmentStatePagerAdapter(fragmentManager) { + override fun getCount() = 3 + + override fun getItem(position: Int) = when(position) { + 0 -> OverviewFragment() + 1 -> UninstallFragment() + 2 -> AboutFragment() + else -> throw IllegalStateException() + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/overview/overview/CanNotAddDevicesInLocalModeDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/overview/overview/CanNotAddDevicesInLocalModeDialogFragment.kt new file mode 100644 index 0000000..b867b0b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/overview/CanNotAddDevicesInLocalModeDialogFragment.kt @@ -0,0 +1,42 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.overview.overview + +import android.app.Dialog +import android.os.Bundle +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager +import io.timelimit.android.R +import io.timelimit.android.extensions.showSafe + +class CanNotAddDevicesInLocalModeDialogFragment: DialogFragment() { + companion object { + private const val DIALOG_TAG = "h" + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + return AlertDialog.Builder(context!!, theme) + .setTitle(R.string.overview_add_device) + .setMessage(R.string.overview_add_error_local_mode) + .setPositiveButton(R.string.generic_ok, null) + .create() + } + + fun show(manager: FragmentManager) { + showSafe(manager, DIALOG_TAG) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragment.kt b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragment.kt new file mode 100644 index 0000000..2c01f38 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragment.kt @@ -0,0 +1,126 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.overview.overview + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.recyclerview.widget.ItemTouchHelper +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.CoroutineFragment +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.HintsToShow +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.waitForNonNullValue +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import kotlinx.android.synthetic.main.fragment_overview.* +import kotlinx.coroutines.launch + +class OverviewFragment : CoroutineFragment() { + private val handlers: OverviewFragmentParentHandlers by lazy { parentFragment as OverviewFragmentParentHandlers } + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val model: OverviewFragmentModel by lazy { + ViewModelProviders.of(this).get(OverviewFragmentModel::class.java) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_overview, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + val adapter = OverviewFragmentAdapter() + + recycler.adapter = adapter + recycler.layoutManager = LinearLayoutManager(context!!) + + adapter.handlers = object: OverviewFragmentHandlers { + override fun onAddUserClicked() { + handlers.openAddUserScreen() + } + + override fun onDeviceClicked(device: Device) { + handlers.openManageDeviceScreen(deviceId = device.id) + } + + override fun onUserClicked(user: User) { + when (user.type) { + UserType.Child -> handlers.openManageChildScreen(childId = user.id) + UserType.Parent -> handlers.openManageParentScreen(parentId = user.id) + }.let { } + } + + override fun onAddDeviceClicked() { + launch { + if (logic.database.config().getDeviceAuthTokenAsync().waitForNonNullValue().isEmpty()) { + CanNotAddDevicesInLocalModeDialogFragment().show(fragmentManager!!) + } else if (auth.requestAuthenticationOrReturnTrue()) { + handlers.openAddDeviceScreen() + } + } + } + + override fun onFinishSetupClicked() { + handlers.openSetupDeviceScreen() + } + } + + model.listEntries.observe(this, Observer { adapter.data = it }) + + ItemTouchHelper( + object: ItemTouchHelper.Callback() { + override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { + if (adapter.data!![viewHolder.adapterPosition] == OverviewFragmentHeaderIntro) { + return makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.END) or + makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END) + } else { + return 0 + } + } + + override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder) = throw IllegalStateException() + + override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { + // remove the introduction header + Threads.database.execute { + logic.database.config().setHintsShownSync(HintsToShow.OVERVIEW_INTRODUCTION) + } + } + } + ).attachToRecyclerView(recycler) + } +} + +interface OverviewFragmentParentHandlers { + fun openAddUserScreen() + fun openAddDeviceScreen() + fun openManageDeviceScreen(deviceId: String) + fun openManageChildScreen(childId: String) + fun openManageParentScreen(parentId: String) + fun openSetupDeviceScreen() +} diff --git a/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentAdapter.kt b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentAdapter.kt new file mode 100644 index 0000000..97eaa25 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentAdapter.kt @@ -0,0 +1,257 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.overview.overview + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.* +import kotlin.properties.Delegates + +class OverviewFragmentAdapter : RecyclerView.Adapter() { + init { + setHasStableIds(true) + } + + var data: List? by Delegates.observable(null as List?) { _, _, _ -> notifyDataSetChanged() } + var handlers: OverviewFragmentHandlers? = null + + fun getItem(index: Int): OverviewFragmentItem { + return data!![index] + } + + override fun getItemId(position: Int): Long { + val item = getItem(position) + + return when (item) { + is OverviewFragmentItemDevice -> "device ${item.device.id}".hashCode().toLong() + is OverviewFragmentItemUser -> "user ${item.user.id}".hashCode().toLong() + else -> item.hashCode().toLong() + } + } + + override fun getItemCount(): Int { + val data = this.data + + if (data == null) { + return 0 + } else { + return data.size + } + } + + private fun getItemType(item: OverviewFragmentItem): OverviewFragmentViewType = when(item) { + is OverviewFragmentHeaderUsers -> OverviewFragmentViewType.Header + is OverviewFragmentHeaderDevices -> OverviewFragmentViewType.Header + is OverviewFragmentItemUser -> OverviewFragmentViewType.UserItem + is OverviewFragmentItemDevice -> OverviewFragmentViewType.DeviceItem + is OverviewFragmentActionAddUser -> OverviewFragmentViewType.AddUserItem + is OverviewFragmentActionAddDevice -> OverviewFragmentViewType.AddDeviceItem + is OverviewFragmentHeaderIntro -> OverviewFragmentViewType.Introduction + is OverviewFragmentHeaderFinishSetup -> OverviewFragmentViewType.FinishSetup + is OverviewFragmentItemMessage -> OverviewFragmentViewType.ServerMessage + } + + override fun getItemViewType(position: Int) = getItemType(getItem(position)).ordinal + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = when(viewType) { + OverviewFragmentViewType.Header.ordinal -> + HeaderViewHolder( + GenericListHeaderBinding.inflate(LayoutInflater.from(parent.context), parent, false) + ) + + OverviewFragmentViewType.UserItem.ordinal -> + UserViewHolder( + FragmentOverviewUserItemBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + + OverviewFragmentViewType.DeviceItem.ordinal -> + DeviceViewHolder( + FragmentOverviewDeviceItemBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + + OverviewFragmentViewType.AddUserItem.ordinal -> + AddUserViewHolder( + AddItemViewBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ).apply { + label = parent.context.getString(R.string.add_user_title) + + root.setOnClickListener { + handlers?.onAddUserClicked() + } + }.root + ) + + OverviewFragmentViewType.AddDeviceItem.ordinal -> AddDeviceViewHolder( + AddItemViewBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ).apply { + label = parent.context.getString(R.string.overview_add_device) + + root.setOnClickListener { + handlers?.onAddDeviceClicked() + } + }.root + ) + + OverviewFragmentViewType.Introduction.ordinal -> IntroViewHolder( + LayoutInflater.from(parent.context) + .inflate(R.layout.fragment_overview_intro, parent, false) + ) + + OverviewFragmentViewType.FinishSetup.ordinal -> FinishSetupViewHolder( + FragmentOverviewFinishSetupBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ).apply { + btnGo.setOnClickListener { handlers?.onFinishSetupClicked() } + }.root + ) + + OverviewFragmentViewType.ServerMessage.ordinal -> ServerMessageViewHolder( + FragmentOverviewServerMessageBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) + + else -> throw IllegalStateException() + } + + override fun onBindViewHolder(holder: OverviewFragmentViewHolder, position: Int) { + val item = getItem(position) + + when (item) { + is OverviewFragmentHeaderUsers -> { + if (holder !is HeaderViewHolder) { + throw IllegalStateException() + } + + holder.header.text = holder.itemView.context.getString(R.string.overview_header_users) + holder.header.executePendingBindings() + } + is OverviewFragmentHeaderDevices -> { + if (holder !is HeaderViewHolder) { + throw IllegalStateException() + } + + holder.header.text = holder.itemView.context.getString(R.string.overview_header_devices) + holder.header.executePendingBindings() + } + is OverviewFragmentItemUser -> { + if (holder !is UserViewHolder) { + throw IllegalStateException() + } + + val binding = holder.binding + + binding.username = item.user.name + binding.areTimeLimitsDisabled = item.limitsTemporarilyDisabled + binding.isTemporarilyBlocked = item.temporarilyBlocked + binding.isParent = item.user.type == UserType.Parent + binding.isChild = item.user.type == UserType.Child + + binding.card.setOnClickListener { + this.handlers?.onUserClicked(item.user) + } + + binding.executePendingBindings() + } + is OverviewFragmentItemDevice -> { + if (holder !is DeviceViewHolder) { + throw IllegalStateException() + } + + val binding = holder.binding + + binding.deviceTitle = item.device.name + binding.currentDeviceUserTitle = item.deviceUser?.name + binding.hasManipulation = item.device.hasAnyManipulation + binding.isCurrentDevice = item.isCurrentDevice + binding.isMissingRequiredPermission = item.isMissingRequiredPermission + binding.didUninstall = item.device.didReportUninstall + binding.isPasswordDisabled = item.device.isUserKeptSignedIn + binding.isConnected = item.isConnected + binding.isUsingOlderVersion = item.device.currentAppVersion < BuildConfig.VERSION_CODE + binding.executePendingBindings() + + binding.card.setOnClickListener { + this.handlers?.onDeviceClicked(item.device) + } + } + is OverviewFragmentActionAddUser -> { /* nothing to do */ } + is OverviewFragmentActionAddDevice-> { /* nothing to do */ } + is OverviewFragmentHeaderIntro -> { /* nothing to do */ } + is OverviewFragmentHeaderFinishSetup -> { /* nothing to do */ } + is OverviewFragmentItemMessage -> { + holder as ServerMessageViewHolder + + holder.binding.text = item.message + holder.binding.executePendingBindings() + } + }.let { } + } +} + +enum class OverviewFragmentViewType { + Header, + UserItem, + DeviceItem, + AddUserItem, + AddDeviceItem, + Introduction, + FinishSetup, + ServerMessage +} + +sealed class OverviewFragmentViewHolder(view: View): RecyclerView.ViewHolder(view) +class HeaderViewHolder(val header: GenericListHeaderBinding): OverviewFragmentViewHolder(header.root) +class AddUserViewHolder(view: View): OverviewFragmentViewHolder(view) +class UserViewHolder(val binding: FragmentOverviewUserItemBinding): OverviewFragmentViewHolder(binding.root) +class DeviceViewHolder(val binding: FragmentOverviewDeviceItemBinding): OverviewFragmentViewHolder(binding.root) +class AddDeviceViewHolder(view: View): OverviewFragmentViewHolder(view) +class IntroViewHolder(view: View): OverviewFragmentViewHolder(view) +class FinishSetupViewHolder(view: View): OverviewFragmentViewHolder(view) +class ServerMessageViewHolder(val binding: FragmentOverviewServerMessageBinding): OverviewFragmentViewHolder(binding.root) + +interface OverviewFragmentHandlers { + fun onAddUserClicked() + fun onAddDeviceClicked() + fun onUserClicked(user: User) + fun onDeviceClicked(device: Device) + fun onFinishSetupClicked() +} diff --git a/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentItem.kt b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentItem.kt new file mode 100644 index 0000000..5af1e69 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentItem.kt @@ -0,0 +1,34 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.overview.overview + +import io.timelimit.android.data.model.Device +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +import io.timelimit.android.integration.platform.RuntimePermissionStatus + +sealed class OverviewFragmentItem +object OverviewFragmentHeaderUsers: OverviewFragmentItem() +object OverviewFragmentHeaderDevices: OverviewFragmentItem() +data class OverviewFragmentItemDevice(val device: Device, val deviceUser: User?, val isCurrentDevice: Boolean, val isConnected: Boolean): OverviewFragmentItem() { + val isMissingRequiredPermission = deviceUser?.type == UserType.Child && device.currentUsageStatsPermission == RuntimePermissionStatus.NotGranted +} +data class OverviewFragmentItemUser(val user: User, val temporarilyBlocked: Boolean, val limitsTemporarilyDisabled: Boolean): OverviewFragmentItem() +object OverviewFragmentActionAddUser: OverviewFragmentItem() +object OverviewFragmentActionAddDevice: OverviewFragmentItem() +object OverviewFragmentHeaderIntro: OverviewFragmentItem() +object OverviewFragmentHeaderFinishSetup: OverviewFragmentItem() +data class OverviewFragmentItemMessage(val message: String): OverviewFragmentItem() \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentModel.kt b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentModel.kt new file mode 100644 index 0000000..c903c72 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentModel.kt @@ -0,0 +1,122 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.overview.overview + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import io.timelimit.android.data.model.HintsToShow +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.liveDataFromFunction +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.DefaultAppLogic + +class OverviewFragmentModel(application: Application): AndroidViewModel(application) { + private val logic = DefaultAppLogic.with(application) + + private val categoryEntries = logic.database.category().getAllCategoriesShortInfo() + private val usersWithTemporarilyDisabledLimits = logic.database.user().getAllUsersLive().switchMap { + users -> + + liveDataFromFunction { logic.realTimeLogic.getCurrentTimeInMillis() }.map { + currentTime -> + + users.map { + user -> + + user to (user.disableLimitsUntil >= currentTime) + } + } + }.ignoreUnchanged() + private val userEntries = usersWithTemporarilyDisabledLimits.switchMap { users -> + categoryEntries.map { categories -> + users.map { user -> + OverviewFragmentItemUser( + user = user.first, + limitsTemporarilyDisabled = user.second, + temporarilyBlocked = categories.find { category -> category.childId == user.first.id && category.temporarilyBlocked } != null + ) + } + } + } + + private val ownDeviceId = logic.deviceId + private val devices = logic.database.device().getAllDevicesLive() + private val devicesWithUsers = devices.switchMap { devices -> + usersWithTemporarilyDisabledLimits.map { users -> + devices.map { device -> + device to users.find { it.first.id == device.currentUserId } + } + } + } + private val deviceEntries = ownDeviceId.switchMap { thisDeviceId -> + devicesWithUsers.switchMap { devices -> + logic.websocket.connectedDevices.map { connectedDevices -> + devices.map { (device, user) -> + OverviewFragmentItemDevice( + device = device, + deviceUser = user?.first, + isCurrentDevice = device.id == thisDeviceId, + isConnected = connectedDevices.contains(device.id) + ) + } + } + } + } + + private val isNoUserAssignedLive = logic.deviceUserEntry.map { it == null }.ignoreUnchanged() + private val hasShownIntroduction = logic.database.config().wereHintsShown(HintsToShow.OVERVIEW_INTRODUCTION) + private val messageLive = logic.database.config().getServerMessage() + private val introEntries = isNoUserAssignedLive.switchMap { noUserAssigned -> + hasShownIntroduction.switchMap { hasShownIntro -> + messageLive.map { message -> + val result = mutableListOf() + + if (noUserAssigned) { + result.add(OverviewFragmentHeaderFinishSetup) + } + + if (message != null) { + result.add(OverviewFragmentItemMessage(message)) + } + + if (!hasShownIntro) { + result.add(OverviewFragmentHeaderIntro) + } + + result + } + } + } + + val listEntries = introEntries.switchMap { introEntries -> + deviceEntries.switchMap { deviceEntries -> + userEntries.map { userEntries -> + mutableListOf().apply { + addAll(introEntries) + + add(OverviewFragmentHeaderDevices) + addAll(deviceEntries) + add(OverviewFragmentActionAddDevice) + + add(OverviewFragmentHeaderUsers) + addAll(userEntries) + add(OverviewFragmentActionAddUser) + } + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/overview/uninstall/UninstallFragment.kt b/app/src/main/java/io/timelimit/android/ui/overview/uninstall/UninstallFragment.kt new file mode 100644 index 0000000..d897142 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/uninstall/UninstallFragment.kt @@ -0,0 +1,69 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.overview.uninstall + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import io.timelimit.android.BuildConfig +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.databinding.FragmentUninstallBinding +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.getActivityViewModel +import io.timelimit.android.work.ReportUninstallWorker + +class UninstallFragment : Fragment() { + private val auth: ActivityViewModel by lazy { getActivityViewModel(activity!!) } + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentUninstallBinding.inflate(inflater, container, false) + + binding.uninstall.isEnabled = binding.checkConfirm.isChecked + binding.checkConfirm.setOnCheckedChangeListener { _, isChecked -> binding.uninstall.isEnabled = isChecked } + + binding.uninstall.setOnClickListener { reset(revokePermissions = binding.checkPermissions.isChecked) } + + return binding.root + } + + private fun reset(revokePermissions: Boolean) { + if (BuildConfig.storeCompilant || auth.requestAuthenticationOrReturnTrue()) { + logic.platformIntegration.setEnableSystemLockdown(false) + + if (revokePermissions) { + logic.platformIntegration.disableDeviceAdmin() + } + + runAsync { + val server = logic.serverLogic.getServerConfigCoroutine() + + if (server.hasAuthToken) { + ReportUninstallWorker.enqueue( + deviceAuthToken = server.deviceAuthToken, + customServerUrl = server.customServerUrl + ) + } + + logic.appSetupLogic.dangerousResetApp() + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/payment/ActivityPurchaseModel.kt b/app/src/main/java/io/timelimit/android/ui/payment/ActivityPurchaseModel.kt new file mode 100644 index 0000000..75e4809 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/payment/ActivityPurchaseModel.kt @@ -0,0 +1,224 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.payment + +import android.app.Application +import android.util.Log +import android.widget.Toast +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.extensions.consumeAsync +import io.timelimit.android.extensions.startAsync +import io.timelimit.android.extensions.waitUntilReady +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.mergeLiveData +import io.timelimit.android.livedata.setTemporarily +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.network.CanDoPurchaseStatus +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.solovyev.android.checkout.* +import java.io.IOException + +class ActivityPurchaseModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "ActivityPurchaseModel" + } + + private val billing = (application as io.timelimit.android.Application).billing + private val logic = DefaultAppLogic.with(application) + private val lock = Mutex() + private val isWorkingInternal = MutableLiveData().apply { value = false } + private val hadErrorInternal = MutableLiveData().apply { value = false } + private val processPurchaseSuccessInternal = MutableLiveData().apply { value = false } + + val isWorking = isWorkingInternal.castDown() + val hadError = hadErrorInternal.castDown() + val processPurchaseSuccess = processPurchaseSuccessInternal.castDown() + val status = mergeLiveData(isWorking, hadError, processPurchaseSuccess).map { + (working, error, success) -> + + if (success != null && success) { + ActivityPurchaseModelStatus.Done + } else if (working != null && working) { + ActivityPurchaseModelStatus.Working + } else if (error != null && error) { + ActivityPurchaseModelStatus.Error + } else { + ActivityPurchaseModelStatus.Idle + } + } + + fun resetProcessPurchaseSuccess() { + processPurchaseSuccessInternal.value = false + } + + private var activityCheckout: ActivityCheckout? = null + + fun setActivityCheckout(checkout: ActivityCheckout) { + checkout.start() + + checkout.createPurchaseFlow(object: RequestListener { + override fun onError(response: Int, e: Exception) { + // ignored + } + + override fun onSuccess(result: Purchase) { + if (PurchaseIds.SKUS.contains(result.sku)) { + runAsync { + lock.withLock { + isWorkingInternal.setTemporarily(true).use { _ -> + handlePurchase(result) + } + } + } + } + } + }) + + activityCheckout = checkout + } + + fun forgetActivityCheckout() { + activityCheckout?.stop() + activityCheckout = null + } + + fun queryAndProcessPurchasesAsync() { + runAsync { + lock.withLock { + isWorkingInternal.setTemporarily(true).use { _ -> + val checkout = activityCheckout + + if (checkout != null) { + val inventory = checkout.makeInventory() + + inventory.load( + Inventory.Request.create() + .loadAllPurchases(), + object: Inventory.Callback { + override fun onLoaded(products: Inventory.Products) { + products[ProductTypes.IN_APP].purchases.forEach { purchase -> + if (PurchaseIds.SKUS.contains(purchase.sku)) { + runAsync { + handlePurchase(purchase) + } + } + } + } + } + ) + } + } + } + } + } + + private suspend fun handlePurchase(purchase: Purchase) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "handlePurchase()") + } + + try { + val server = logic.serverLogic.getServerConfigCoroutine() + + if (server.hasAuthToken) { + server.api.finishPurchaseByGooglePlay( + receipt = purchase.data, + signature = purchase.signature, + deviceAuthToken = server.deviceAuthToken + ) + } + + processPurchaseSuccessInternal.value = true + consumePurchaseAsync(purchase) + } catch (ex: Exception) { + hadErrorInternal.value = true + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "server rejected purchase", ex) + } + } + } + + private fun consumePurchaseAsync(purchase: Purchase) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "consumePurchaseAsync()") + } + + runAsync { + lock.withLock { + Checkout.forApplication(billing).startAsync().use { + it.requests.consumeAsync(purchase.token) + } + } + } + } + + fun startPurchase(sku: String) { + runAsync { + lock.withLock { + isWorkingInternal.setTemporarily(true).use { + _ -> + + try { + val server = logic.serverLogic.getServerConfigCoroutine() + + if (!server.hasAuthToken) { + Toast.makeText(getApplication(), R.string.error_general, Toast.LENGTH_SHORT).show() + + return@runAsync + } + + if (server.api.canDoPurchase(server.deviceAuthToken) != CanDoPurchaseStatus.Yes) { + throw IOException("can not do purchase right now") + } + + // start the purchase + val activityCheckout = activityCheckout + + if (activityCheckout == null) { + Toast.makeText(getApplication(), R.string.error_general, Toast.LENGTH_SHORT).show() + + return@runAsync + } + + activityCheckout.waitUntilReady().requests.purchase( + ProductTypes.IN_APP, + sku, + null, + activityCheckout.purchaseFlow + ) + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "could not start purchase", ex) + } + + Toast.makeText(getApplication(), R.string.error_general, Toast.LENGTH_SHORT).show() + } + } + } + } + } +} + +enum class ActivityPurchaseModelStatus { + Idle, Working, Error, Done +} diff --git a/app/src/main/java/io/timelimit/android/ui/payment/PurchaseFragment.kt b/app/src/main/java/io/timelimit/android/ui/payment/PurchaseFragment.kt new file mode 100644 index 0000000..e7c067a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/payment/PurchaseFragment.kt @@ -0,0 +1,130 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.payment + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentPurchaseBinding +import io.timelimit.android.livedata.mergeLiveData +import io.timelimit.android.ui.MainActivity + +class PurchaseFragment : Fragment() { + private val activityModel: ActivityPurchaseModel by lazy { (activity as MainActivity).purchaseModel } + private val model: PurchaseModel by lazy { + ViewModelProviders.of(this).get(PurchaseModel::class.java) + } + + companion object { + private const val PAGE_BUY = 0 + private const val PAGE_ERROR = 1 + private const val PAGE_WAIT = 2 + private const val PAGE_DONE = 3 + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + if (savedInstanceState == null) { + activityModel.resetProcessPurchaseSuccess() + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentPurchaseBinding.inflate(inflater, container, false) + var processingPurchaseError = false + + mergeLiveData(activityModel.status, model.status).observe(this, Observer { + status -> + + val (activityStatus, fragmentStatus) = status!! + + if (activityStatus != ActivityPurchaseModelStatus.Idle) { + when (activityStatus) { + null -> binding.flipper.displayedChild = PAGE_WAIT + ActivityPurchaseModelStatus.Working -> binding.flipper.displayedChild = PAGE_WAIT + ActivityPurchaseModelStatus.Idle -> throw IllegalStateException() + ActivityPurchaseModelStatus.Error -> { + binding.flipper.displayedChild = PAGE_ERROR + + binding.errorReason = getString(R.string.error_general) + binding.showRetryButton = true + processingPurchaseError = true + } + ActivityPurchaseModelStatus.Done -> binding.flipper.displayedChild = PAGE_DONE + }.let { } + } else if (fragmentStatus != null) { + when (fragmentStatus) { + PurchaseFragmentPreparing -> binding.flipper.displayedChild = PAGE_WAIT + is PurchaseFragmentReady -> { + binding.flipper.displayedChild = PAGE_BUY + binding.priceData = fragmentStatus + } + is PurchaseFragmentError -> { + binding.flipper.displayedChild = PAGE_ERROR + + binding.errorReason = when (fragmentStatus) { + PurchaseFragmentErrorBillingNotSupportedByDevice -> getString(R.string.purchase_error_not_supported_by_device) + PurchaseFragmentErrorBillingNotSupportedByAppVariant -> getString(R.string.purchase_error_not_supported_by_app_variant) + PurchaseFragmentNetworkError -> getString(R.string.error_network) + PurchaseFragmentExistingPaymentError -> getString(R.string.purchase_error_existing_payment) + PurchaseFragmentServerRejectedError -> getString(R.string.purchase_error_server_rejected) + } + + binding.showRetryButton = when (fragmentStatus) { + is PurchaseFragmentRecoverableError -> true + is PurchaseFragmentUnrecoverableError -> false + } + processingPurchaseError = false + } + }.let { } + } else { + binding.flipper.displayedChild = PAGE_WAIT + } + }) + + binding.handlers = object: PurchaseFragmentHandlers { + override fun retryAtErrorScreenClicked() { + if (processingPurchaseError) { + activityModel.queryAndProcessPurchasesAsync() + } else { + model.retry() + } + } + + override fun buyForOneMonth() { + activityModel.startPurchase(PurchaseIds.SKU_MONTH) + } + + override fun buyForOneYear() { + activityModel.startPurchase(PurchaseIds.SKU_YEAR) + } + } + + return binding.root + } +} + +interface PurchaseFragmentHandlers { + fun retryAtErrorScreenClicked() + fun buyForOneMonth() + fun buyForOneYear() +} diff --git a/app/src/main/java/io/timelimit/android/ui/payment/PurchaseIds.kt b/app/src/main/java/io/timelimit/android/ui/payment/PurchaseIds.kt new file mode 100644 index 0000000..2952faa --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/payment/PurchaseIds.kt @@ -0,0 +1,23 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.payment + +object PurchaseIds { + const val SKU_YEAR = "premium_year_2018" + const val SKU_MONTH = "premium_month_2018" + + val SKUS = listOf(SKU_YEAR, SKU_MONTH) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/payment/PurchaseModel.kt b/app/src/main/java/io/timelimit/android/ui/payment/PurchaseModel.kt new file mode 100644 index 0000000..cd3a870 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/payment/PurchaseModel.kt @@ -0,0 +1,112 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.payment + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.extensions.getSkusAsync +import io.timelimit.android.extensions.startAsync +import io.timelimit.android.livedata.castDown +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.network.CanDoPurchaseStatus +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.solovyev.android.checkout.Checkout +import org.solovyev.android.checkout.ProductTypes + +class PurchaseModel(application: Application): AndroidViewModel(application) { + private val logic: AppLogic by lazy { DefaultAppLogic.with(application) } + private val application: io.timelimit.android.Application by lazy { application as io.timelimit.android.Application } + private val statusInternal = MutableLiveData() + private val lock = Mutex() + + val status = statusInternal.castDown() + + init { + prepare() + } + + fun retry() { + if (this.status.value is PurchaseFragmentRecoverableError) { + prepare() + } + } + + private fun prepare() { + runAsync { + lock.withLock { + try { + statusInternal.value = PurchaseFragmentPreparing + + if (!BuildConfig.storeCompilant) { + statusInternal.value = PurchaseFragmentErrorBillingNotSupportedByAppVariant + } else { + val server = logic.serverLogic.getServerConfigCoroutine() + + val canDoPurchase = if (server.hasAuthToken) + server.api.canDoPurchase(server.deviceAuthToken) + else + CanDoPurchaseStatus.NoForUnknownReason + + if (canDoPurchase == CanDoPurchaseStatus.Yes) { + val checkout = Checkout.forApplication(application.billing) + + checkout.startAsync().use { + if (!it.billingSupported) { + statusInternal.value = PurchaseFragmentErrorBillingNotSupportedByDevice + } else { + val skus = it.requests.getSkusAsync( + ProductTypes.IN_APP, + PurchaseIds.SKUS + ) + + statusInternal.value = PurchaseFragmentReady( + monthPrice = skus.getSku(PurchaseIds.SKU_MONTH)?.price.toString(), + yearPrice = skus.getSku(PurchaseIds.SKU_YEAR)?.price.toString() + ) + } + } + } else if (canDoPurchase == CanDoPurchaseStatus.NotDueToOldPurchase) { + statusInternal.value = PurchaseFragmentExistingPaymentError + } else { + statusInternal.value = PurchaseFragmentServerRejectedError + } + } + } catch (ex: Exception) { + statusInternal.value = PurchaseFragmentNetworkError + } + } + } + } +} + +sealed class PurchaseFragmentStatus +sealed class PurchaseFragmentError: PurchaseFragmentStatus() +class PurchaseFragmentReady(val monthPrice: String, val yearPrice: String): PurchaseFragmentStatus() +object PurchaseFragmentPreparing: PurchaseFragmentStatus() + +sealed class PurchaseFragmentUnrecoverableError: PurchaseFragmentError() +sealed class PurchaseFragmentRecoverableError: PurchaseFragmentError() + +object PurchaseFragmentErrorBillingNotSupportedByDevice: PurchaseFragmentUnrecoverableError() +object PurchaseFragmentErrorBillingNotSupportedByAppVariant: PurchaseFragmentUnrecoverableError() +object PurchaseFragmentNetworkError: PurchaseFragmentRecoverableError() +object PurchaseFragmentExistingPaymentError: PurchaseFragmentUnrecoverableError() +object PurchaseFragmentServerRejectedError: PurchaseFragmentUnrecoverableError() diff --git a/app/src/main/java/io/timelimit/android/ui/payment/RequiresPurchaseDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/payment/RequiresPurchaseDialogFragment.kt new file mode 100644 index 0000000..10c8257 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/payment/RequiresPurchaseDialogFragment.kt @@ -0,0 +1,40 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.payment + +import android.app.Dialog +import android.os.Bundle +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager +import io.timelimit.android.R +import io.timelimit.android.extensions.showSafe + +class RequiresPurchaseDialogFragment: DialogFragment() { + companion object { + private const val DIALOG_TAG = "rpdf" + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = AlertDialog.Builder(context!!, theme) + .setTitle(R.string.purchase_required_dialog_title) + .setMessage(R.string.purchase_required_dialog_text) + .setPositiveButton(R.string.generic_ok, null) + .create() + + fun show(manager: FragmentManager) { + showSafe(manager, DIALOG_TAG) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/SetupDevicePermissionsFragment.kt b/app/src/main/java/io/timelimit/android/ui/setup/SetupDevicePermissionsFragment.kt new file mode 100644 index 0000000..20cb56f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/SetupDevicePermissionsFragment.kt @@ -0,0 +1,130 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup + +import android.app.admin.DevicePolicyManager +import android.content.ComponentName +import android.content.Intent +import android.os.Build +import android.os.Bundle +import android.provider.Settings +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.Fragment +import androidx.navigation.Navigation +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentSetupDevicePermissionsBinding +import io.timelimit.android.extensions.safeNavigate +import io.timelimit.android.integration.platform.ProtectionLevel +import io.timelimit.android.integration.platform.android.AdminReceiver +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.manage.device.manage.InformAboutDeviceOwnerDialogFragment + +class SetupDevicePermissionsFragment : Fragment() { + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private lateinit var binding: FragmentSetupDevicePermissionsBinding + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val navigation = Navigation.findNavController(container!!) + + binding = FragmentSetupDevicePermissionsBinding.inflate(inflater, container, false) + + binding.handlers = object: SetupDevicePermissionsHandlers { + override fun manageDeviceAdmin() { + val protectionLevel = logic.platformIntegration.getCurrentProtectionLevel() + + if (protectionLevel == ProtectionLevel.None) { + if (InformAboutDeviceOwnerDialogFragment.shouldShow) { + InformAboutDeviceOwnerDialogFragment().show(fragmentManager!!) + } else { + startActivity( + Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN) + .putExtra( + DevicePolicyManager.EXTRA_DEVICE_ADMIN, + ComponentName(context!!, AdminReceiver::class.java) + ) + ) + } + } else { + startActivity( + Intent(Settings.ACTION_SECURITY_SETTINGS) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } + } + + override fun openUsageStatsSettings() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + startActivity( + Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } + } + + override fun openNotificationAccessSettings() { + try { + startActivity( + Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS") + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } catch (ex: Exception) { + Toast.makeText( + context, + R.string.error_general, + Toast.LENGTH_SHORT + ).show() + } + } + + override fun gotoNextStep() { + navigation.safeNavigate( + SetupDevicePermissionsFragmentDirections + .actionSetupDevicePermissionsFragmentToSetupLocalModeFragment(), + R.id.setupDevicePermissionsFragment + ) + } + } + + refreshStatus() + + return binding.root + } + + private fun refreshStatus() { + val platform = logic.platformIntegration + + binding.notificationAccessPermission = platform.getNotificationAccessPermissionStatus() + binding.protectionLevel = platform.getCurrentProtectionLevel() + binding.usageStatsAccess = platform.getForegroundAppPermissionStatus() + } + + override fun onResume() { + super.onResume() + + refreshStatus() + } +} + +interface SetupDevicePermissionsHandlers { + fun manageDeviceAdmin() + fun openUsageStatsSettings() + fun openNotificationAccessSettings() + fun gotoNextStep() +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/SetupLocalModeFragment.kt b/app/src/main/java/io/timelimit/android/ui/setup/SetupLocalModeFragment.kt new file mode 100644 index 0000000..07f4802 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/SetupLocalModeFragment.kt @@ -0,0 +1,111 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup + +import android.app.Application +import android.os.Bundle +import android.util.Log +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.Fragment +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.Navigation +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.model.NetworkTime +import io.timelimit.android.databinding.FragmentSetupLocalModeBinding +import io.timelimit.android.livedata.mergeLiveData +import io.timelimit.android.logic.DefaultAppLogic +import kotlinx.android.synthetic.main.fragment_setup_local_mode.* + +class SetupLocalModeFragment : Fragment() { + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentSetupLocalModeBinding.inflate(inflater, container, false) + + val model = ViewModelProviders.of(this).get(SetupLocalModeModel::class.java) + val navigation = Navigation.findNavController(container!!) + + mergeLiveData(binding.setPasswordView.passwordOk, model.status).observe(this, Observer { + binding.nextBtn.isEnabled = it!!.first == true && it.second == SetupLocalModeModel.Status.Idle + }) + + model.status.observe(this, Observer { + val isIdle = it == SetupLocalModeModel.Status.Idle + + binding.setPasswordView.isEnabled = isIdle + }) + + model.status.observe(this, Observer { + if (it == SetupLocalModeModel.Status.Done) { + navigation.popBackStack(R.id.overviewFragment, false) + } + }) + + binding.nextBtn.setOnClickListener { + model.trySetupWithPassword( + set_password_view.password.value!!, + SetupNetworkTimeVerification.readSelection(binding.networkTimeVerification) + ) + } + + return binding.root + } +} + +class SetupLocalModeModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "SetupLocalModeModel" + } + + enum class Status { + Idle, Running, Done + } + + val status = MutableLiveData() + + init { + status.value = Status.Idle + } + + fun trySetupWithPassword(parentPassword: String, networkTimeVerification: NetworkTime) { + runAsync { + if (status.value != Status.Idle) { + throw IllegalStateException() + } + + status.value = Status.Running + + try { + DefaultAppLogic.with(getApplication()).appSetupLogic.setupForLocalUse(parentPassword, networkTimeVerification, getApplication()) + status.value = Status.Done + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "setup failed", ex) + } + + Toast.makeText(getApplication(), R.string.error_general, Toast.LENGTH_SHORT).show() + + status.value = Status.Idle + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/SetupNetworkTimeVerification.kt b/app/src/main/java/io/timelimit/android/ui/setup/SetupNetworkTimeVerification.kt new file mode 100644 index 0000000..6d977fd --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/SetupNetworkTimeVerification.kt @@ -0,0 +1,29 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup + +import io.timelimit.android.R +import io.timelimit.android.data.model.NetworkTime +import io.timelimit.android.databinding.SetupNetworkTimeVerificationBinding + +object SetupNetworkTimeVerification { + fun readSelection(view: SetupNetworkTimeVerificationBinding) = when (view.networkTimeVerificationRadioGroup.checkedRadioButtonId) { + R.id.network_time_verification_disabled -> NetworkTime.Disabled + R.id.network_time_verification_if_possible -> NetworkTime.IfPossible + R.id.network_time_verification_enabled -> NetworkTime.Enabled + else -> throw IllegalStateException() + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/SetupSelectModeFragment.kt b/app/src/main/java/io/timelimit/android/ui/setup/SetupSelectModeFragment.kt new file mode 100644 index 0000000..9ec0b08 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/SetupSelectModeFragment.kt @@ -0,0 +1,84 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup + + +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.provider.Settings +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.navigation.Navigation +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentSetupSelectModeBinding +import io.timelimit.android.extensions.safeNavigate +import io.timelimit.android.logic.DefaultAppLogic +import kotlinx.android.synthetic.main.fragment_setup_select_mode.* + +class SetupSelectModeFragment : Fragment() { + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentSetupSelectModeBinding.inflate(inflater, container, false) + + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + val navigation = Navigation.findNavController(view) + + btn_local_mode.setOnClickListener { + navigation.safeNavigate( + SetupSelectModeFragmentDirections.actionSetupSelectModeFragmentToSetupDevicePermissionsFragment(), + R.id.setupSelectModeFragment + ) + } + + btn_parent_mode.setOnClickListener { + navigation.safeNavigate( + SetupSelectModeFragmentDirections.actionSetupSelectModeFragmentToSetupParentModeFragment(), + R.id.setupSelectModeFragment + ) + } + + btn_network_child_mode.setOnClickListener { + navigation.safeNavigate( + SetupSelectModeFragmentDirections.actionSetupSelectModeFragmentToSetupRemoteChildFragment(), + R.id.setupSelectModeFragment + ) + } + + btn_uninstall.setOnClickListener { + DefaultAppLogic.with(context!!).platformIntegration.disableDeviceAdmin() + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + startActivity( + Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context!!.packageName}")) + .addCategory(Intent.CATEGORY_DEFAULT) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } else { + startActivity( + Intent(Intent.ACTION_UNINSTALL_PACKAGE, Uri.parse("package:${context!!.packageName}")) + ) + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/SetupTermsFragment.kt b/app/src/main/java/io/timelimit/android/ui/setup/SetupTermsFragment.kt new file mode 100644 index 0000000..c59c4a2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/SetupTermsFragment.kt @@ -0,0 +1,65 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup + + +import android.os.Bundle +import android.text.method.LinkMovementMethod +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.navigation.Navigation +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentSetupTermsBinding +import io.timelimit.android.extensions.safeNavigate +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.setup.customserver.SelectCustomServerDialogFragment + +class SetupTermsFragment : Fragment() { + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentSetupTermsBinding.inflate(inflater, container, false) + + binding.btnAccept.setOnClickListener { + acceptTerms() + } + + binding.customServerButton.setOnClickListener { + SelectCustomServerDialogFragment().show(fragmentManager!!) + } + + binding.termsText1.movementMethod = LinkMovementMethod.getInstance() + binding.termsText2.movementMethod = LinkMovementMethod.getInstance() + + DefaultAppLogic.with(context!!).database.config().getCustomServerUrlAsync().observe(this, Observer { + if (it.isEmpty()) { + binding.customServerStatus.setText(R.string.custom_server_status_disabled) + } else { + binding.customServerStatus.setText(getString(R.string.custom_server_status_enabled, it)) + } + }) + + return binding.root + } + + private fun acceptTerms() { + Navigation.findNavController(view!!).safeNavigate( + SetupTermsFragmentDirections.actionSetupTermsFragmentToSetupSelectModeFragment(), + R.id.setupTermsFragment + ) + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/child/SetupRemoteChildFragment.kt b/app/src/main/java/io/timelimit/android/ui/setup/child/SetupRemoteChildFragment.kt new file mode 100644 index 0000000..618fc60 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/child/SetupRemoteChildFragment.kt @@ -0,0 +1,78 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup.child + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.Navigation +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.databinding.SetupRemoteChildFragmentBinding +import io.timelimit.android.extensions.safeNavigate +import io.timelimit.android.ui.overview.main.MainFragmentDirections + +class SetupRemoteChildFragment : Fragment() { + private val model: SetupRemoteChildViewModel by lazy { + ViewModelProviders.of(this).get(SetupRemoteChildViewModel::class.java) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = SetupRemoteChildFragmentBinding.inflate(inflater, container, false) + + binding.btnOk.setOnClickListener { + model.trySetup(binding.editCode.text.toString()) + } + + model.status.observe(this, Observer { + status -> + + when (status) { + SetupRemoteChildStatus.Idle -> binding.flipper.displayedChild = 0 + SetupRemoteChildStatus.Working -> binding.flipper.displayedChild = 1 + SetupRemoteChildStatus.CodeInvalid -> { + Snackbar.make(container!!, R.string.setup_remote_child_code_invalid, Snackbar.LENGTH_SHORT).show() + + model.confirmError() + } + SetupRemoteChildStatus.NetworkError -> { + Snackbar.make(container!!, R.string.error_network, Snackbar.LENGTH_SHORT).show() + + model.confirmError() + } + null -> {/* nothing to do */} + }.let { } + }) + + model.isSetupDone.observe(this, Observer { + if (it!!) { + val navigation = Navigation.findNavController(binding.root) + + navigation.popBackStack(R.id.overviewFragment, false) + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToSetupDeviceFragment(), + R.id.overviewFragment + ) + } + }) + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/child/SetupRemoteChildViewModel.kt b/app/src/main/java/io/timelimit/android/ui/setup/child/SetupRemoteChildViewModel.kt new file mode 100644 index 0000000..b3cf6e4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/child/SetupRemoteChildViewModel.kt @@ -0,0 +1,95 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup.child + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import com.jaredrummler.android.device.DeviceName +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.backup.DatabaseBackup +import io.timelimit.android.data.transaction +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.map +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.ApplyServerDataStatus +import io.timelimit.android.sync.network.ClientDataStatus +import io.timelimit.android.sync.network.NewDeviceInfo +import io.timelimit.android.sync.network.api.UnauthorizedHttpError + +class SetupRemoteChildViewModel(application: Application): AndroidViewModel(application) { + private val statusInternal = MutableLiveData().apply { value = SetupRemoteChildStatus.Idle } + private val logic: AppLogic by lazy { DefaultAppLogic.with(application) } + + val status = statusInternal.castDown() + val isSetupDone = logic.database.config().getOwnDeviceId().map { it != null } + + fun trySetup(registerToken: String) { + if (statusInternal.value != SetupRemoteChildStatus.Idle) { + return + } + + statusInternal.value = SetupRemoteChildStatus.Working + + runAsync { + try { + val api = logic.serverLogic.getServerConfigCoroutine().api + + val registerResponse = api.registerChildDevice( + childDeviceInfo = NewDeviceInfo(model = DeviceName.getDeviceName()), + registerToken = registerToken, + deviceName = DeviceName.getDeviceName() + ) + + val clientStatusResponse = api.pullChanges(registerResponse.deviceAuthToken, ClientDataStatus.empty) + + Threads.database.executeAndWait { + logic.database.transaction().use { transaction -> + val customServerUrl = logic.database.config().getCustomServerUrlSync() + + logic.database.deleteAllData() + logic.database.config().setCustomServerUrlSync(customServerUrl) + logic.database.config().setOwnDeviceIdSync(registerResponse.ownDeviceId) + logic.database.config().setDeviceAuthTokenSync(registerResponse.deviceAuthToken) + + ApplyServerDataStatus.applyServerDataStatusSync(clientStatusResponse, logic.database, logic.platformIntegration) + + transaction.setSuccess() + } + } + + DatabaseBackup.with(getApplication()).tryCreateDatabaseBackupAsync() + } catch (ex: UnauthorizedHttpError) { + statusInternal.value = SetupRemoteChildStatus.CodeInvalid + } catch (ex: Exception) { + statusInternal.value = SetupRemoteChildStatus.NetworkError + } + } + } + + fun confirmError() { + if (statusInternal.value == SetupRemoteChildStatus.NetworkError || statusInternal.value == SetupRemoteChildStatus.CodeInvalid) { + statusInternal.value = SetupRemoteChildStatus.Idle + } + } +} + +enum class SetupRemoteChildStatus { + Idle, Working, NetworkError, CodeInvalid +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/customserver/SelectCustomServerDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/setup/customserver/SelectCustomServerDialogFragment.kt new file mode 100644 index 0000000..fd8ea52 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/customserver/SelectCustomServerDialogFragment.kt @@ -0,0 +1,69 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup.customserver + + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.FragmentManager +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.databinding.SelectCustomServerDialogFragmentBinding +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.livedata.waitForNonNullValue +import io.timelimit.android.logic.DefaultAppLogic + +class SelectCustomServerDialogFragment : BottomSheetDialogFragment() { + companion object { + private const val DIALOG_TAG = "SelectCustomServerDialogFragment" + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = SelectCustomServerDialogFragmentBinding.inflate(inflater, container, false) + val logic = DefaultAppLogic.with(context!!) + val model = ViewModelProviders.of(this).get(SelectCustomServerModel::class.java) + + if (savedInstanceState == null) { + runAsync { + binding.url.setText(logic.database.config().getCustomServerUrlAsync().waitForNonNullValue()) + } + } + + binding.defaultServerButton.setOnClickListener { + model.checkAndSave("") + } + + binding.okButton.setOnClickListener { + model.checkAndSave(binding.url.text.toString().trim()) + } + + model.status.observe(this, Observer { + when (it!!) { + SelectCustomServerStatus.Done -> dismiss() + SelectCustomServerStatus.Idle -> binding.isWorking = false + SelectCustomServerStatus.Working -> binding.isWorking = true + } + }) + + return binding.root + } + + fun show(fragmentManager: FragmentManager) = showSafe(fragmentManager, DIALOG_TAG) +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/customserver/SelectCustomServerModel.kt b/app/src/main/java/io/timelimit/android/ui/setup/customserver/SelectCustomServerModel.kt new file mode 100644 index 0000000..9eca65a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/customserver/SelectCustomServerModel.kt @@ -0,0 +1,86 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup.customserver + +import android.app.Application +import android.util.Log +import android.widget.Toast +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.BuildConfig +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.livedata.castDown +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.network.api.HttpError +import java.io.IOException + +class SelectCustomServerModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "SelectCustomServerModel" + } + + private val logic = DefaultAppLogic.with(application) + private val statusInternal = MutableLiveData().apply { value = SelectCustomServerStatus.Idle } + + val status = statusInternal.castDown() + + fun checkAndSave(url: String) { + statusInternal.value = SelectCustomServerStatus.Working + + runAsync { + try { + if (url.isNotEmpty()) { + logic.serverCreator(url).getTimeInMillis() + } + + saveUrl(url) + + statusInternal.value = SelectCustomServerStatus.Done + } catch (ex: Exception) { + statusInternal.value = SelectCustomServerStatus.Idle + + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "can not set custom server", ex) + } + + if (ex is HttpError) { + Toast.makeText(getApplication(), R.string.custom_server_select_test_failed, Toast.LENGTH_SHORT).show() + } else if (ex is IOException) { + Toast.makeText(getApplication(), R.string.error_network, Toast.LENGTH_SHORT).show() + } else { + Toast.makeText(getApplication(), R.string.error_general, Toast.LENGTH_SHORT).show() + } + } + } + } + + private suspend fun saveUrl(url: String) { + Threads.database.executeAndWait { + if (logic.database.config().getOwnDeviceIdSync() != null) { + throw IllegalStateException("already configured") + } + + logic.database.config().setCustomServerUrlSync(url) + } + } +} + +enum class SelectCustomServerStatus { + Idle, Working, Done +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/setup/device/SetupDeviceFragment.kt b/app/src/main/java/io/timelimit/android/ui/setup/device/SetupDeviceFragment.kt new file mode 100644 index 0000000..de96d37 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/device/SetupDeviceFragment.kt @@ -0,0 +1,295 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup.device + +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.CheckBox +import androidx.appcompat.widget.AppCompatRadioButton +import androidx.fragment.app.Fragment +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.Navigation +import io.timelimit.android.R +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.model.AppRecommendation +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.FragmentSetupDeviceBinding +import io.timelimit.android.extensions.safeNavigate +import io.timelimit.android.livedata.* +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.ActivityViewModelHolder +import io.timelimit.android.ui.overview.main.MainFragmentDirections +import io.timelimit.android.ui.setup.SetupNetworkTimeVerification + +class SetupDeviceFragment : Fragment() { + companion object { + private const val PAGE_READY = 0 + private const val PAGE_REQUIRE_AUTH = 1 + private const val PAGE_WORKING = 2 + const val NEW_PARENT = ":np" + const val NEW_CHILD = ":nc" + val NEW_USER = setOf(NEW_PARENT, NEW_CHILD) + + private const val STATUS_SELECTED_USER = "a" + private const val STATUS_SELECTED_APPS_TO_NOT_WHITELIST = "b" + private const val STATUS_ALLOWED_APPS_CATEGORY = "c" + } + + private val selectedUser = MutableLiveData() + private val selectedAppsToNotWhitelist = mutableSetOf() + private var allowedAppsCategory = "" + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + if (savedInstanceState != null) { + val oldSelectedUser = savedInstanceState.getString(STATUS_SELECTED_USER) + + if (oldSelectedUser != null) { + selectedUser.value = oldSelectedUser + } + + selectedAppsToNotWhitelist.clear() + selectedAppsToNotWhitelist.addAll( + savedInstanceState.getStringArrayList(STATUS_SELECTED_APPS_TO_NOT_WHITELIST)!! + ) + + allowedAppsCategory = savedInstanceState.getString(STATUS_ALLOWED_APPS_CATEGORY)!! + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + + outState.putString(STATUS_SELECTED_USER, selectedUser.value) + outState.putStringArrayList(STATUS_SELECTED_APPS_TO_NOT_WHITELIST, ArrayList(selectedAppsToNotWhitelist)) + outState.putString(STATUS_ALLOWED_APPS_CATEGORY, allowedAppsCategory) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentSetupDeviceBinding.inflate(inflater, container, false) + val logic = DefaultAppLogic.with(context!!) + val activity = activity as ActivityViewModelHolder + val model = ViewModelProviders.of(this).get(SetupDeviceModel::class.java) + val navigation = Navigation.findNavController(container!!) + + binding.needsParent.authBtn.setOnClickListener { + activity.showAuthenticationScreen() + } + + val isParentAuthenticatedLive = activity.getActivityViewModel().authenticatedUser.map { it?.second?.type == UserType.Parent } + + binding.flipper.displayedChild = PAGE_WORKING + mergeLiveData(isParentAuthenticatedLive, model.status).observe(this, Observer { (isParent, status) -> + if (status == SetupDeviceModelStatus.Ready) { + if (isParent == true) { + binding.flipper.displayedChild = PAGE_READY + } else { + binding.flipper.displayedChild = PAGE_REQUIRE_AUTH + } + } else { + binding.flipper.displayedChild = PAGE_WORKING + + when (status) { + SetupDeviceModelStatus.Done -> { + runAsync { + val ownDeviceId = logic.deviceId.waitForNullableValue()!! + + navigation.popBackStack() + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToManageDeviceFragment( + ownDeviceId + ), + R.id.overviewFragment + ) + } + } + SetupDeviceModelStatus.Working -> { /* nothing to do */ } + null -> { /* nothing to do */ } + else -> throw IllegalStateException() + } + } + }) + + logic.database.user().getAllUsersLive().observe(this, Observer { users -> + // ID to label + val items = mutableListOf>() + + // prepare the list content + users.forEach { user -> + items.add(user.id to user.name) + } + + items.add(NEW_PARENT to getString(R.string.setup_device_new_parent)) + items.add(NEW_CHILD to getString(R.string.setup_device_new_child)) + + // select the first item if nothing is selected currently + if (items.find { (id) -> id == selectedUser.value } == null) { + selectedUser.value = items.first().first + } + + // build the views + val views = items.map { (id, label) -> + AppCompatRadioButton(context).apply { + setOnClickListener { selectedUser.value = id } + text = label + tag = id + } + } + + // apply the views + binding.selectUserRadioGroup.removeAllViews() + views.forEach { view -> binding.selectUserRadioGroup.addView(view) } + views.find { it.tag == selectedUser.value }?.isChecked = true + }) + + val isNewUser = selectedUser.map { NEW_USER.contains(it) } + val isParentUser = selectedUser.switchMap { + if (it == NEW_CHILD) { + liveDataFromValue(false) + } else if (it == NEW_PARENT) { + liveDataFromValue(true) + } else { + logic.database.user().getUserByIdLive(it).map {user -> + user?.type == UserType.Parent + } + } + } + + isNewUser.observe(this, Observer { binding.isAddingNewUser = it }) + isParentUser.observe(this, Observer { binding.isAddingChild = !it }) + + val categoriesOfTheSelectedUser = selectedUser.switchMap { user -> + if (NEW_USER.contains(user)) { + liveDataFromValue(emptyList()) + } else { + logic.database.category().getCategoriesByChildId(user) + } + } + + val appsAssignedToTheUser = categoriesOfTheSelectedUser.switchMap { categories -> + logic.database.categoryApp().getCategoryApps(categories.map { it.id }).map { categoryApps -> + categoryApps.map { it.packageName }.toSet() + } + } + + val recommendWhitelistLocalApps = logic.platformIntegration.getLocalApps(IdGenerator.generateId()).filter { it.recommendation == AppRecommendation.Whitelist } + + val appsToWhitelist = appsAssignedToTheUser.map { assignedApps -> + recommendWhitelistLocalApps.filterNot { app -> assignedApps.contains(app.packageName) } + } + + appsToWhitelist.observe(this, Observer { apps -> + binding.areThereAnyApps = apps.isNotEmpty() + + binding.suggestedAllowedApps.removeAllViews() + + apps.forEach { app -> + binding.suggestedAllowedApps.addView( + CheckBox(context).apply { + text = app.title + isChecked = !selectedAppsToNotWhitelist.contains(app.packageName) + + setOnCheckedChangeListener { _, isChecked -> + if (isChecked) { + selectedAppsToNotWhitelist.remove(app.packageName) + } else { + selectedAppsToNotWhitelist.add(app.packageName) + } + } + } + ) + } + }) + + categoriesOfTheSelectedUser.observe(this, Observer { categories -> + // id to title + val items = mutableListOf>() + + categories.forEach { category -> + items.add(category.id to category.title) + } + + if (items.isEmpty()) { + allowedAppsCategory = "" + binding.areThereAnyCategories = false + } else { + if (items.find { (id) -> id == allowedAppsCategory } == null) { + // use the one with the lowest blocked times + allowedAppsCategory = categories.sortedBy { it.blockedMinutesInWeek.dataNotToModify.cardinality() }.first().id + } + + binding.areThereAnyCategories = true + + val views = items.map { (id, label) -> + AppCompatRadioButton(context!!).apply { + text = label + tag = id + setOnClickListener { allowedAppsCategory = id } + } + } + + binding.allowedAppsCategory.removeAllViews() + views.forEach { view -> binding.allowedAppsCategory.addView(view) } + views.find { it.tag == allowedAppsCategory }?.isChecked = true + } + }) + + val selectedName = MutableLiveData().apply { value = binding.newUserName.text.toString() } + binding.newUserName.addTextChangedListener(object: TextWatcher { + override fun afterTextChanged(p0: Editable?) = Unit + override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit + override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { + selectedName.value = binding.newUserName.text.toString() + } + }) + + val hasSelectedName = selectedName.map { it.isNotBlank() } + val isNameRequired = isNewUser + val validationOfName = hasSelectedName.or(isNameRequired.invert()) + val isPasswordRequired = isNewUser.and(isParentUser) + val isPasswordValid = binding.setPasswordView.passwordOk + val isPasswordEmpty = binding.setPasswordView.passwordEmpty + val validationOfPassword = isPasswordValid.or( + isPasswordRequired.invert() + .and(isPasswordEmpty) + ) + val validationOfAll = validationOfName.and(validationOfPassword) + + validationOfAll.observe(this, Observer { binding.confirmBtn.isEnabled = it }) + + binding.confirmBtn.setOnClickListener { + model.doSetup( + userId = selectedUser.value!!, + username = binding.newUserName.text.toString(), + password = binding.setPasswordView.password.value!!, + allowedAppsCategory = allowedAppsCategory, + appsToNotWhitelist = selectedAppsToNotWhitelist, + model = activity.getActivityViewModel(), + networkTime = SetupNetworkTimeVerification.readSelection(binding.networkTimeVerification) + ) + } + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/device/SetupDeviceModel.kt b/app/src/main/java/io/timelimit/android/ui/setup/device/SetupDeviceModel.kt new file mode 100644 index 0000000..7d53f3c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/device/SetupDeviceModel.kt @@ -0,0 +1,177 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup.device + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.model.AppRecommendation +import io.timelimit.android.data.model.NetworkTime +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.waitForNullableValue +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.* +import io.timelimit.android.sync.network.ParentPassword +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.user.create.DefaultCategories + +class SetupDeviceModel(application: Application): AndroidViewModel(application) { + private val logic = DefaultAppLogic.with(application) + private val statusInternal = MutableLiveData().apply { value = SetupDeviceModelStatus.Ready } + + val status = statusInternal.castDown() + + fun doSetup( + userId: String, + username: String, + password: String, + allowedAppsCategory: String, + appsToNotWhitelist: Set, + model: ActivityViewModel, + networkTime: NetworkTime + ) { + if (statusInternal.value != SetupDeviceModelStatus.Ready) { + return + } + + statusInternal.value = SetupDeviceModelStatus.Working + + runAsync { + val actions = mutableListOf() + var realUserId = userId + var realAllowedAppsCategory = allowedAppsCategory + val defaultCategories = DefaultCategories.with(getApplication()) + + val isUserAnChild = when (userId) { + SetupDeviceFragment.NEW_PARENT -> { + // generate user id + realUserId = IdGenerator.generateId() + + // create parent + actions.add(AddUserAction( + userId = realUserId, + name = username, + timeZone = logic.timeApi.getSystemTimeZone().id, + userType = UserType.Parent, + password = ParentPassword.createCoroutine(password) + )) + + false + } + SetupDeviceFragment.NEW_CHILD -> { + // generate user id + realUserId = IdGenerator.generateId() + + // create child + actions.add(AddUserAction( + userId = realUserId, + name = username, + timeZone = logic.timeApi.getSystemTimeZone().id, + userType = UserType.Child, + password = if (password.isEmpty()) null else ParentPassword.createCoroutine(password) + )) + + // create default categories + realAllowedAppsCategory = IdGenerator.generateId() + val allowedGamesCategory = IdGenerator.generateId() + + actions.add(CreateCategoryAction( + childId = realUserId, + categoryId = realAllowedAppsCategory, + title = defaultCategories.allowedAppsTitle + )) + + actions.add(CreateCategoryAction( + childId = realUserId, + categoryId = allowedGamesCategory, + title = defaultCategories.allowedGamesTitle + )) + + actions.add(UpdateCategoryBlockedTimesAction( + categoryId = allowedGamesCategory, + blockedTimes = defaultCategories.allowedGamesBlockedTimes + )) + + defaultCategories.generateGamesTimeLimitRules(allowedGamesCategory).forEach { rule -> + actions.add(CreateTimeLimitRuleAction(rule)) + } + + true + } + else -> { + logic.database.user().getUserByIdLive(userId).waitForNullableValue()!!.type == UserType.Child + } + } + + if (isUserAnChild) { + if (realAllowedAppsCategory == "") { + // create allowed apps category if none was specified and overwrite its id + realAllowedAppsCategory = IdGenerator.generateId() + + actions.add(CreateCategoryAction( + childId = realUserId, + categoryId = realAllowedAppsCategory, + title = defaultCategories.allowedAppsTitle + )) + } + + // add allowed apps + val allowedAppsPackages = logic.platformIntegration.getLocalApps(IdGenerator.generateId()) + .filter { app -> app.recommendation == AppRecommendation.Whitelist } + .map { app -> app.packageName } + .toMutableSet().apply { + removeAll(appsToNotWhitelist) + }.toList() + + if (allowedAppsPackages.isNotEmpty()) { + actions.add(AddCategoryAppsAction( + categoryId = realAllowedAppsCategory, + packageNames = allowedAppsPackages + )) + } + } + + // apply the network time mode + val deviceId = logic.deviceId.waitForNullableValue()!! + + actions.add(UpdateNetworkTimeVerificationAction( + deviceId = deviceId, + mode = networkTime + )) + + // assign user to this device + actions.add(SetDeviceUserAction( + deviceId = deviceId, + userId = realUserId + )) + + if (model.tryDispatchParentActions(actions)) { + statusInternal.value = SetupDeviceModelStatus.Done + } else { + statusInternal.value = SetupDeviceModelStatus.Ready + } + } + } +} + +enum class SetupDeviceModelStatus { + Ready, + Working, + Done +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/parent/SetupParentModeFragment.kt b/app/src/main/java/io/timelimit/android/ui/setup/parent/SetupParentModeFragment.kt new file mode 100644 index 0000000..96e3b0f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/parent/SetupParentModeFragment.kt @@ -0,0 +1,149 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup.parent + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.Navigation +import com.jaredrummler.android.device.DeviceName +import io.timelimit.android.R +import io.timelimit.android.databinding.FragmentSetupParentModeBinding +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.sync.network.StatusOfMailAddress +import io.timelimit.android.ui.authentication.AuthenticateByMailFragment +import io.timelimit.android.ui.authentication.AuthenticateByMailFragmentListener + +class SetupParentModeFragment : Fragment(), AuthenticateByMailFragmentListener { + val model: SetupParentModeModel by lazy { ViewModelProviders.of(this).get(SetupParentModeModel::class.java) } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentSetupParentModeBinding.inflate(layoutInflater, container, false) + + model.mailAuthToken.switchMap { + mailAuthToken -> + + if (mailAuthToken == null) { + liveDataFromValue(1) // show login screen + } else { + // show form or loading indicator or error screen + model.statusOfMailAddress.switchMap { + status -> + + if (status == null) { + liveDataFromValue(2) // loading screen + } else { + model.isDoingSetup.map { + if (it!!) { + 2 // loading screen + } else { + 0 // the form + } + } + } + } + } + }.observe(this, Observer { + binding.switcher.displayedChild = it!! + }) + + val isNewFamily = model.statusOfMailAddress.map { + it == null || it.status == StatusOfMailAddress.MailAddressWithoutFamily + } + + model.statusOfMailAddress.observe(this, Observer { + if (it != null) { + binding.isNewFamily = when (it.status) { + StatusOfMailAddress.MailAddressWithoutFamily -> true + StatusOfMailAddress.MailAddressWithFamily -> false + } + binding.mail = it.mail + } + }) + + isNewFamily.observe(this, Observer { binding.isNewFamily = it }) + + // TODO: require that an device name and an parent name are set + val isInputValid = model.statusOfMailAddress.switchMap { + if (it == null) { + liveDataFromValue(false) + } else { + when (it.status) { + StatusOfMailAddress.MailAddressWithFamily -> liveDataFromValue(true) + StatusOfMailAddress.MailAddressWithoutFamily -> binding.password.passwordOk + } + } + } + + isInputValid.observe(this, Observer { + binding.enableOkButton = it!! + }) + + if (savedInstanceState == null) { + // provide an useful default value + binding.deviceName.setText(DeviceName.getDeviceName()) + } + + binding.ok.setOnClickListener { + val status = model.statusOfMailAddress.value + + if (status == null) { + throw IllegalStateException() + } + + when (status.status) { + StatusOfMailAddress.MailAddressWithoutFamily -> { + model.createFamily( + parentPassword = binding.password.password.value!!, + parentName = binding.prename.text.toString(), + deviceName = binding.deviceName.text.toString() + ) + } + StatusOfMailAddress.MailAddressWithFamily -> { + model.addDeviceToFamily( + deviceName = binding.deviceName.text.toString() + ) + } + } + } + + model.isSetupDone.observe(this, Observer { + if (it!!) { + Navigation.findNavController(binding.root).popBackStack(R.id.overviewFragment, false) + } + }) + + return binding.root + } + + override fun onLoginSucceeded(mailAuthToken: String) = model.setMailToken(mailAuthToken) + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + if (savedInstanceState == null) { + childFragmentManager.beginTransaction() + .replace(R.id.mail_auth_container, AuthenticateByMailFragment()) + .commit() + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/setup/parent/SetupParentModeModel.kt b/app/src/main/java/io/timelimit/android/ui/setup/parent/SetupParentModeModel.kt new file mode 100644 index 0000000..8f9cb14 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/parent/SetupParentModeModel.kt @@ -0,0 +1,191 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.setup.parent + +import android.app.Application +import android.widget.Toast +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import com.jaredrummler.android.device.DeviceName +import io.timelimit.android.R +import io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.backup.DatabaseBackup +import io.timelimit.android.data.transaction +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.map +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.ApplyServerDataStatus +import io.timelimit.android.sync.network.ClientDataStatus +import io.timelimit.android.sync.network.NewDeviceInfo +import io.timelimit.android.sync.network.ParentPassword +import io.timelimit.android.sync.network.StatusOfMailAddressResponse +import io.timelimit.android.sync.network.api.ConflictHttpError +import io.timelimit.android.sync.network.api.UnauthorizedHttpError + +class SetupParentModeModel(application: Application): AndroidViewModel(application) { + private val logic = DefaultAppLogic.with(application) + + private val mailAuthTokenInternal = MutableLiveData().apply { value = null } + private val statusOfMailAddressInternal = MutableLiveData().apply { value = null } + private val isDoingSetupInternal = MutableLiveData().apply { value = false } + + val mailAuthToken = mailAuthTokenInternal.castDown() + val statusOfMailAddress = statusOfMailAddressInternal.castDown() + val isDoingSetup = isDoingSetupInternal.castDown() + val isSetupDone = logic.database.config().getOwnDeviceId().map { it != null } + + fun setMailToken(mailAuthToken: String) { + if (this.mailAuthTokenInternal.value == null) { + this.mailAuthTokenInternal.value = mailAuthToken + this.statusOfMailAddressInternal.value = null + + runAsync { + try { + val api = logic.serverLogic.getServerConfigCoroutine().api + val status = api.getStatusByMailToken(mailAuthToken) + + statusOfMailAddressInternal.value = status + } catch (ex: Exception) { + Toast.makeText(getApplication(), R.string.error_network, Toast.LENGTH_SHORT).show() + + mailAuthTokenInternal.value = null + } + } + } + } + + fun createFamily(parentPassword: String, parentName: String, deviceName: String) { + val database = logic.database + + if (isDoingSetup.value!!) { + return + } + + isDoingSetupInternal.value = true + + runAsync { + try { + val api = logic.serverLogic.getServerConfigCoroutine().api + + val registerResponse = api.createFamilyByMailToken( + mailToken = mailAuthToken.value!!, + parentPassword = ParentPassword.createCoroutine(parentPassword), + parentDevice = NewDeviceInfo( + model = DeviceName.getDeviceName() + ), + deviceName = deviceName, + parentName = parentName, + timeZone = logic.timeApi.getSystemTimeZone().id + ) + + val clientStatusResponse = api.pullChanges(registerResponse.deviceAuthToken, ClientDataStatus.empty) + + Threads.database.executeAndWait { + logic.database.transaction().use { transaction -> + val customServerUrl = logic.database.config().getCustomServerUrlSync() + + database.deleteAllData() + + database.config().setCustomServerUrlSync(customServerUrl) + database.config().setOwnDeviceIdSync(registerResponse.ownDeviceId) + database.config().setDeviceAuthTokenSync(registerResponse.deviceAuthToken) + + ApplyServerDataStatus.applyServerDataStatusSync(clientStatusResponse, logic.database, logic.platformIntegration) + + transaction.setSuccess() + } + } + + DatabaseBackup.with(getApplication()).tryCreateDatabaseBackupAsync() + + // the fragment detects the success and leaves this screen + } catch (ex: ConflictHttpError) { + mailAuthTokenInternal.value = null + isDoingSetupInternal.value = false + + Toast.makeText(getApplication(), R.string.error_server_rejected, Toast.LENGTH_SHORT).show() + } catch (ex: UnauthorizedHttpError) { + isDoingSetupInternal.value = false + mailAuthTokenInternal.value = null + + Toast.makeText(getApplication(), R.string.error_server_rejected, Toast.LENGTH_SHORT).show() + } catch (ex: Exception) { + isDoingSetupInternal.value = false + + Toast.makeText(getApplication(), R.string.error_network, Toast.LENGTH_SHORT).show() + } + } + } + + fun addDeviceToFamily(deviceName: String) { + val database = logic.database + + if (isDoingSetup.value!!) { + return + } + + isDoingSetupInternal.value = true + + runAsync { + try { + val api = logic.serverLogic.getServerConfigCoroutine().api + + val registerResponse = api.signInToFamilyByMailToken( + mailToken = mailAuthToken.value!!, + parentDevice = NewDeviceInfo( + model = DeviceName.getDeviceName() + ), + deviceName = deviceName + ) + + val clientStatusResponse = api.pullChanges(registerResponse.deviceAuthToken, ClientDataStatus.empty) + + Threads.database.executeAndWait { + logic.database.transaction().use { transaction -> + + database.deleteAllData() + database.config().setOwnDeviceIdSync(registerResponse.ownDeviceId) + database.config().setDeviceAuthTokenSync(registerResponse.deviceAuthToken) + + ApplyServerDataStatus.applyServerDataStatusSync(clientStatusResponse, logic.database, logic.platformIntegration) + + transaction.setSuccess() + } + } + + DatabaseBackup.with(getApplication()).tryCreateDatabaseBackupAsync() + + // the fragment detects the success and leaves this screen + } catch (ex: ConflictHttpError) { + isDoingSetupInternal.value = false + mailAuthTokenInternal.value = null + + Toast.makeText(getApplication(), R.string.error_server_rejected, Toast.LENGTH_SHORT).show() + } catch (ex: UnauthorizedHttpError) { + isDoingSetupInternal.value = false + mailAuthTokenInternal.value = null + + Toast.makeText(getApplication(), R.string.error_server_rejected, Toast.LENGTH_SHORT).show() + } catch (ex: Exception) { + isDoingSetupInternal.value = false + + Toast.makeText(getApplication(), R.string.error_network, Toast.LENGTH_SHORT).show() + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/user/create/AddUserFragment.kt b/app/src/main/java/io/timelimit/android/ui/user/create/AddUserFragment.kt new file mode 100644 index 0000000..c3d9a9c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/user/create/AddUserFragment.kt @@ -0,0 +1,135 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.user.create + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Observer +import androidx.lifecycle.ViewModelProviders +import androidx.navigation.Navigation +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.FragmentAddUserBinding +import io.timelimit.android.livedata.* +import io.timelimit.android.ui.main.ActivityViewModel +import io.timelimit.android.ui.main.ActivityViewModelHolder + +class AddUserFragment : Fragment() { + companion object { + private const val PAGE_INPUT = 0 + private const val PAGE_WAIT = 1 + private const val PAGE_AUTH = 2 + } + + private val activity: ActivityViewModelHolder by lazy { getActivity() as ActivityViewModelHolder } + private val auth: ActivityViewModel by lazy { activity.getActivityViewModel() } + private val model: AddUserModel by lazy { ViewModelProviders.of(this).get(AddUserModel::class.java) } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val binding = FragmentAddUserBinding.inflate(inflater, container, false) + val navigation = Navigation.findNavController(container!!) + + // user type + + val userType = MutableLiveData() + + fun getUserType(checkedItemId: Int) = when (checkedItemId) { + R.id.radio_type_child -> UserType.Child + R.id.radio_type_parent -> UserType.Parent + else -> throw IllegalStateException() + } + + userType.value = getUserType(binding.radioGroupType.checkedRadioButtonId) + + binding.radioGroupType.setOnCheckedChangeListener { _, checkedId -> userType.value = getUserType(checkedId) } + + // password + + val isPasswordRequired = userType.map { it == UserType.Parent } + + userType.observe(this, Observer { + binding.isCreatingChildUser = it == UserType.Child + }) + + val isPasswordEmpty = binding.password.passwordEmpty + val isPasswordOk = binding.password.passwordOk.or( + isPasswordRequired.invert() + .and(isPasswordEmpty) + ) + + // username + + val username = binding.name.getTextLive() + val usernameOk = username.map { it.isNotBlank() } + + // ok button + + val isEverythingOk = isPasswordOk.and(usernameOk) + + isEverythingOk.observe(this, Observer { binding.createBtn.isEnabled = it!! }) + + // create function + + binding.createBtn.setOnClickListener { + if (auth.isParentAuthenticated()) { + model.tryCreateUser( + name = binding.name.text.toString(), + type = userType.value!!, + password = binding.password.password.value!!, + model = auth + ) + } + } + + + mergeLiveData(model.status, auth.authenticatedUser).observe(this, Observer { + data -> + + val (status, user) = data!! + + if (user == null || user.second.type != UserType.Parent) { + binding.flipper.displayedChild = PAGE_AUTH + } else { + when (status) { + AddUserModelStatus.Idle -> { + binding.flipper.displayedChild = PAGE_INPUT + } + AddUserModelStatus.Working -> { + binding.flipper.displayedChild = PAGE_WAIT + } + AddUserModelStatus.Done -> { + Snackbar.make(binding.root, R.string.add_user_confirmation_done, Snackbar.LENGTH_SHORT).show() + navigation.popBackStack() + + binding.flipper.displayedChild = PAGE_WAIT + } + null -> {/* nothing to do */ + } + }.let { } + } + }) + + // link the auth button + binding.missingAuthView.loginBtn.setOnClickListener { activity.showAuthenticationScreen() } + + return binding.root + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/user/create/AddUserModel.kt b/app/src/main/java/io/timelimit/android/ui/user/create/AddUserModel.kt new file mode 100644 index 0000000..6af0c27 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/user/create/AddUserModel.kt @@ -0,0 +1,134 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.user.create + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.coroutines.runAsync +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.model.AppRecommendation +import io.timelimit.android.data.model.UserType +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.waitForNonNullValue +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.* +import io.timelimit.android.sync.network.ParentPassword +import io.timelimit.android.ui.main.ActivityViewModel +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +class AddUserModel(application: Application): AndroidViewModel(application) { + private val logic: AppLogic by lazy { DefaultAppLogic.with(application) } + + private val statusInternal = MutableLiveData().apply { value = AddUserModelStatus.Idle } + private val createUserLock = Mutex() + + val status = statusInternal.castDown() + + fun tryCreateUser(name: String, password: String, type: UserType, model: ActivityViewModel) { + runAsync { + createUserLock.withLock { + statusInternal.value = AddUserModelStatus.Working + + when (type) { + UserType.Parent -> { + if( + model.tryDispatchParentAction( + AddUserAction( + name = name, + password = ParentPassword.createCoroutine(password), + userType = UserType.Parent, + userId = IdGenerator.generateId(), + timeZone = logic.timeApi.getSystemTimeZone().id + ) + ) + ) { + statusInternal.value = AddUserModelStatus.Done + } else { + statusInternal.value = AddUserModelStatus.Idle + } + } + UserType.Child -> { + val childId = IdGenerator.generateId() + val allowedAppsCategory = IdGenerator.generateId() + val allowedGamesCategory = IdGenerator.generateId() + + // NOTE: the default config is created at the AddUserModel and at the AppSetupLogic + val defaultCategories = DefaultCategories.with(getApplication()) + + val actions = ArrayList(listOf( + AddUserAction( + name = name, + password = if (password.isEmpty()) null else ParentPassword.createCoroutine(password), + userType = UserType.Child, + userId = childId, + timeZone = logic.timeApi.getSystemTimeZone().id + ), + CreateCategoryAction( + childId = childId, + categoryId = allowedAppsCategory, + title = defaultCategories.allowedAppsTitle + ), + CreateCategoryAction( + childId = childId, + categoryId = allowedGamesCategory, + title = defaultCategories.allowedGamesTitle + ), + UpdateCategoryBlockedTimesAction( + categoryId = allowedGamesCategory, + blockedTimes = defaultCategories.allowedGamesBlockedTimes + ) + )) + + defaultCategories.generateGamesTimeLimitRules(allowedAppsCategory).forEach { rule -> + actions.add(CreateTimeLimitRuleAction(rule)) + } + + // add recommend allowed apps + val recommendAppWhitelist = logic.database.app() + .getAppsByRecommendationLive(AppRecommendation.Whitelist) + .waitForNonNullValue() + .asSequence() + .map { app -> app.packageName } + .distinct() + .toList() + + if (recommendAppWhitelist.isNotEmpty()) { + actions.add( + AddCategoryAppsAction( + categoryId = allowedAppsCategory, + packageNames = recommendAppWhitelist + ) + ) + } + + if(model.tryDispatchParentActions(actions)) { + statusInternal.value = AddUserModelStatus.Done + } else { + statusInternal.value = AddUserModelStatus.Idle + } + } + } + } + } + } +} + +enum class AddUserModelStatus { + Idle, Working, Done +} diff --git a/app/src/main/java/io/timelimit/android/ui/user/create/DefaultCategories.kt b/app/src/main/java/io/timelimit/android/ui/user/create/DefaultCategories.kt new file mode 100644 index 0000000..c08f0bc --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/user/create/DefaultCategories.kt @@ -0,0 +1,102 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.user.create + +import android.content.Context +import io.timelimit.android.R +import io.timelimit.android.data.IdGenerator +import io.timelimit.android.data.customtypes.ImmutableBitmask +import io.timelimit.android.data.model.TimeLimitRule +import java.util.* + +class DefaultCategories private constructor(private val context: Context) { + companion object { + private var instance: DefaultCategories? = null + + fun with(context: Context): DefaultCategories { + if (instance == null) { + instance = DefaultCategories(context.applicationContext) + } + + return instance!! + } + } + + val allowedAppsTitle get() = context.getString(R.string.setup_category_allowed) + val allowedGamesTitle get() = context.getString(R.string.setup_category_games) + val allowedGamesBlockedTimes: ImmutableBitmask by lazy { + ImmutableBitmask( + BitSet().apply { + for (i in 0..6) { + val startOfDay = i * 60 * 24 + + // to 6 AM + set(startOfDay, startOfDay + 6 * 60) + + // from 6 PM + set(startOfDay + 18 * 60, startOfDay + 24 * 60) + } + } + ) + } + + fun generateGamesTimeLimitRules(categoryId: String): List { + val rules = mutableListOf() + + // maximum time for each workday + for (day in 0..4) { + rules.add( + TimeLimitRule( + id = IdGenerator.generateId(), + categoryId = categoryId, + applyToExtraTimeUsage = false, + dayMask = (1 shl day).toByte(), + maximumTimeInMillis = 1000 * 60 * 30 // 30 minutes + ) + ) + } + + // maximum time for each weekend day + for (day in 5..6) { + rules.add( + TimeLimitRule( + id = IdGenerator.generateId(), + categoryId = categoryId, + applyToExtraTimeUsage = false, + dayMask = (1 shl day).toByte(), + maximumTimeInMillis = 1000 * 60 * 60 * 3 // 3 hours + ) + ) + } + + // maximum time per total week + val dayMask = BitSet() + + dayMask.set(0, 7) + + rules.add( + TimeLimitRule( + id = IdGenerator.generateId(), + categoryId = categoryId, + applyToExtraTimeUsage = false, + dayMask = 1 + 2 + 4 + 8 + 16 + 32 + 64, + maximumTimeInMillis = 1000 * 60 * 60 * 6 // 6 hours + ) + ) + + return rules.toList() + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/util/ConfirmDeleteDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/util/ConfirmDeleteDialogFragment.kt new file mode 100644 index 0000000..8150e6d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/util/ConfirmDeleteDialogFragment.kt @@ -0,0 +1,41 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.util + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import io.timelimit.android.databinding.ConfirmDeleteDialogBinding + +abstract class ConfirmDeleteDialogFragment: BottomSheetDialogFragment(), ConfirmDeleteDialogFragmentHandlers { + lateinit var binding: ConfirmDeleteDialogBinding + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + binding = ConfirmDeleteDialogBinding.inflate(inflater, container, false) + + binding.handlers = this + + return binding.root + } + + abstract override fun onConfirmDeletion() +} + +interface ConfirmDeleteDialogFragmentHandlers { + fun onConfirmDeletion() +} diff --git a/app/src/main/java/io/timelimit/android/ui/util/EditTextBottomSheetDialog.kt b/app/src/main/java/io/timelimit/android/ui/util/EditTextBottomSheetDialog.kt new file mode 100644 index 0000000..bd17f4e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/util/EditTextBottomSheetDialog.kt @@ -0,0 +1,80 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.util + +import android.content.Context +import android.os.Bundle +import android.view.KeyEvent +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputMethodManager +import androidx.fragment.app.DialogFragment +import com.google.android.material.bottomsheet.BottomSheetDialog +import io.timelimit.android.async.Threads +import io.timelimit.android.databinding.EditTextBottomSheetDialogBinding + +abstract class EditTextBottomSheetDialog: DialogFragment() { + private val inputMethodManager: InputMethodManager by lazy { + context!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + } + + lateinit var binding: EditTextBottomSheetDialogBinding + + override fun onCreateDialog(savedInstanceState: Bundle?) = BottomSheetDialog(context!!, theme).apply { + setOnShowListener { + Threads.mainThreadHandler.post { + binding.editText.requestFocus() + inputMethodManager.showSoftInput(binding.editText, 0) + } + } + } + + fun didInitField() { + binding.editText.setSelection(binding.editText.text.length) + binding.editText.requestFocus() + inputMethodManager.showSoftInput(binding.editText, 0) + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + binding = EditTextBottomSheetDialogBinding.inflate(inflater, container, false) + + binding.editText.setOnEditorActionListener { _, actionId, _ -> + if (actionId == EditorInfo.IME_ACTION_GO) { + go() + + true + } else { + false + } + } + + binding.editText.setOnKeyListener { _, keyCode, keyEvent -> + if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) { + go() + + true + } else { + false + } + } + + return binding.root + } + + abstract fun go() +} diff --git a/app/src/main/java/io/timelimit/android/ui/util/SyncStatusModel.kt b/app/src/main/java/io/timelimit/android/ui/util/SyncStatusModel.kt new file mode 100644 index 0000000..9cc7cfa --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/util/SyncStatusModel.kt @@ -0,0 +1,73 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.util + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.LiveData +import io.timelimit.android.R +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.DefaultAppLogic + +class SyncStatusModel(application: Application): AndroidViewModel(application) { + private val logic = DefaultAppLogic.with(application) + private val db = logic.database + private val sync = logic.syncUtil + + private val isConnectedMode = db.config().getDeviceAuthTokenAsync().map { it.isNotEmpty() } + private val isConnected = logic.isConnected + private val isNormalSyncPending = sync.isNormalSyncRequested + private val isUnimportantSyncPending = sync.isVeryUnimportantSyncRequested + private val hasQueuedItems = db.pendingSyncAction().countAllActionsLive().map { it != 0L } + + val statusText = isConnectedMode.switchMap { connectedMode -> + if (connectedMode) { + isConnected.switchMap { connected -> + if (connected) { + val base = application.getString(R.string.sync_status_online) + + isNormalSyncPending.switchMap { normalSyncPending -> + if (normalSyncPending) { + liveDataFromValue(application.getString(R.string.sync_status_not_synced, base)) + } else { + isUnimportantSyncPending.map { unimportantSyncPending -> + if (unimportantSyncPending) { + application.getString(R.string.sync_status_unimportant_not_synced, base) + } else { + base + } + } + } + } + } else { + val base = application.getString(R.string.sync_status_offline) + + hasQueuedItems.map { itemsPending -> + if (itemsPending) { + application.getString(R.string.sync_status_not_synced, base) + } else { + base + } + } + } + } as LiveData + } else { + liveDataFromValue(null as String?) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/view/AppFilterView.kt b/app/src/main/java/io/timelimit/android/ui/view/AppFilterView.kt new file mode 100644 index 0000000..8cca9dc --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/AppFilterView.kt @@ -0,0 +1,88 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.view + +import android.text.Editable +import android.text.TextWatcher +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import io.timelimit.android.data.model.App +import io.timelimit.android.databinding.AppFilterViewBinding + +object AppFilterView { + fun getFilter(view: AppFilterViewBinding): AppFilter = buildAppFilter( + searchTerm = view.search.text.toString(), + includeSystemApps = view.showSystemApps.isChecked + ) + + fun getFilterLive(view: AppFilterViewBinding): LiveData { + val result = MutableLiveData().apply { value = getFilter(view) } + + fun update() { + result.value = getFilter(view) + } + + view.showSystemApps.setOnCheckedChangeListener { _, _ -> update() } + view.search.addTextChangedListener(object: TextWatcher { + override fun afterTextChanged(s: Editable?) { + // ignore + } + + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { + // ignore + } + + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { + update() + } + }) + + return result + } + + private fun buildAppFilter( + searchTerm: String, + includeSystemApps: Boolean + ): AppFilter { + return object: AppFilter { + override fun matches(app: App): Boolean { + if ((!includeSystemApps) && (!app.isLaunchable)) { + return false + } + + if (searchTerm.isNotBlank()) { + if (app.title.contains(searchTerm, true) || app.packageName.contains(searchTerm, true)) { + // ok + } else { + return false + } + } + + return true + } + } + } + + interface AppFilter { + fun matches(app: App): Boolean + + companion object { + val dummy = object: AppFilter { + override fun matches(app: App) = true + } + } + } +} diff --git a/app/src/main/java/io/timelimit/android/ui/view/ManageDisableTimelimitsView.kt b/app/src/main/java/io/timelimit/android/ui/view/ManageDisableTimelimitsView.kt new file mode 100644 index 0000000..b3f40d9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/ManageDisableTimelimitsView.kt @@ -0,0 +1,59 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.view + +import android.content.Context +import android.text.TextUtils +import android.util.AttributeSet +import android.view.LayoutInflater +import android.widget.FrameLayout +import io.timelimit.android.R +import io.timelimit.android.databinding.ViewManageDisableTimeLimitsBinding +import kotlin.properties.Delegates + +class ManageDisableTimelimitsView(context: Context, attributeSet: AttributeSet): FrameLayout(context, attributeSet) { + private val binding = ViewManageDisableTimeLimitsBinding.inflate(LayoutInflater.from(context), this, false) + + init { + addView(binding.root) + } + + var disableTimeLimitsUntilString: String? by Delegates.observable(null as String?) { + _, _, value -> + + if (TextUtils.isEmpty(value)) { + binding.disabledUntilString = null + } else { + binding.disabledUntilString = resources.getString(R.string.manage_disable_time_limits_info_enabled, value) + } + } + + var handlers: ManageDisableTimelimitsViewHandlers? by Delegates.observable(null as ManageDisableTimelimitsViewHandlers?) { + _, _, value -> binding.handlers = value + } + + var userName: String? by Delegates.observable(null as String?) { + _, _, value -> binding.userName = value + } +} + +interface ManageDisableTimelimitsViewHandlers { + fun disableTimeLimitsUntilSelectedTimeOfToday() + fun disableTimeLimitsUntilSelectedDate() + fun disableTimeLimitsForDuration(duration: Long) + fun disableTimeLimitsForToday() + fun enableTimeLimits() +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/view/SafeViewFlipper.kt b/app/src/main/java/io/timelimit/android/ui/view/SafeViewFlipper.kt new file mode 100644 index 0000000..cfac1c5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/SafeViewFlipper.kt @@ -0,0 +1,35 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.view + +import android.content.Context +import android.util.AttributeSet +import android.widget.ViewFlipper + +// based on https://stackoverflow.com/a/8208874 +// this should fix some rare crashes at Android 4.4 +class SafeViewFlipper: ViewFlipper { + constructor(context: Context) : this(context, null) + constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) + + override fun onDetachedFromWindow() { + try { + super.onDetachedFromWindow() + } catch (ex: IllegalArgumentException) { + stopFlipping() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/view/SelectDayView.kt b/app/src/main/java/io/timelimit/android/ui/view/SelectDayView.kt new file mode 100644 index 0000000..e3c7a99 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/SelectDayView.kt @@ -0,0 +1,20 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.view + +interface SelectDayViewHandlers { + fun updateDayChecked(day: Int) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/view/SelectTimeSpanView.kt b/app/src/main/java/io/timelimit/android/ui/view/SelectTimeSpanView.kt new file mode 100644 index 0000000..d108d93 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/SelectTimeSpanView.kt @@ -0,0 +1,132 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.view + +import android.content.Context +import android.util.AttributeSet +import android.view.LayoutInflater +import android.widget.FrameLayout +import android.widget.SeekBar +import io.timelimit.android.R +import io.timelimit.android.databinding.ViewSelectTimeSpanBinding +import io.timelimit.android.util.TimeTextUtil +import kotlin.properties.Delegates + +class SelectTimeSpanView(context: Context, attributeSet: AttributeSet): FrameLayout(context, attributeSet) { + private val binding = ViewSelectTimeSpanBinding.inflate(LayoutInflater.from(context), this, false) + + init { + addView(binding.root) + } + + var listener: SelectTimeSpanViewListener? = null + + var timeInMillis: Long by Delegates.observable(0L) { + _, _, _ -> + bindTime() + listener?.onTimeSpanChanged(timeInMillis) + } + + var maxDays: Int by Delegates.observable(0) { + _, _, _ -> binding.maxDays = maxDays + } + + init { + val attributes = context.obtainStyledAttributes(attributeSet, R.styleable.SelectTimeSpanView) + + timeInMillis = attributes.getInt(R.styleable.SelectTimeSpanView_timeInMillis, timeInMillis.toInt()).toLong() + maxDays = attributes.getInt(R.styleable.SelectTimeSpanView_maxDays, maxDays) + + attributes.recycle() + + bindTime() + } + + private fun bindTime() { + val totalMinutes = (timeInMillis / (1000 * 60)).toInt() + val totalHours = totalMinutes / 60 + val totalDays = totalHours / 24 + val minutes = totalMinutes % 60 + val hours = totalHours % 24 + + binding.days = totalDays + binding.minutes = minutes + binding.hours = hours + + binding.daysText = TimeTextUtil.days(totalDays, context!!) + binding.minutesText = TimeTextUtil.minutes(minutes, context!!) + binding.hoursText = TimeTextUtil.hours(hours, context!!) + } + + private fun readStatusFromBinding() { + val days = binding.days!!.toLong() + val hours = binding.hours!!.toLong() + val minutes = binding.minutes!!.toLong() + + timeInMillis = (((days * 24) + hours) * 60 + minutes) * 1000 * 60 + } + + init { + binding.daysSeek.setOnSeekBarChangeListener(object: SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { + binding.days = progress + readStatusFromBinding() + } + + override fun onStartTrackingTouch(seekBar: SeekBar?) { + // ignore + } + + override fun onStopTrackingTouch(seekBar: SeekBar?) { + // ignore + } + }) + + binding.hoursSeek.setOnSeekBarChangeListener(object: SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { + binding.hours = progress + readStatusFromBinding() + } + + override fun onStartTrackingTouch(seekBar: SeekBar?) { + // ignore + } + + override fun onStopTrackingTouch(seekBar: SeekBar?) { + // ignore + } + }) + + binding.minutesSeek.setOnSeekBarChangeListener(object: SeekBar.OnSeekBarChangeListener { + override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { + binding.minutes = progress + readStatusFromBinding() + } + + override fun onStartTrackingTouch(seekBar: SeekBar?) { + // ignore + } + + override fun onStopTrackingTouch(seekBar: SeekBar?) { + // ignore + } + }) + } +} + +interface SelectTimeSpanViewListener { + fun onTimeSpanChanged(newTimeInMillis: Long) +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/ui/view/SetPasswordView.kt b/app/src/main/java/io/timelimit/android/ui/view/SetPasswordView.kt new file mode 100644 index 0000000..bc2ddbf --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/SetPasswordView.kt @@ -0,0 +1,123 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.ui.view + +import android.content.Context +import android.text.Editable +import android.text.TextWatcher +import android.util.AttributeSet +import android.view.LayoutInflater +import android.widget.FrameLayout +import androidx.lifecycle.LiveData +import androidx.lifecycle.MutableLiveData +import androidx.lifecycle.Transformations +import io.timelimit.android.databinding.ViewSetPasswordBinding +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.util.PasswordValidator + +class SetPasswordView(context: Context, attributeSet: AttributeSet): FrameLayout(context, attributeSet) { + private val binding = ViewSetPasswordBinding.inflate( + LayoutInflater.from(context), + this, + true + ) + + val password = MutableLiveData() + val passwordRepeat = MutableLiveData() + + init { + password.value = "" + passwordRepeat.value = "" + + binding.fieldPassword.addTextChangedListener(object: TextWatcher { + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { + password.value = binding.fieldPassword.text.toString() + } + + override fun afterTextChanged(s: Editable?) { + // ignore + } + + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { + // ignore + } + }) + + binding.fieldPasswordRepeat.addTextChangedListener(object: TextWatcher { + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { + passwordRepeat.value = binding.fieldPasswordRepeat.text.toString() + } + + override fun afterTextChanged(s: Editable?) { + // ignore + } + + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { + // ignore + } + }) + + password.observeForever { binding.password = it!! } + passwordRepeat.observeForever() { binding.passwordRepeat = it!! } + } + + private val passwordQualityProblem: LiveData = Transformations.map(password) { + if (it.isEmpty()) { + null + } else { + PasswordValidator.validate(it, context) + } + } + private val passwordsNotEqualProblem: LiveData = Transformations.switchMap(password) { + val passwordValue = it + + Transformations.map(passwordRepeat) { + (passwordValue.isNotEmpty() && it.isNotEmpty()) && passwordValue != it + } + } + + val passwordEmpty = password.switchMap { password1 -> + passwordRepeat.map { password2 -> + password1.isEmpty() && password2.isEmpty() + } + } + + val passwordOk: LiveData = Transformations.switchMap(password) { + val password1 = it + + Transformations.map(passwordRepeat) { + val password2 = it + + password1.isNotEmpty() && password2.isNotEmpty() && (password1 == password2) && + (PasswordValidator.validate(password1, context) == null) + } + } + + init { + passwordQualityProblem .observeForever { binding.passwordProblem = it } + passwordsNotEqualProblem.observeForever { binding.passwordsNotEqualProblem = it } + passwordOk.observeForever { /* keep the value fresh */ } + passwordEmpty.observeForever { /* keep the value fresh */ } + } + + override fun setEnabled(enabled: Boolean) { + super.setEnabled(enabled) + + binding.fieldPassword.isEnabled = enabled + binding.fieldPasswordRepeat.isEnabled = enabled + } +} diff --git a/app/src/main/java/io/timelimit/android/util/JoinUtil.kt b/app/src/main/java/io/timelimit/android/util/JoinUtil.kt new file mode 100644 index 0000000..e27011f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/util/JoinUtil.kt @@ -0,0 +1,47 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.util + +import android.content.Context +import io.timelimit.android.R + +object JoinUtil { + fun join(parts: List, context: Context) = when { + parts.isEmpty() -> "" + parts.size == 1 -> parts.first() + parts.size >= 2 -> { + val output = StringBuilder() + + parts.forEachIndexed { index, item -> + output.append(item) + + if (index == parts.size - 2) { + output + .append(' ') + .append(context.getString(R.string.util_join_and)) + .append(' ') + } else if (index == parts.size - 1) { + // nothing to do, this is the last item + } else { + output.append(", ") + } + } + + output.toString() + } + else -> throw IllegalStateException() + } +} \ No newline at end of file diff --git a/app/src/main/java/io/timelimit/android/util/ParseJsonArrayUtil.kt b/app/src/main/java/io/timelimit/android/util/ParseJsonArrayUtil.kt new file mode 100644 index 0000000..7735b13 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/util/ParseJsonArrayUtil.kt @@ -0,0 +1,32 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.util + +import android.util.JsonReader + +fun parseJsonArray(parser: JsonReader, parseItem: () -> T): List { + val result = mutableListOf() + + parser.beginArray() + while (parser.hasNext()) { + result.add(parseItem()) + } + parser.endArray() + + return result.toList() +} + +fun parseJsonStringArray(parser: JsonReader) = parseJsonArray(parser) { parser.nextString() } diff --git a/app/src/main/java/io/timelimit/android/util/PasswordValidator.kt b/app/src/main/java/io/timelimit/android/util/PasswordValidator.kt new file mode 100644 index 0000000..a3ac3e4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/util/PasswordValidator.kt @@ -0,0 +1,59 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.util + +import android.content.Context +import io.timelimit.android.R + +object PasswordValidator { + private const val MINIMAL_CHAR_AMOUNT = 5 + private const val MINIMAL_LETTER_AMOUNT = 2 + + /** + * Use this function to check if the password is possible + * + * @param password a password to check + * @param context a context + * @return a string which says what is missing or null if it is ok + */ + fun validate(password: String, context: Context): String? { + return if (length(password) < MINIMAL_CHAR_AMOUNT) { + context.getString(R.string.password_validator_too_short, MINIMAL_CHAR_AMOUNT) + } else if (countAlphabeticChars(password) < MINIMAL_LETTER_AMOUNT) { + context.getString(R.string.password_validator_min_letters, MINIMAL_LETTER_AMOUNT) + } else { + null + } + } + + private fun countAlphabeticChars(string: String): Int { + var alphabetic = 0 + var i = 0 + val length = length(string) + while (i < length) { + if (Character.isLetter(string[i])) { + alphabetic++ + } + i++ + } + + return alphabetic + } + + private fun length(string: String?): Int { + return string?.length ?: 0 + } +} diff --git a/app/src/main/java/io/timelimit/android/util/TimeTextUtil.kt b/app/src/main/java/io/timelimit/android/util/TimeTextUtil.kt new file mode 100644 index 0000000..dcc741f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/util/TimeTextUtil.kt @@ -0,0 +1,73 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.util + +import android.content.Context +import io.timelimit.android.R + +object TimeTextUtil { + private const val millisecondsPerDay = 1000 * 60 * 60 * 24 + + fun hours(hours: Int, context: Context): String { + return context.resources.getQuantityString(R.plurals.util_time_hours, hours, hours) + } + + fun minutes(minutes: Int, context: Context): String { + return context.resources.getQuantityString(R.plurals.util_time_minutes, minutes, minutes) + } + + fun days(days: Int, context: Context): String { + return context.resources.getQuantityString(R.plurals.util_time_days, days, days) + } + + fun time(time: Int, context: Context): String { + if (time == 0) { + return context.resources.getString(R.string.util_time_blocked) + } else if (time % millisecondsPerDay == 0) { + return days(time / millisecondsPerDay, context) + } else { + val totalMinutes = time / (1000 * 60) + val minutes = totalMinutes % 60 + val hours = totalMinutes / 60 + + return if (minutes != 0 && hours != 0) { + context.resources.getString(R.string.util_limit_hours_and_minutes, hours(hours, context), minutes(minutes, context)) + } else if (minutes != 0) { + minutes(minutes, context) + } else if (hours != 0) { + hours(hours, context) + } else { + context.resources.getString(R.string.util_time_less_minute) + } + } + } + + fun remaining(time: Int, context: Context): String { + return if (time > 0) { + context.resources.getString(R.string.util_time_remaining, time(time, context)) + } else { + context.resources.getString(R.string.util_time_done) + } + } + + fun used(time: Int, context: Context): String { + return if (time <= 0) { + context.resources.getString(R.string.util_time_unused) + } else { + context.resources.getString(R.string.util_time_used, time(time, context)) + } + } +} diff --git a/app/src/main/java/io/timelimit/android/work/ReportUninstallWorker.kt b/app/src/main/java/io/timelimit/android/work/ReportUninstallWorker.kt new file mode 100644 index 0000000..2267594 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/work/ReportUninstallWorker.kt @@ -0,0 +1,82 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.work + +import android.content.Context +import android.util.Log +import androidx.work.* +import io.timelimit.android.BuildConfig +import io.timelimit.android.logic.DefaultAppLogic + +class ReportUninstallWorker(val context: Context, workerParameters: WorkerParameters): CoroutineWorker(context, workerParameters) { + companion object { + private const val DATA_AUTH_TOKEN = "deviceAuthToken" + private const val DATA_CUSTOM_SERVER_URL = "customServerUrl" + private const val LOG_TAG = "ReportUninstallWorker" + + fun enqueue(deviceAuthToken: String, customServerUrl: String) { + if (deviceAuthToken.isEmpty()) { + return + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "enqueue()") + } + + WorkManager.getInstance().enqueue( + OneTimeWorkRequest.Builder(ReportUninstallWorker::class.java) + .setConstraints( + Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .build() + ) + .setInputData( + Data.Builder() + .putString(DATA_AUTH_TOKEN, deviceAuthToken) + .putString(DATA_CUSTOM_SERVER_URL, customServerUrl) + .build() + ) + .build() + ) + } + } + + override suspend fun doWork(): Result { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "doWork()") + } + + return try { + val logic = DefaultAppLogic.with(context) + val deviceAuthToken = inputData.getString(DATA_AUTH_TOKEN)!! + val customServerUrl = inputData.getString(DATA_CUSTOM_SERVER_URL) ?: "" + + logic.serverLogic.getServerFromCustomServerUrl(customServerUrl).reportDeviceRemoved(deviceAuthToken) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "doWork() succeeded") + } + + Result.success() + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "doWork() failed", ex) + } + + Result.retry() + } + } +} diff --git a/app/src/main/java/io/timelimit/android/work/SyncInBackgroundWorker.kt b/app/src/main/java/io/timelimit/android/work/SyncInBackgroundWorker.kt new file mode 100644 index 0000000..566c2d1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/work/SyncInBackgroundWorker.kt @@ -0,0 +1,87 @@ +/* + * TimeLimit Copyright 2019 Jonas Lochmann + * + * 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 version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package io.timelimit.android.work + +import android.content.Context +import android.util.Log +import androidx.work.* +import io.timelimit.android.BuildConfig +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.SyncingDisabledException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.util.concurrent.TimeUnit + +class SyncInBackgroundWorker(val context: Context, workerParameters: WorkerParameters): CoroutineWorker(context, workerParameters) { + companion object { + private const val LOG_TAG = "SyncInBackground" + private const val UNIQUE_WORK_NAME = "SyncInBackgroundWork" + + fun enqueueDelayed() { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "enqueueDelayed") + } + + WorkManager.getInstance().beginUniqueWork( + UNIQUE_WORK_NAME, + ExistingWorkPolicy.KEEP, + OneTimeWorkRequest.Builder(SyncInBackgroundWorker::class.java) + .setInitialDelay(10, TimeUnit.SECONDS) + .setConstraints( + Constraints.Builder() + .setRequiredNetworkType(NetworkType.CONNECTED) + .setRequiresBatteryNotLow(true) + .build() + ) + .build() + ).enqueue() + } + + fun deschedule() { + WorkManager.getInstance().cancelUniqueWork(UNIQUE_WORK_NAME) + } + } + + override suspend fun doWork(): Result { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "upload actions now") + } + + return withContext (Dispatchers.Main) { + try { + DefaultAppLogic.with(context).syncUtil.doSync() + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "done uploading actions") + } + + Result.success() + } catch (ex: SyncingDisabledException) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "upload actions failed because syncing is disabled") + } + + Result.failure() + } catch (ex: Exception) { + if (BuildConfig.DEBUG) { + Log.w(LOG_TAG, "upload actions failed", ex) + } + + Result.retry() + } + } + } +} diff --git a/app/src/main/res/anim/wizard_close_step_in.xml b/app/src/main/res/anim/wizard_close_step_in.xml new file mode 100644 index 0000000..a8c3b42 --- /dev/null +++ b/app/src/main/res/anim/wizard_close_step_in.xml @@ -0,0 +1,22 @@ + + + + + diff --git a/app/src/main/res/anim/wizard_close_step_out.xml b/app/src/main/res/anim/wizard_close_step_out.xml new file mode 100644 index 0000000..1abc855 --- /dev/null +++ b/app/src/main/res/anim/wizard_close_step_out.xml @@ -0,0 +1,22 @@ + + + + + diff --git a/app/src/main/res/anim/wizard_open_step_in.xml b/app/src/main/res/anim/wizard_open_step_in.xml new file mode 100644 index 0000000..00c5e36 --- /dev/null +++ b/app/src/main/res/anim/wizard_open_step_in.xml @@ -0,0 +1,22 @@ + + + + + diff --git a/app/src/main/res/anim/wizard_open_step_out.xml b/app/src/main/res/anim/wizard_open_step_out.xml new file mode 100644 index 0000000..e30dd7d --- /dev/null +++ b/app/src/main/res/anim/wizard_open_step_out.xml @@ -0,0 +1,22 @@ + + + + + diff --git a/app/src/main/res/drawable-hdpi/ic_stat_block.png b/app/src/main/res/drawable-hdpi/ic_stat_block.png new file mode 100644 index 0000000..5d1011d Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_block.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_stat_check.png b/app/src/main/res/drawable-hdpi/ic_stat_check.png new file mode 100644 index 0000000..f5d4265 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_check.png differ diff --git a/app/src/main/res/drawable-hdpi/ic_stat_timelapse.png b/app/src/main/res/drawable-hdpi/ic_stat_timelapse.png new file mode 100644 index 0000000..5472c34 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_stat_timelapse.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_stat_block.png b/app/src/main/res/drawable-mdpi/ic_stat_block.png new file mode 100644 index 0000000..06ffcc4 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_stat_block.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_stat_check.png b/app/src/main/res/drawable-mdpi/ic_stat_check.png new file mode 100644 index 0000000..5b27aa8 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_stat_check.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_stat_timelapse.png b/app/src/main/res/drawable-mdpi/ic_stat_timelapse.png new file mode 100644 index 0000000..a80fc47 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_stat_timelapse.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_block.png b/app/src/main/res/drawable-xhdpi/ic_stat_block.png new file mode 100644 index 0000000..97bb721 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_block.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_check.png b/app/src/main/res/drawable-xhdpi/ic_stat_check.png new file mode 100644 index 0000000..d38cdf5 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_check.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_stat_timelapse.png b/app/src/main/res/drawable-xhdpi/ic_stat_timelapse.png new file mode 100644 index 0000000..6701fdc Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_stat_timelapse.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_stat_block.png b/app/src/main/res/drawable-xxhdpi/ic_stat_block.png new file mode 100644 index 0000000..bcd4966 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_stat_block.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_stat_check.png b/app/src/main/res/drawable-xxhdpi/ic_stat_check.png new file mode 100644 index 0000000..c43d36d Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_stat_check.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_stat_timelapse.png b/app/src/main/res/drawable-xxhdpi/ic_stat_timelapse.png new file mode 100644 index 0000000..4da59be Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_stat_timelapse.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_stat_block.png b/app/src/main/res/drawable-xxxhdpi/ic_stat_block.png new file mode 100644 index 0000000..2c5fb74 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_stat_block.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_stat_check.png b/app/src/main/res/drawable-xxxhdpi/ic_stat_check.png new file mode 100644 index 0000000..7affc14 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_stat_check.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_stat_timelapse.png b/app/src/main/res/drawable-xxxhdpi/ic_stat_timelapse.png new file mode 100644 index 0000000..d771623 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_stat_timelapse.png differ diff --git a/app/src/main/res/drawable/bottom_navigation_colors.xml b/app/src/main/res/drawable/bottom_navigation_colors.xml new file mode 100644 index 0000000..f31450f --- /dev/null +++ b/app/src/main/res/drawable/bottom_navigation_colors.xml @@ -0,0 +1,9 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_account_circle_black_24dp.xml b/app/src/main/res/drawable/ic_account_circle_black_24dp.xml new file mode 100644 index 0000000..7678580 --- /dev/null +++ b/app/src/main/res/drawable/ic_account_circle_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_add_black_24dp.xml b/app/src/main/res/drawable/ic_add_black_24dp.xml new file mode 100644 index 0000000..0258249 --- /dev/null +++ b/app/src/main/res/drawable/ic_add_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_add_white_24dp.xml b/app/src/main/res/drawable/ic_add_white_24dp.xml new file mode 100644 index 0000000..e3979cd --- /dev/null +++ b/app/src/main/res/drawable/ic_add_white_24dp.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_alarm_off_black_24dp.xml b/app/src/main/res/drawable/ic_alarm_off_black_24dp.xml new file mode 100644 index 0000000..785e67b --- /dev/null +++ b/app/src/main/res/drawable/ic_alarm_off_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_alarm_white_24dp.xml b/app/src/main/res/drawable/ic_alarm_white_24dp.xml new file mode 100644 index 0000000..6244bba --- /dev/null +++ b/app/src/main/res/drawable/ic_alarm_white_24dp.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_apps_white_24dp.xml b/app/src/main/res/drawable/ic_apps_white_24dp.xml new file mode 100644 index 0000000..373f775 --- /dev/null +++ b/app/src/main/res/drawable/ic_apps_white_24dp.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_check_box_black_24dp.xml b/app/src/main/res/drawable/ic_check_box_black_24dp.xml new file mode 100644 index 0000000..9948171 --- /dev/null +++ b/app/src/main/res/drawable/ic_check_box_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_check_box_outline_blank_black_24dp.xml b/app/src/main/res/drawable/ic_check_box_outline_blank_black_24dp.xml new file mode 100644 index 0000000..cf8bfa2 --- /dev/null +++ b/app/src/main/res/drawable/ic_check_box_outline_blank_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_content_copy_black_24dp.xml b/app/src/main/res/drawable/ic_content_copy_black_24dp.xml new file mode 100644 index 0000000..8a894a3 --- /dev/null +++ b/app/src/main/res/drawable/ic_content_copy_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_delete_black_24dp.xml b/app/src/main/res/drawable/ic_delete_black_24dp.xml new file mode 100644 index 0000000..39e64d6 --- /dev/null +++ b/app/src/main/res/drawable/ic_delete_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_edit_black_24dp.xml b/app/src/main/res/drawable/ic_edit_black_24dp.xml new file mode 100644 index 0000000..2ab2fb7 --- /dev/null +++ b/app/src/main/res/drawable/ic_edit_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_history_black_24dp.xml b/app/src/main/res/drawable/ic_history_black_24dp.xml new file mode 100644 index 0000000..a61de1b --- /dev/null +++ b/app/src/main/res/drawable/ic_history_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_info_outline_black_24dp.xml b/app/src/main/res/drawable/ic_info_outline_black_24dp.xml new file mode 100644 index 0000000..cf53e14 --- /dev/null +++ b/app/src/main/res/drawable/ic_info_outline_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_list_white_24dp.xml b/app/src/main/res/drawable/ic_list_white_24dp.xml new file mode 100644 index 0000000..f470376 --- /dev/null +++ b/app/src/main/res/drawable/ic_list_white_24dp.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_lock_open_black_24dp.xml b/app/src/main/res/drawable/ic_lock_open_black_24dp.xml new file mode 100644 index 0000000..c812598 --- /dev/null +++ b/app/src/main/res/drawable/ic_lock_open_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_lock_open_white_24dp.xml b/app/src/main/res/drawable/ic_lock_open_white_24dp.xml new file mode 100644 index 0000000..6c09b2a --- /dev/null +++ b/app/src/main/res/drawable/ic_lock_open_white_24dp.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_lock_outline_black_24dp.xml b/app/src/main/res/drawable/ic_lock_outline_black_24dp.xml new file mode 100644 index 0000000..9a14b68 --- /dev/null +++ b/app/src/main/res/drawable/ic_lock_outline_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_security_black_24dp.xml b/app/src/main/res/drawable/ic_security_black_24dp.xml new file mode 100644 index 0000000..9186423 --- /dev/null +++ b/app/src/main/res/drawable/ic_security_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_settings_black_24dp.xml b/app/src/main/res/drawable/ic_settings_black_24dp.xml new file mode 100644 index 0000000..ace746c --- /dev/null +++ b/app/src/main/res/drawable/ic_settings_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_settings_white_24dp.xml b/app/src/main/res/drawable/ic_settings_white_24dp.xml new file mode 100644 index 0000000..79af3ab --- /dev/null +++ b/app/src/main/res/drawable/ic_settings_white_24dp.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_smartphone_black_24dp.xml b/app/src/main/res/drawable/ic_smartphone_black_24dp.xml new file mode 100644 index 0000000..0f291f1 --- /dev/null +++ b/app/src/main/res/drawable/ic_smartphone_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_time_white_24dp.xml b/app/src/main/res/drawable/ic_time_white_24dp.xml new file mode 100644 index 0000000..87e8fda --- /dev/null +++ b/app/src/main/res/drawable/ic_time_white_24dp.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_update_black_24dp.xml b/app/src/main/res/drawable/ic_update_black_24dp.xml new file mode 100644 index 0000000..a1a7cbd --- /dev/null +++ b/app/src/main/res/drawable/ic_update_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_warning_black_24dp.xml b/app/src/main/res/drawable/ic_warning_black_24dp.xml new file mode 100644 index 0000000..b3a9e03 --- /dev/null +++ b/app/src/main/res/drawable/ic_warning_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_warning_white_24dp.xml b/app/src/main/res/drawable/ic_warning_white_24dp.xml new file mode 100644 index 0000000..29d8a44 --- /dev/null +++ b/app/src/main/res/drawable/ic_warning_white_24dp.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_wifi_black_24dp.xml b/app/src/main/res/drawable/ic_wifi_black_24dp.xml new file mode 100644 index 0000000..69c81f1 --- /dev/null +++ b/app/src/main/res/drawable/ic_wifi_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..5d40627 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,24 @@ + + + diff --git a/app/src/main/res/layout/activity_unlock_after_manipulation.xml b/app/src/main/res/layout/activity_unlock_after_manipulation.xml new file mode 100644 index 0000000..35a8a22 --- /dev/null +++ b/app/src/main/res/layout/activity_unlock_after_manipulation.xml @@ -0,0 +1,46 @@ + + + + + + + + +