commit afb86e9d0e433c45d012fa6b91893a3e9e407a58 Author: Jonas L Date: Mon Jan 14 10:11:01 2019 +0100 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..4be575b --- /dev/null +++ b/Readme.md @@ -0,0 +1,10 @@ +# Open TimeLimit + +This App allows setting time limits for the usage of Android phones/ devices. + +It is a fork of the proprietary App [TimeLimit](https://timelimit.io) +with all networking related features removed. + +### Building + +Open it with Android Studio and press the Run button. 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..8434cbe --- /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(103%2C%2058%2C%20183)&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 diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..ac9b516 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,120 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General 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" +apply plugin: 'kotlin-kapt' + +androidExtensions { + experimental = true +} + +def keystoreProperties = new Properties() +keystoreProperties.load(new FileInputStream(project.file("keystore.properties"))) + +android { + compileSdkVersion 28 + defaultConfig { + applicationId "io.timelimit.android.open" + minSdkVersion 19 + targetSdkVersion 28 + versionCode 1 + versionName "0.1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + kapt { + arguments { + arg("room.schemaLocation", "$projectDir/schemas".toString()) + } + } + } + + signingConfigs { + release { + keyAlias keystoreProperties['keyAlias'] + keyPassword keystoreProperties['keyPassword'] + storeFile file(keystoreProperties['storeFile']) + storePassword keystoreProperties['storePassword'] + } + } + + lintOptions { + disable 'GoogleAppIndexingWarning' + baseline file("lint-baseline.xml") + } + + dataBinding { + enabled = true + } + + buildTypes { + release { + signingConfig signingConfigs.release + minifyEnabled true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } +} + +dependencies { + def nav_version = "1.0.0-alpha09" + def room_version = "2.0.0" + def paging_version = "2.1.0-rc01" + + 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:$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 '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.okio:okio:2.1.0' +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..75094d4 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,47 @@ +# Open TimeLimit Copyright 2019 Jonas Lochmann +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 3 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General 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 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 ; +} 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..a946890 --- /dev/null +++ b/app/schemas/io.timelimit.android.data.RoomDatabase/1.json @@ -0,0 +1,431 @@ +{ + "formatVersion": 1, + "database": { + "version": 1, + "identityHash": "cb315927a05cf9a1e8a76f795a54744e", + "entities": [ + { + "tableName": "user", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `password` TEXT NOT NULL, `type` TEXT NOT NULL, `timezone` TEXT NOT NULL, `disable_limits_until` 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": "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 + } + ], + "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, `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": "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}` (`package_name` TEXT NOT NULL, `title` TEXT NOT NULL, `launchable` INTEGER NOT NULL, `recommendation` TEXT NOT NULL, PRIMARY KEY(`package_name`))", + "fields": [ + { + "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": [ + "package_name" + ], + "autoGenerate": false + }, + "indices": [ + { + "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, 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 + } + ], + "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}` (`package_name` TEXT NOT NULL, PRIMARY KEY(`package_name`))", + "fields": [ + { + "fieldPath": "packageName", + "columnName": "package_name", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "package_name" + ], + "autoGenerate": false + }, + "indices": [], + "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, \"cb315927a05cf9a1e8a76f795a54744e\")" + ] + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..64e2a40 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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..88e2bc6 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/Application.kt @@ -0,0 +1,27 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + +class Application : Application() { + override fun onCreate() { + super.onCreate() + + AndroidThreeTen.init(this) + } +} 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..e4b6275 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/async/Threads.kt @@ -0,0 +1,26 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 crypto = Executors.newSingleThreadExecutor()!! +} 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..cd9882c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/coroutines/AwaitExecutorExecution.kt @@ -0,0 +1,45 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..daf39fa --- /dev/null +++ b/app/src/main/java/io/timelimit/android/coroutines/CoroutineFragment.kt @@ -0,0 +1,35 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/RunAsync.kt b/app/src/main/java/io/timelimit/android/coroutines/RunAsync.kt new file mode 100644 index 0000000..14df30c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/coroutines/RunAsync.kt @@ -0,0 +1,39 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/PasswordHashing.kt b/app/src/main/java/io/timelimit/android/crypto/PasswordHashing.kt new file mode 100644 index 0000000..bb1318f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/crypto/PasswordHashing.kt @@ -0,0 +1,39 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 io.timelimit.android.async.Threads +import io.timelimit.android.coroutines.executeAndWait +import org.mindrot.jbcrypt.BCrypt + +object PasswordHashing { + suspend fun hashCoroutine(password: String) = Threads.crypto.executeAndWait { + hashSync(password) + } + + 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 + } + } +} 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..4d5b843 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/Database.kt @@ -0,0 +1,58 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 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() +} 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..446f5a8 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/IdGenerator.kt @@ -0,0 +1,54 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..89489f4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/JsonSerializable.kt @@ -0,0 +1,22 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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) +} 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..4dc40c9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/RoomDatabase.kt @@ -0,0 +1,93 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 +], version = 1) +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() + .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..b9c9e57 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/backup/DatabaseBackup.kt @@ -0,0 +1,148 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.buffer +import okio.sink +import okio.source +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() + databaseFile.source().buffer().readAll(databaseBackupFile.sink(append = false)) + + // 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..7586b70 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/backup/DatabaseBackupLowlevel.kt @@ -0,0 +1,179 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 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(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() + } + 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() + } + } +} 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..bc331da --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/customtypes/Bitmask.kt @@ -0,0 +1,115 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..daee85f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/AppDao.kt @@ -0,0 +1,49 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 { + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun addAppsSync(apps: Collection) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun addAppSync(app: App) + + @Query("DELETE FROM app WHERE package_name IN (:packageNames)") + fun removeAppsByPackageNamesSync(packageNames: List) + + @Query("SELECT * FROM app") + fun getApps(): LiveData> + + @Query("SELECT * FROM app WHERE package_name = :packageName") + fun getAppsByPackageName(packageName: 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..9d90bac --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/CategoryAppDao.kt @@ -0,0 +1,49 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..8ac4fa8 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/CategoryDao.kt @@ -0,0 +1,77 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + +@Dao +abstract class CategoryDao { + @Query("SELECT * FROM category WHERE child_id = :childId") + abstract fun getCategoriesByChildId(childId: String): LiveData> + + @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 * 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> +} + +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..9c58caf --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/ConfigDao.kt @@ -0,0 +1,115 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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) + } + + 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") +} 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..7d80a70 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/DeviceDao.kt @@ -0,0 +1,64 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.integration.platform.NewPermissionStatusConverter +import io.timelimit.android.integration.platform.ProtectionLevelConverter +import io.timelimit.android.integration.platform.RuntimePermissionStatusConverter + +@Dao +@TypeConverters( + 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 WHERE id = :deviceId") + abstract fun updateDeviceUser(deviceId: String, userId: String) + + @Update + abstract fun updateDeviceEntry(device: Device) + + @Query("SELECT * FROM device WHERE current_user_id = :userId") + abstract fun getDevicesByUserId(userId: String): LiveData> + + @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 = \"\" WHERE current_user_id = :userId") + abstract fun unassignCurrentUserFromAllDevices(userId: String) +} 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..5ec8dc5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/TemporarilyAllowedAppDao.kt @@ -0,0 +1,39 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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") + abstract fun getTemporarilyAllowedAppsInternal(): LiveData> + + fun getTemporarilyAllowedApps(): LiveData> { + return Transformations.map(getTemporarilyAllowedAppsInternal()) { it.map { it.packageName } } + } + + @Insert + abstract fun addTemporarilyAllowedAppSync(app: TemporarilyAllowedApp) + + @Query("DELETE FROM temporarily_allowed_app") + abstract fun removeAllTemporarilyAllowedAppsSync() +} 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..0133e53 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/TimeLimitRuleDao.kt @@ -0,0 +1,53 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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("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) + + @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("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..bf6d96f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/UsedTimeDao.kt @@ -0,0 +1,65 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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) + + @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..6081772 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/dao/UserDao.kt @@ -0,0 +1,62 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 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 +} 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..a310c01 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/extensions/UserDate.kt @@ -0,0 +1,32 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.integration.time.TimeApi +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.livedata.liveDataFromFunction +import io.timelimit.android.livedata.switchMap + +fun LiveData.getDateLive(timeApi: TimeApi) = this.mapToTimezone().switchMap { + timeZone -> + + liveDataFromFunction { + DateInTimezone.newInstance(timeApi.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..cefa4b4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/extensions/UserTimezone.kt @@ -0,0 +1,32 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..c840034 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/App.kt @@ -0,0 +1,108 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 = "app") +@TypeConverters(AppRecommendationConverter::class) +data class App ( + @PrimaryKey + @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 PACKAGE_NAME = "packageName" + private const val TITLE = "title" + private const val IS_LAUNCHABLE = "isLaunchable" + private const val RECOMMENDATION = "recommendation" + + fun parse(reader: JsonReader): App { + 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 App( + packageName = packageName!!, + title = title!!, + isLaunchable = isLaunchable!!, + recommendation = recommendation!! + ) + } + } + + override 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() + } +} + +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..95771dc --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/Category.kt @@ -0,0 +1,118 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 +): 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 = "childId" + private const val TITLE = "title" + private const val BLOCKED_MINUTES_IN_WEEK = "blockedMinutesInWeek" + private const val EXTRA_TIME_IN_MILLIS = "extraTimeInMillis" + private const val TEMPORARILY_BLOCKED = "temporarilyBlocked" + + 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 + + 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() + else -> reader.skipValue() + } + } + + reader.endObject() + + return Category( + id = id!!, + childId = childId!!, + title = title!!, + blockedMinutesInWeek = blockedMinutesInWeek!!, + extraTimeInMillis = extraTimeInMillis!!, + temporarilyBlocked = temporarilyBlocked!! + ) + } + } + + 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.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..9893bb3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/CategoryApp.kt @@ -0,0 +1,75 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 = "categoryId" + private const val PACKAGE_NAME = "packageName" + + 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..5935721 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/ConfigurationItem.kt @@ -0,0 +1,120 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 = "key" + private const val VALUE = "value" + + // 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() + } +} + +enum class ConfigurationItemType { + OwnDeviceId, + ShownHints, + WasDeviceLocked +} + +object ConfigurationItemTypeUtil { + private const val OWN_DEVICE_ID = 1 + private const val SHOWN_HINTS = 2 + private const val WAS_DEVICE_LOCKED = 3 + + val TYPES = listOf( + ConfigurationItemType.OwnDeviceId, + ConfigurationItemType.ShownHints, + ConfigurationItemType.WasDeviceLocked + ) + + fun serialize(value: ConfigurationItemType) = when(value) { + ConfigurationItemType.OwnDeviceId -> OWN_DEVICE_ID + ConfigurationItemType.ShownHints -> SHOWN_HINTS + ConfigurationItemType.WasDeviceLocked -> WAS_DEVICE_LOCKED + } + + fun parse(value: Int) = when(value) { + OWN_DEVICE_ID -> ConfigurationItemType.OwnDeviceId + SHOWN_HINTS -> ConfigurationItemType.ShownHints + WAS_DEVICE_LOCKED -> ConfigurationItemType.WasDeviceLocked + 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 +} 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..d0c2879 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/Device.kt @@ -0,0 +1,210 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.integration.platform.* + +@Entity(tableName = "device") +@TypeConverters( + 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 = "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 = "had_manipulation") + val hadManipulation: 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 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 HAD_MANIPULATION = "hm" + + 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 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 hadManipulation: Boolean? = null + + 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() + 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() + HAD_MANIPULATION -> hadManipulation = reader.nextBoolean() + else -> reader.skipValue() + } + } + + reader.endObject() + + return Device( + id = id!!, + name = name!!, + model = model!!, + addedAt = addedAt!!, + currentUserId = currentUserId!!, + currentProtectionLevel = currentProtectionLevel!!, + highestProtectionLevel = highestProtectionLevel!!, + currentUsageStatsPermission = currentUsageStatsPermission!!, + highestUsageStatsPermission = highestUsageStatsPermission!!, + currentNotificationAccessPermission = currentNotificationAccessPermission!!, + highestNotificationAccessPermission = highestNotificationAccessPermission!!, + currentAppVersion = currentAppVersion!!, + highestAppVersion = highestAppVersion!!, + manipulationTriedDisablingDeviceAdmin = manipulationTriedDisablingDeviceAdmin!!, + hadManipulation = hadManipulation!! + ) + } + } + + 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() + } + } + + 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(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(HAD_MANIPULATION).value(hadManipulation) + + 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 + + @Transient + val hasAnyManipulation = hasActiveManipulationWarning || hadManipulation +} 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..bf06850 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/TemporarilyAllowedApp.kt @@ -0,0 +1,27 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 androidx.room.PrimaryKey + +@Entity(tableName = "temporarily_allowed_app") +data class TemporarilyAllowedApp( + @PrimaryKey + @ColumnInfo(name = "package_name") + val packageName: String +) 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..e559ba9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/TimeLimitRule.kt @@ -0,0 +1,109 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..c63fe34 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/UsedTimeItem.kt @@ -0,0 +1,86 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..cc9e1e2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/data/model/User.kt @@ -0,0 +1,139 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + +@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 = "type") + val type: UserType, + @ColumnInfo(name = "timezone") + val timeZone: String, + // 0 = time limits enabled + @ColumnInfo(name = "disable_limits_until") + val disableLimitsUntil: Long +): JsonSerializable { + companion object { + private const val ID = "id" + private const val NAME = "name" + private const val PASSWORD = "password" + private const val TYPE = "type" + private const val TIMEZONE = "timeZone" + private const val DISABLE_LIMITS_UNTIL = "disableLimitsUntil" + + fun parse(reader: JsonReader): User { + var id: String? = null + var name: String? = null + var password: String? = null + var type: UserType? = null + var timeZone: String? = null + var disableLimitsUntil: Long? = null + + reader.beginObject() + while (reader.hasNext()) { + when(reader.nextName()) { + ID -> id = reader.nextString() + NAME -> name = reader.nextString() + PASSWORD -> password = reader.nextString() + TYPE -> type = UserTypeJson.parse(reader.nextString()) + TIMEZONE -> timeZone = reader.nextString() + DISABLE_LIMITS_UNTIL -> disableLimitsUntil = reader.nextLong() + else -> reader.skipValue() + } + } + reader.endObject() + + return User( + id = id!!, + name = name!!, + password = password!!, + type = type!!, + timeZone = timeZone!!, + disableLimitsUntil = disableLimitsUntil!! + ) + } + } + + init { + IdGenerator.assertIdValid(id) + + if (disableLimitsUntil < 0) { + throw IllegalArgumentException() + } + + if (name.isEmpty()) { + throw IllegalArgumentException() + } + + if (timeZone.isEmpty()) { + throw IllegalArgumentException() + } + } + + override fun serialize(writer: JsonWriter) { + writer.beginObject() + + writer.name(ID).value(id) + writer.name(NAME).value(name) + writer.name(PASSWORD).value(password) + writer.name(TYPE).value(UserTypeJson.serialize(type)) + writer.name(TIMEZONE).value(timeZone) + writer.name(DISABLE_LIMITS_UNTIL).value(disableLimitsUntil) + + 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..d47ec67 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/date/CalendarCache.kt @@ -0,0 +1,38 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + } + } +} 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..fdfcb00 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/date/DateInTimezone.kt @@ -0,0 +1,56 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..2c101b8 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/date/DayOfWeek.kt @@ -0,0 +1,22 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..c62f11d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/date/MinuteOfWeek.kt @@ -0,0 +1,33 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/DialogFragment.kt b/app/src/main/java/io/timelimit/android/extensions/DialogFragment.kt new file mode 100644 index 0000000..50a083f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/extensions/DialogFragment.kt @@ -0,0 +1,25 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..c2542fd --- /dev/null +++ b/app/src/main/java/io/timelimit/android/extensions/EditText.kt @@ -0,0 +1,42 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + +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..94b72d5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/extensions/Navigation.kt @@ -0,0 +1,25 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..9bff318 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/extensions/Set.kt @@ -0,0 +1,24 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/integration/platform/PlatformIntegration.kt b/app/src/main/java/io/timelimit/android/integration/platform/PlatformIntegration.kt new file mode 100644 index 0000000..3f2abf3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/PlatformIntegration.kt @@ -0,0 +1,173 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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(): 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 fun getForegroundAppPackageName(): String? + abstract fun setAppStatusMessage(message: AppStatusMessage?) + abstract fun isScreenOn(): Boolean + abstract fun setShowNotificationToRevokeTemporarilyAllowedApps(show: Boolean) + // 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..e7c8d6b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/AdminReceiver.kt @@ -0,0 +1,68 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..6a4cc2b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/AdminStatus.kt @@ -0,0 +1,44 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.integration.platform.ProtectionLevel + +object AdminStatus { + fun getAdminStatus(context: Context, policyManager: DevicePolicyManager): ProtectionLevel { + val component = ComponentName(context, AdminReceiver::class.java) + + return 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..8c24db8 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/AndroidIntegration.kt @@ -0,0 +1,309 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 (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(): Collection { + return AndroidIntegrationApps.getLocalApps(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 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 (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 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) && + (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) + ) { + 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..f3f43bc --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/Apps.kt @@ -0,0 +1,157 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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(context: Context): Collection { + val packageManager = context.packageManager + + val result = HashMap() + + // WHITELIST + // add launcher + add(map = result, resolveInfoList = packageManager.queryIntentActivities(launcherIntent, 0), recommendation = AppRecommendation.Whitelist, context = context) + // add settings + add(map = result, packageName = Intent(Settings.ACTION_SETTINGS).resolveActivity(packageManager)?.packageName, recommendation = AppRecommendation.Whitelist, context = context) + // add dialer + add(map = result, packageName = Intent(Intent.ACTION_DIAL).resolveActivity(packageManager)?.packageName, 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, 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, recommendation = AppRecommendation.Whitelist, context = context) + } + // add contacts + add(map = result, packageName = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI).resolveActivity(packageManager)?.packageName, recommendation = AppRecommendation.Whitelist, context = context) + // add all apps with launcher icon + add(map = result, resolveInfoList = packageManager.queryIntentActivities(mainIntent, 0), 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( + packageName = packageName, + title = applicationInfo.loadLabel(packageManager).toString(), + isLaunchable = false, + recommendation = AppRecommendation.None + ) + } + } + + return result.values + } + + private fun add(map: MutableMap, resolveInfoList: List, 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( + packageName = packageName, + title = info.activityInfo.applicationInfo.loadLabel(packageManager).toString(), + isLaunchable = true, + recommendation = recommendation + ) + } + } + } + + private fun add(map: MutableMap, packageName: 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( + 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..09d8e89 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/AppsChangeListener.kt @@ -0,0 +1,41 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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) + } +} 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..567c457 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/BackgroundService.kt @@ -0,0 +1,129 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 = "action" + private const val ACTION_SET_NOTIFICATION = "set_notification" + private const val ACTION_REVOKE_TEMPORARILY_ALLOWED_APPS = "revoke_temporarily_allowed_apps" + private const val EXTRA_NOTIFICATION = "notification" + + 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..c2b8495 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/Notification.kt @@ -0,0 +1,71 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..cfaf832 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/NotificationListener.kt @@ -0,0 +1,119 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 { + if (shouldRemoveNotification(sbn) == NotificationHandling.Replace) { + cancelNotification(sbn.key) + + 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(getString(R.string.notification_filter_not_blocked_title)) + .setContentText(queryAppTitleCache.query(sbn.packageName)) + .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): NotificationHandling { + if (sbn.packageName == packageName || sbn.isOngoing) { + return NotificationHandling.Keep + } + + val blockingReason = blockingReasonUtil.getBlockingReason(sbn.packageName).waitForNonNullValue() + + if (blockingReason == BlockingReason.None) { + return NotificationHandling.Keep + } + + if (isSystemApp(sbn.packageName) && blockingReason == BlockingReason.NotPartOfAnCategory) { + return NotificationHandling.Keep + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "blocking notification of ${sbn.packageName} because $blockingReason") + } + + return NotificationHandling.Replace + } + + 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 + } + } +} + +enum class NotificationHandling { + Replace, Keep +} 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..65cd2ff --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/CompatForegroundAppHelper.kt @@ -0,0 +1,36 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 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..acd0d4b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/ForegroundAppHelper.kt @@ -0,0 +1,46 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 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..1feab76 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/foregroundapp/LollipopForegroundAppHelper.kt @@ -0,0 +1,72 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.integration.platform.RuntimePermissionStatus + +@TargetApi(Build.VERSION_CODES.LOLLIPOP) +class LollipopForegroundAppHelper(private val context: Context) : ForegroundAppHelper() { + 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 + + @Throws(SecurityException::class) + override fun getForegroundAppPackage(): String? { + if (getPermissionStatus() == RuntimePermissionStatus.NotGranted) { + throw SecurityException() + } + + val time = System.currentTimeMillis() + // query data for last 7 days + val usageEvents = usageStatsManager.queryEvents(time - 1000 * 60 * 60 * 24 * 7, time) + + if (usageEvents != null) { + val event = UsageEvents.Event() + + var lastTime: Long = 0 + var lastPackage: String? = null + + while (usageEvents.hasNextEvent()) { + usageEvents.getNextEvent(event) + + if (event.eventType == UsageEvents.Event.MOVE_TO_FOREGROUND) { + if (event.timeStamp > lastTime) { + lastTime = event.timeStamp + lastPackage = event.packageName + } + } + } + + return lastPackage + } + + return null + } + + 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..8c08b36 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/receiver/BootReceiver.kt @@ -0,0 +1,30 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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) + } + } +} 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..7121b73 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/android/receiver/UpdateReceiver.kt @@ -0,0 +1,30 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..7ff203f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/dummy/DummyApps.kt @@ -0,0 +1,51 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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( + packageName = "com.demo.taskkiller", + title = "Task-Killer", + isLaunchable = true, + recommendation = AppRecommendation.Blacklist + ) + + val launcherLocalApp = App( + packageName = "com.demo.home", + title = "Launcher", + isLaunchable = true, + recommendation = AppRecommendation.Whitelist + ) + + val messagingLocalApp = App( + packageName = "com.demo.messaging", + title = "Messaging", + isLaunchable = true, + recommendation = AppRecommendation.None + ) + + val gameLocalApp = App( + packageName = "com.demo.game", + title = "Game", + isLaunchable = true, + recommendation = AppRecommendation.None + ) + + val all = listOf(taskmanagerLocalApp, launcherLocalApp, messagingLocalApp, gameLocalApp) +} 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..56295ca --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/platform/dummy/DummyIntegration.kt @@ -0,0 +1,124 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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(): Collection { + return localApps + } + + 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 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 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..559107e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/time/DummyTimeApi.kt @@ -0,0 +1,91 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + ) +} 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..75427e6 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/time/RealTimeApi.kt @@ -0,0 +1,43 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.uptimeMillis() + } + + override fun runDelayed(runnable: Runnable, delayInMillis: Long) { + handler.postDelayed(runnable, delayInMillis) + } + + override fun cancelScheduledAction(runnable: Runnable) { + handler.removeCallbacks(runnable) + } + + override fun getSystemTimeZone() = TimeZone.getDefault() +} 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..a665fe5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/integration/time/TimeApi.kt @@ -0,0 +1,36 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..14fd1b6 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/BooleanConnections.kt @@ -0,0 +1,32 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 mergeLiveData(this, other).map { + (it.first != null && it.first == true) || ( it.second != null && it.second == true) + } +} + +fun LiveData.and(other: LiveData): LiveData { + return mergeLiveData(this, other).map { + (it.first != null && it.first == true) && ( it.second != null && it.second == true) + } +} + +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..74f681a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/CastDown.kt @@ -0,0 +1,20 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..1aa4ed9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/FromValue.kt @@ -0,0 +1,26 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..d606a1f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/FromView.kt @@ -0,0 +1,44 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..5d704df --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/GetValue.kt @@ -0,0 +1,55 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..d83b4de --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/IgnoreUnchanged.kt @@ -0,0 +1,33 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..a7f193d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/LiveDataFromFunction.kt @@ -0,0 +1,43 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..fc853b3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/Map.kt @@ -0,0 +1,36 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..640f857 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/MergeLiveData.kt @@ -0,0 +1,140 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..bba127c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/livedata/MultiKeyLiveDataCache.kt @@ -0,0 +1,118 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + } +} + +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/logic/AndroidAppLogic.kt b/app/src/main/java/io/timelimit/android/logic/AndroidAppLogic.kt new file mode 100644 index 0000000..adac30a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/AndroidAppLogic.kt @@ -0,0 +1,70 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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 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), + 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/AppLogic.kt b/app/src/main/java/io/timelimit/android/logic/AppLogic.kt new file mode 100644 index 0000000..22a2fcb --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/AppLogic.kt @@ -0,0 +1,76 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.ignoreUnchanged +import io.timelimit.android.livedata.liveDataFromValue +import io.timelimit.android.livedata.switchMap + +class AppLogic( + val platformIntegration: PlatformIntegration, + val timeApi: TimeApi, + val database: Database, + 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 backgroundTaskLogic = BackgroundTaskLogic(this) + val appSetupLogic = AppSetupLogic(this) + private val syncAppsLogic = 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..88dadf2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/AppSetupLogic.kt @@ -0,0 +1,185 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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, 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 { + // just for safety: delete everything + appLogic.database.deleteAllData() + } + + 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, + currentProtectionLevel = ProtectionLevel.None, + highestProtectionLevel = ProtectionLevel.None, + currentNotificationAccessPermission = NewPermissionStatus.NotGranted, + highestNotificationAccessPermission = NewPermissionStatus.NotGranted, + currentUsageStatsPermission = RuntimePermissionStatus.NotGranted, + highestUsageStatsPermission = RuntimePermissionStatus.NotGranted, + currentAppVersion = 0, + highestAppVersion = 0, + manipulationTriedDisablingDeviceAdmin = false, + hadManipulation = false + ) + + appLogic.database.device().addDeviceSync(device) + } + + run { + // add child + + val child = User( + id = childUserId, + name = context.getString(R.string.setup_username_child), + password = "", + type = UserType.Child, + timeZone = timeZone, + disableLimitsUntil = 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), + type = UserType.Parent, + timeZone = timeZone, + disableLimitsUntil = 0 + ) + + appLogic.database.user().addUserSync(parent) + } + + val installedApps = appLogic.platformIntegration.getLocalApps() + + // 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 + )) + + appLogic.database.category().addCategory(Category( + id = allowedGamesCategoryId, + childId = childUserId, + title = defaultCategories.allowedGamesTitle, + blockedMinutesInWeek = defaultCategories.allowedGamesBlockedTimes, + extraTimeInMillis = 0, + temporarilyBlocked = false + )) + + // 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() + } +} 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..6a181b1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/BackgroundTaskLogic.kt @@ -0,0 +1,463 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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.database.temporarilyAllowedApp().getTemporarilyAllowedApps() + + 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 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 liveDataCaches = LiveDataCaches(arrayOf( + deviceUserEntryLive, + childCategories, + appCategories, + timeLimitRules, + usedTimesOfCategoryAndWeekByFirstDayOfWeek + )) + + private var usedTimeUpdateHelper: UsedTimeItemBatchUpdateHelper? = null + private var previousMainLogicExecutionTime = 0 + private var previousMainLoopEndTime = 0L + + private val appTitleCache = QueryAppTitleCache(appLogic.platformIntegration) + + private suspend fun backgroundServiceLoop() { + 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) + liveDataCaches.removeAllItems() + appLogic.platformIntegration.setAppStatusMessage(null) + deviceUserEntryLive.read().waitUntilValueMatches { it != null && it.type == UserType.Child } + + continue + } + + // loop logic + try { + // get the current time + val nowTimestamp = appLogic.timeApi.getCurrentTimeInMillis() + + // get the categories + val categories = childCategories.get(deviceUserEntry.id).waitForNonNullValue() + val temporarilyAllowedApps = temporarilyAllowedApps.waitForNonNullValue() + + // get the current status + val isScreenOn = appLogic.platformIntegration.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 } + + 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) { + 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 nowTimezone = TimeZone.getTimeZone(deviceUserEntry.timeZone) + + val nowDate = DateInTimezone.newInstance(nowTimestamp, nowTimezone) + val minuteOfWeek = getMinuteOfWeek(nowTimestamp, nowTimezone) + + // disable time limits temporarily feature + if (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 + (category.blockedMinutesInWeek.read(minuteOfWeek)) + ) { + 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() + + if (rules.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 usedTimes = usedTimesOfCategoryAndWeekByFirstDayOfWeek.get(Pair(category.id, nowDate.dayOfEpoch - nowDate.dayOfWeek)).waitForNonNullValue() + + val newUsedTimeItemBatchUpdateHelper = UsedTimeItemBatchUpdateHelper.eventuallyUpdateInstance( + date = nowDate, + categoryId = category.id, + oldInstance = usedTimeUpdateHelper, + usedTimeItemForDay = usedTimes.get(nowDate.dayOfWeek), + logic = appLogic + ) + usedTimeUpdateHelper = newUsedTimeItemBatchUpdateHelper + + val usedTimesSparseArray = SparseLongArray() + + for (i in 0..6) { + val usedTimesItem = usedTimes[i]?.usedMillis + + if (newUsedTimeItemBatchUpdateHelper.date.dayOfWeek == i) { + usedTimesSparseArray.put(i, newUsedTimeItemBatchUpdateHelper.getTotalUsedTime()) + } else { + usedTimesSparseArray.put(i, (if (usedTimesItem != null) usedTimesItem else 0)) + } + } + + val remaining = RemainingTime.getRemainingTime( + nowDate.dayOfWeek, usedTimesSparseArray, rules, + Math.max(0, category.extraTimeInMillis - newUsedTimeItemBatchUpdateHelper.getCachedExtraTimeToSubtract()) + ) + + 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 { + 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( + newProtectionLevel = null, + newUsageStatsPermissionStatus = null, + newNotificationAccessPermission = null, + 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() + + 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() + + val emptyChanges = UpdateDeviceStatusAction( + newProtectionLevel = null, + newUsageStatsPermissionStatus = null, + newNotificationAccessPermission = null, + newAppVersion = null + ) + + var changes = emptyChanges + + 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 != emptyChanges) { + ApplyActionUtil.applyAppLogicAction(changes, appLogic) + } + } + } + } + + suspend fun resetTemporarilyAllowedApps() { + Threads.database.executeAndWait(Runnable { + appLogic.database.temporarilyAllowedApp().removeAllTemporarilyAllowedAppsSync() + }) + } + + 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..1553a9c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/BlockingReason.kt @@ -0,0 +1,235 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 +} + +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.database.temporarilyAllowedApp().getTemporarilyAllowedApps().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) { + liveDataFromValue(BlockingReason.NotPartOfAnCategory) + } else if (categoryEntry.temporarilyBlocked) { + liveDataFromValue(BlockingReason.TemporarilyBlocked) + } else { + getBlockingReasonStep4Point5(categoryEntry, child, timeZone) + } + } + } + + private fun getBlockingReasonStep4Point5(category: Category, child: User, timeZone: TimeZone): LiveData { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "step 4.5") + } + + val areLimitsDisabled: LiveData + + if (child.disableLimitsUntil == 0L) { + areLimitsDisabled = liveDataFromValue(false) + } else { + areLimitsDisabled = timeInMillis.map { timeInMillis -> + child.disableLimitsUntil > timeInMillis + } + } + + return areLimitsDisabled.switchMap { + limitsDisabled -> + + if (limitsDisabled) { + liveDataFromValue(BlockingReason.None) + } else { + getBlockingReasonStep5(category, timeZone) + } + } + } + + private fun getBlockingReasonStep5(category: Category, timeZone: TimeZone): LiveData { + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "step 5") + } + + return Transformations.switchMap(getMinuteOfWeekLive(appLogic.timeApi, timeZone)) { + trustedMinuteOfWeek -> + + if (category.blockedMinutesInWeek.dataNotToModify.isEmpty) { + getBlockingReasonStep6(category, timeZone) + } 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 getDateLive(appLogic.timeApi, timeZone).switchMap { + nowTrustedDate -> + + appLogic.database.timeLimitRules().getTimeLimitRulesByCategory(category.id).switchMap { + rules -> + + if (rules.isEmpty()) { + liveDataFromValue(BlockingReason.None) + } else { + getBlockingReasonStep7(category, nowTrustedDate, rules) + } + } + } + } + + 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 val timeInMillis: LiveData = liveDataFromFunction { + appLogic.timeApi.getCurrentTimeInMillis() + } + + private fun getMinuteOfWeekLive(api: TimeApi, timeZone: TimeZone): LiveData = liveDataFromFunction { + getMinuteOfWeek(api.getCurrentTimeInMillis(), timeZone) + }.ignoreUnchanged() + + private fun getDateLive(api: TimeApi, timeZone: TimeZone): LiveData = liveDataFromFunction { + DateInTimezone.newInstance(api.getCurrentTimeInMillis(), timeZone) + }.ignoreUnchanged() +} 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..620a3c3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/DefaultAppLogic.kt @@ -0,0 +1,30 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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!! + } +} 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..4d7798e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/ManipulationLogic.kt @@ -0,0 +1,99 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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("opentimelimit1234")) { + 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..c42bf14 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/QueryAppTitleCache.kt @@ -0,0 +1,39 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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!! + } + } +} 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..e796d6a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/RemainingTime.kt @@ -0,0 +1,89 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 { + 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/SyncInstalledAppsLogic.kt b/app/src/main/java/io/timelimit/android/logic/SyncInstalledAppsLogic.kt new file mode 100644 index 0000000..ba3744b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/SyncInstalledAppsLogic.kt @@ -0,0 +1,101 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 userEntry = appLogic.deviceUserEntry.waitForNullableValue() + + if (userEntry == null || userEntry.type != UserType.Child) { + return@withLock + } + + val currentlyInstalled = appLogic.platformIntegration.getLocalApps().associateBy { app -> app.packageName } + val currentlySaved = appLogic.database.app().getApps().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..27ec20f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/TestAppLogic.kt @@ -0,0 +1,37 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 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 + +class TestAppLogic(maximumProtectionLevel: ProtectionLevel, context: Context) { + val platformIntegration = DummyIntegration(maximumProtectionLevel) + val timeApi = DummyTimeApi(100) + val database = RoomDatabase.createInMemoryInstance(context) + + val logic = AppLogic( + platformIntegration = platformIntegration, + timeApi = timeApi, + database = database, + 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..dbe4834 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/logic/UsedTimeItemBatchUpdateHelper.kt @@ -0,0 +1,103 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 categoryId: String, var cachedItem: UsedTimeItem?) { + companion object { + suspend fun eventuallyUpdateInstance( + date: DateInTimezone, + categoryId: String, + oldInstance: UsedTimeItemBatchUpdateHelper?, + usedTimeItemForDay: UsedTimeItem?, + logic: AppLogic + ): UsedTimeItemBatchUpdateHelper { + if (oldInstance != null && oldInstance.date == date && oldInstance.categoryId == categoryId) { + if (oldInstance.cachedItem != usedTimeItemForDay) { + oldInstance.cachedItem = usedTimeItemForDay + } + + return oldInstance + } else { + if (oldInstance != null) { + oldInstance.commit(logic) + } + + return UsedTimeItemBatchUpdateHelper( + date = date, + categoryId = categoryId, + cachedItem = usedTimeItemForDay + ) + } + } + } + + 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 getTotalUsedTime(): Long { + val cachedItem = cachedItem + + return (if (cachedItem == null) 0 else cachedItem.usedMillis) + timeToAdd + } + + fun getCachedExtraTimeToSubtract(): Int { + return extraTimeToSubtract + } + + suspend fun queryCurrentStatusFromDatabase(database: Database) { + cachedItem = database.usedTimes().getUsedTimeItem(categoryId, date.dayOfEpoch).waitForNullableValue() + } + + suspend fun commit(logic: AppLogic) { + if (timeToAdd == 0) { + // do nothing + } else { + ApplyActionUtil.applyAppLogicAction( + AddUsedTimeAction( + categoryId = categoryId, + timeToAdd = timeToAdd, + dayOfEpoch = date.dayOfEpoch, + extraTimeToSubtract = extraTimeToSubtract + ), + logic + ) + + timeToAdd = 0 + extraTimeToSubtract = 0 + + queryCurrentStatusFromDatabase(logic.database) + } + } +} 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..c5d4e7a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/Actions.kt @@ -0,0 +1,255 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.IdGenerator +import io.timelimit.android.data.customtypes.ImmutableBitmask +import io.timelimit.android.data.model.AppRecommendation +import io.timelimit.android.data.model.TimeLimitRule +import io.timelimit.android.data.model.UserType +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.sync.validation.ListValidation + +// 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. + * + */ + +// base types +sealed class Action + +sealed class AppLogicAction: Action() +sealed class ParentAction: Action() + +// +// now the concrete actions +// + +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() + } + } +} + +data class InstalledApp(val packageName: String, val title: String, val isLaunchable: Boolean, val recommendation: AppRecommendation) +data class AddInstalledAppsAction(val apps: List): AppLogicAction() { + init { + ListValidation.assertNotEmptyListWithoutDuplicates(apps.map { it.packageName }) + } +} +data class RemoveInstalledAppsAction(val packageNames: List): AppLogicAction() { + init { + ListValidation.assertNotEmptyListWithoutDuplicates(packageNames) + } +} + +data class AddCategoryAppsAction(val categoryId: String, val packageNames: List): ParentAction() { + init { + IdGenerator.assertIdValid(categoryId) + ListValidation.assertNotEmptyListWithoutDuplicates(packageNames) + } +} +data class RemoveCategoryAppsAction(val categoryId: String, val packageNames: List): ParentAction() { + init { + IdGenerator.assertIdValid(categoryId) + ListValidation.assertNotEmptyListWithoutDuplicates(packageNames) + } +} + +data class CreateCategoryAction(val childId: String, val categoryId: String, val title: String): ParentAction() { + init { + IdGenerator.assertIdValid(categoryId) + IdGenerator.assertIdValid(childId) + } +} +data class DeleteCategoryAction(val categoryId: String): ParentAction() { + init { + IdGenerator.assertIdValid(categoryId) + } +} +data class UpdateCategoryTitleAction(val categoryId: String, val newTitle: String): ParentAction() { + init { + IdGenerator.assertIdValid(categoryId) + } +} +data class SetCategoryExtraTimeAction(val categoryId: String, val newExtraTime: Long): ParentAction() { + init { + IdGenerator.assertIdValid(categoryId) + + if (newExtraTime < 0) { + throw IllegalArgumentException("newExtraTime must be >= 0") + } + } +} +data class IncrementCategoryExtraTimeAction(val categoryId: String, val addedExtraTime: Long): ParentAction() { + init { + IdGenerator.assertIdValid(categoryId) + + if (addedExtraTime <= 0) { + throw IllegalArgumentException("addedExtraTime must be more than zero") + } + } +} +data class UpdateCategoryTemporarilyBlockedAction(val categoryId: String, val blocked: Boolean): ParentAction() { + init { + IdGenerator.assertIdValid(categoryId) + } +} + +// DeviceDao + +data class UpdateDeviceStatusAction( + val newProtectionLevel: ProtectionLevel?, + val newUsageStatsPermissionStatus: RuntimePermissionStatus?, + val newNotificationAccessPermission: NewPermissionStatus?, + val newAppVersion: Int? +): AppLogicAction() { + init { + if (newAppVersion != null && newAppVersion < 0) { + throw IllegalArgumentException() + } + } +} + +data class IgnoreManipulationAction( + val deviceId: String, + val ignoreDeviceAdminManipulation: Boolean, + val ignoreDeviceAdminManipulationAttempt: Boolean, + val ignoreAppDowngrade: Boolean, + val ignoreNotificationAccessManipulation: Boolean, + val ignoreUsageStatsAccessManipulation: Boolean, + val ignoreHadManipulation: Boolean +): ParentAction() { + init { + IdGenerator.assertIdValid(deviceId) + } + + val isEmpty = (!ignoreDeviceAdminManipulation) && + (!ignoreDeviceAdminManipulationAttempt) && + (!ignoreAppDowngrade) && + (!ignoreNotificationAccessManipulation) && + (!ignoreUsageStatsAccessManipulation) && + (!ignoreHadManipulation) +} + +object TriedDisablingDeviceAdminAction: AppLogicAction() + +data class SetDeviceUserAction(val deviceId: String, val userId: String): ParentAction() { + // user id can be an empty string + init { + IdGenerator.assertIdValid(deviceId) + + if (userId != "") { + IdGenerator.assertIdValid(userId) + } + } +} + +data class UpdateCategoryBlockedTimesAction(val categoryId: String, val blockedTimes: ImmutableBitmask): ParentAction() { + init { + IdGenerator.assertIdValid(categoryId) + } +} + +data class CreateTimeLimitRuleAction(val rule: TimeLimitRule): ParentAction() + +data class UpdateTimeLimitRuleAction(val ruleId: String, val dayMask: Byte, val maximumTimeInMillis: Int, val applyToExtraTimeUsage: Boolean): ParentAction() { + 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() + } + } +} + +data class DeleteTimeLimitRuleAction(val ruleId: String): ParentAction() { + init { + IdGenerator.assertIdValid(ruleId) + } +} + +// UserDao +data class AddUserAction(val name: String, val userType: UserType, val password: String?, val userId: String, val timeZone: String): ParentAction() { + init { + if (userType == UserType.Parent) { + password!! + } + + IdGenerator.assertIdValid(userId) + } +} + +data class ChangeParentPasswordAction( + val parentUserId: String, + val newPassword: String +): ParentAction() { + init { + IdGenerator.assertIdValid(parentUserId) + + if (newPassword.isEmpty()) { + throw IllegalArgumentException("missing required parameter") + } + } +} + +data class RemoveUserAction(val userId: String): ParentAction() { + init { + IdGenerator.assertIdValid(userId) + } +} + +data class SetUserDisableLimitsUntilAction(val childId: String, val timestamp: Long): ParentAction() { + init { + IdGenerator.assertIdValid(childId) + + if (timestamp < 0) { + throw IllegalArgumentException() + } + } +} + +data class UpdateDeviceNameAction(val deviceId: String, val name: String): ParentAction() { + init { + IdGenerator.assertIdValid(deviceId) + + if (name.isBlank()) { + throw IllegalArgumentException("new device name must not be blank") + } + } +} 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..22a607d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/DatabaseValidation.kt @@ -0,0 +1,49 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/apply/ApplyAction.kt b/app/src/main/java/io/timelimit/android/sync/actions/apply/ApplyAction.kt new file mode 100644 index 0000000..2ef0ac6 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/apply/ApplyAction.kt @@ -0,0 +1,78 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.integration.platform.PlatformIntegration +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.ManipulationLogic +import io.timelimit.android.sync.actions.AddCategoryAppsAction +import io.timelimit.android.sync.actions.AppLogicAction +import io.timelimit.android.sync.actions.ParentAction +import io.timelimit.android.sync.actions.SetDeviceUserAction +import io.timelimit.android.sync.actions.dispatch.LocalDatabaseAppLogicActionDispatcher +import io.timelimit.android.sync.actions.dispatch.LocalDatabaseParentActionDispatcher + +object ApplyActionUtil { + suspend fun applyAppLogicAction(action: AppLogicAction, appLogic: AppLogic) { + applyAppLogicAction(action, appLogic.database, appLogic.manipulationLogic) + } + + private suspend fun applyAppLogicAction(action: AppLogicAction, database: Database, manipulationLogic: ManipulationLogic) { + Threads.database.executeAndWait { + database.transaction().use { + LocalDatabaseAppLogicActionDispatcher.dispatchAppLogicActionSync(action, database.config().getOwnDeviceIdSync()!!, database, manipulationLogic) + + database.setTransactionSuccessful() + } + } + } + + suspend fun applyParentAction(action: ParentAction, database: Database, platformIntegration: PlatformIntegration) { + Threads.database.executeAndWait { + database.transaction().use { + 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() + } + } + + database.setTransactionSuccessful() + } + } + } +} 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..44c9627 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/dispatch/AppLogicAction.kt @@ -0,0 +1,180 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 -> { + DatabaseValidation.assertCategoryExists(database, action.categoryId) + + // try to update + val updatedRows = database.usedTimes().addUsedTime( + categoryId = action.categoryId, + timeToAdd = action.timeToAdd, + dayOfEpoch = action.dayOfEpoch + ) + + if (updatedRows == 0) { + // create new entry + + database.usedTimes().insertUsedTime(UsedTimeItem( + categoryId = action.categoryId, + dayOfEpoch = action.dayOfEpoch, + usedMillis = action.timeToAdd.toLong() + )) + } // required to make this compile + + + if (action.extraTimeToSubtract != 0) { + database.category().subtractCategoryExtraTime( + categoryId = action.categoryId, + removedExtraTime = action.extraTimeToSubtract + ) + } else { + // required to make this compile + } + } + is AddInstalledAppsAction -> { + database.app().addAppsSync( + action.apps.map { + App( + packageName = it.packageName, + title = it.title, + isLaunchable = it.isLaunchable, + recommendation = it.recommendation + ) + } + ) + } + is RemoveInstalledAppsAction -> { + database.app().removeAppsByPackageNamesSync( + 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) + } + } + } + + 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 + } + }.let { } + + database.setTransactionSuccessful() + } finally { + database.endTransaction() + } + } +} 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..4739e92 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/actions/dispatch/ParentAction.kt @@ -0,0 +1,273 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + )) + } + 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.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 -> { + DatabaseValidation.assertCategoryExists(database, action.categoryId) + + if (action.addedExtraTime < 0) { + throw IllegalArgumentException("invalid added extra time") + } + + database.category().incrementCategoryExtraTime(action.categoryId, action.addedExtraTime) + } + 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, + disableLimitsUntil = 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 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.newPassword + ) + ) + } + 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.ignoreHadManipulation) { + deviceEntry = deviceEntry.copy(hadManipulation = false) + } + + database.device().updateDeviceEntry(deviceEntry) + } + }.let { } + + database.setTransactionSuccessful() + } finally { + database.endTransaction() + } + } +} 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..b7268d6 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/sync/validation/ListValidation.kt @@ -0,0 +1,28 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/ui/MainActivity.kt b/app/src/main/java/io/timelimit/android/ui/MainActivity.kt new file mode 100644 index 0000000..fb7af1f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/MainActivity.kt @@ -0,0 +1,151 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.R +import io.timelimit.android.async.Threads +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.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.setup.SetupTermsFragment + +class MainActivity : AppCompatActivity(), ActivityViewModelHolder { + companion object { + private const val AUTH_DIALOG_TAG = "adt" + } + + private val currentNavigatorFragment = MutableLiveData() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + // 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) }) + } + + override fun onOptionsItemSelected(item: MenuItem) = when { + item.itemId == android.R.id.home -> { + onBackPressed() + + true + } + else -> super.onOptionsItemSelected(item) + } + + override fun onStop() { + super.onStop() + + if (!isChangingConfigurations) { + getActivityViewModel().logOut() + } + } + + 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 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/diagnose/DiagnoseClockFragment.kt b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseClockFragment.kt new file mode 100644 index 0000000..cf75eca --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseClockFragment.kt @@ -0,0 +1,73 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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.map +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.DefaultAppLogic +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.timeApi.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 + }) + + 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..e54bbe9 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/diagnose/DiagnoseMainFragment.kt @@ -0,0 +1,42 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + ) + } + + return 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..fab6427 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/list/TextViewHolder.kt @@ -0,0 +1,28 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..82011fd --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/lock/LockActivity.kt @@ -0,0 +1,107 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.ViewModelProviders +import io.timelimit.android.R +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 + +class LockActivity : AppCompatActivity(), ActivityViewModelHolder { + companion object { + private const val EXTRA_PACKAGE_NAME = "packageName" + private const val LOGIN_DIALOG_TAG = "loginDialog" + + 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() + } + } + + 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 onStop() { + super.onStop() + + if (!isChangingConfigurations) { + getActivityViewModel().logOut() + } + } + + 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) + } + } + } +} 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..6cd69de --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/lock/LockFragment.kt @@ -0,0 +1,326 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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.Category +import io.timelimit.android.data.model.TemporarilyAllowedApp +import io.timelimit.android.data.model.User +import io.timelimit.android.data.model.UserType +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.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 + +class LockFragment : Fragment() { + companion object { + private const val EXTRA_PACKAGE_NAME = "packageName" + + 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) + ) + + binding.packageName = packageName + + if (title != null) { + binding.appTitle = title + } else { + binding.appTitle = "???" + } + + 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.Builder(user.id).build()) + .show(fragmentManager!!) + } + } + + binding.addToCategoryOptions.addView(button) + } + } + }) + + // bind adding extra time controls + binding.extraTimeBtnOk.setOnClickListener { + 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() + } + } + + // bind disable time limits + logic.deviceUserEntry.observe(this, Observer { + child -> + + if (child != null) { + binding.manageDisableTimeLimits.handlers = ManageDisableTimelimitsViewHelper.createHandlers( + childId = child.id, + childTimezone = child.timeZone, + activity = activity!! + ) + + binding.manageDisableTimeLimits.userName = child.name + } + }) + + mergeLiveData(logic.deviceUserEntry, liveDataFromFunction { logic.timeApi.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( + packageName = packageName + )) + }) + } + } + } + } + + 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() + } + } + + return binding.root + } +} + +interface Handlers { + fun openMainApp() + fun allowTemporarily() + fun disableTemporarilyLockForCurrentCategory() + fun disableTemporarilyLockForAllCategories() + fun showAuthenticationScreen() +} diff --git a/app/src/main/java/io/timelimit/android/ui/login/LoginPasswordDialogFragmentModel.kt b/app/src/main/java/io/timelimit/android/ui/login/LoginPasswordDialogFragmentModel.kt new file mode 100644 index 0000000..e8f61fb --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/login/LoginPasswordDialogFragmentModel.kt @@ -0,0 +1,87 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 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.crypto.PasswordHashing +import io.timelimit.android.livedata.castDown +import io.timelimit.android.livedata.waitForNullableValue +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.AuthenticatedUser +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +class LoginPasswordDialogFragmentModel(application: Application): AndroidViewModel(application) { + private val logic: AppLogic by lazy { DefaultAppLogic.with(application) } + private val statusInternal = MutableLiveData().apply{ + value = LoginPasswordDialogFragmentStatus.Idle + } + private val loginLock = Mutex() + + val status = statusInternal.castDown() + + fun tryLogin(userId: String, password: String, model: ActivityViewModel) { + runAsync { + loginLock.withLock { + statusInternal.value = LoginPasswordDialogFragmentStatus.Working + + val userEntry = logic.database.user().getUserByIdLive(userId).waitForNullableValue() + + if (userEntry == null) { + statusInternal.value = LoginPasswordDialogFragmentStatus.PermanentlyFailed + + return@runAsync + } + + val passwordValid = Threads.crypto.executeAndWait { PasswordHashing.validateSync(password, userEntry.password) } + + if (!passwordValid) { + statusInternal.value = LoginPasswordDialogFragmentStatus.PasswordWrong + + return@runAsync + } + + model.setAuthenticatedUser(AuthenticatedUser( + userId = userId, + passwordHash = userEntry.password + )) + + statusInternal.value = LoginPasswordDialogFragmentStatus.Success + } + } + } + + fun resetPasswordWrong() { + if (this.status.value == LoginPasswordDialogFragmentStatus.PasswordWrong) { + this.statusInternal.value = LoginPasswordDialogFragmentStatus.Idle + } + } +} + +enum class LoginPasswordDialogFragmentStatus { + Working, + PasswordWrong, + Idle, + Success, + PermanentlyFailed +} 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..e1c3820 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/login/LoginUserAdapter.kt @@ -0,0 +1,70 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..bbe7605 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/login/NewLoginFragment.kt @@ -0,0 +1,154 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.MutableLiveData +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.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.ui.main.getActivityViewModel + +class NewLoginFragment: DialogFragment() { + companion object { + private const val SELECTED_USER_ID = "selectedUserId" + } + + private val logic: AppLogic by lazy { DefaultAppLogic.with(context!!) } + private val selectedUserId = MutableLiveData().apply { value = null } + private val model: LoginPasswordDialogFragmentModel by lazy { + ViewModelProviders.of(this).get(LoginPasswordDialogFragmentModel::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) { + selectedUserId.value = savedInstanceState.getString(SELECTED_USER_ID) + } + } + + override fun onCreateDialog(savedInstanceState: Bundle?) = object: BottomSheetDialog(context!!, theme) { + override fun onBackPressed() { + if (selectedUserId.value == null) { + super.onBackPressed() + } else { + selectedUserId.value = null + } + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + + 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) + + binding.userList.apply { + val adapter = LoginUserAdapter() + + logic.database.user().getParentUsersLive().observe(this@NewLoginFragment, Observer { adapter.data = it }) + + adapter.listener = object: LoginUserAdapterListener { + override fun onUserClicked(user: User) { + selectedUserId.value = user.id + } + } + + recycler.adapter = adapter + recycler.layoutManager = LinearLayoutManager(context) + } + + binding.enterPassword.apply { + fun tryLogin() { + model.tryLogin( + userId = selectedUserId.value!!, + password = password.text.toString(), + model = getActivityViewModel(activity!!) + ) + } + + password.setOnEnterListenr { + tryLogin() + } + + model.status.observe(this@NewLoginFragment, Observer { + status -> + + val readyForInput = status == LoginPasswordDialogFragmentStatus.Idle + + password.isEnabled = readyForInput + + when (status) { + LoginPasswordDialogFragmentStatus.Working -> {/* nothing to do */} + LoginPasswordDialogFragmentStatus.Idle -> {/* nothing to do */} + LoginPasswordDialogFragmentStatus.PasswordWrong -> { + Toast.makeText(context!!, R.string.login_snackbar_wrong, Toast.LENGTH_SHORT).show() + password.setText("") + + model.resetPasswordWrong() + } + LoginPasswordDialogFragmentStatus.Success -> { + dismissAllowingStateLoss() + } + LoginPasswordDialogFragmentStatus.PermanentlyFailed -> selectedUserId.value = null + null -> {/* nothing to handle */} + }.let { } + }) + } + + selectedUserId.observe(this, Observer { + if (it == null) { + if (binding.switcher.displayedChild != 0) { + binding.switcher.setInAnimation(context!!, R.anim.wizard_close_step_in) + binding.switcher.setOutAnimation(context!!, R.anim.wizard_close_step_out) + binding.switcher.displayedChild = 0 + } + } else { + if (binding.switcher.displayedChild != 1) { + binding.switcher.setInAnimation(context!!, R.anim.wizard_open_step_in) + binding.switcher.setOutAnimation(context!!, R.anim.wizard_open_step_out) + binding.switcher.displayedChild = 1 + } + + binding.enterPassword.password.requestFocus() + inputMethodManager.showSoftInput(binding.enterPassword.password, 0) + } + }) + + 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..423f464 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/main/ActivityViewModel.kt @@ -0,0 +1,126 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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.ParentAction +import io.timelimit.android.sync.actions.apply.ApplyActionUtil + +class ActivityViewModel(application: Application): AndroidViewModel(application) { + companion object { + private const val LOG_TAG = "ActivityViewModel" + } + + private val logic = DefaultAppLogic.with(application) + private val database = logic.database + + val shouldHighlightAuthenticationButton = MutableLiveData().apply { value = false } + + private val authenticatedUserMetadata = MutableLiveData().apply { value = null } + + val authenticatedUser = authenticatedUserMetadata.switchMap { + authenticatedUser -> + + if (authenticatedUser == null) { + liveDataFromValue(null as Pair?) + } else { + database.user().getUserByIdLive(authenticatedUser.userId).map { + if (it == null || it.password != authenticatedUser.passwordHash) { + null + } else { + Pair(authenticatedUser, 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, + 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 passwordHash: 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..b4e00c8 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/main/ActivityViewModelHolder.kt @@ -0,0 +1,31 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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() + } +} 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..5c6d854 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/main/AuthenticationFab.kt @@ -0,0 +1,109 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + +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?.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..7dc385e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/main/FragmentWithCustomTitle.kt @@ -0,0 +1,22 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..a75c76e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/ManageCategoryFragment.kt @@ -0,0 +1,127 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 -> throw IllegalStateException() + } + + 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..6c9e0d1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/PagerAdapter.kt @@ -0,0 +1,38 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..5ecbe10 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/AppAdapter.kt @@ -0,0 +1,119 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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() + + 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..d1411e4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/CategoryAppsFragment.kt @@ -0,0 +1,92 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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 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..1cda6e0 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/CategoryAppsModel.kt @@ -0,0 +1,59 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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().getApps() + + 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..decb481 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/add/AddAppAdapter.kt @@ -0,0 +1,91 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..1034e53 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/apps/add/AddCategoryAppsFragment.kt @@ -0,0 +1,142 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 androidx.appcompat.app.AlertDialog +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentManager +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.map +import io.timelimit.android.livedata.mergeLiveData +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) + + binding.recycler.layoutManager = LinearLayoutManager(context) + binding.recycler.adapter = adapter + + mergeLiveData( + filter, + database.app().getApps() + .map { apps -> apps.distinctBy { app -> app.packageName } } + ).map { + searchTermAndApps -> + + val (search, apps) = searchTermAndApps + + apps?.filter { search?.matches(it) == true } + }.map { + apps -> + + apps?.sortedBy { app -> app.title.toLowerCase() } + }.observe(this, Observer { adapter.data = it }) + + database.category().getCategoriesByChildId(params.childId) + .switchMap { categories -> + val categoryById = categories.associateBy { it.id } + + database.categoryApp().getCategoryApps(categories.map { it.id }).map { apps -> + val categoryTitleByCategoryId = mutableMapOf() + + apps.forEach { + categoryTitleByCategoryId[it.packageName] = categoryById[it.categoryId]?.title ?: "" + } + + categoryTitleByCategoryId + } + }.observe(this, Observer { + adapter.categoryTitleByPackageName = it + }) + + return AlertDialog.Builder(context!!, R.style.AppTheme) + .setView(binding.root) + .setPositiveButton(R.string.category_apps_add_dialog_btn_positive) { + _, _-> + + val packageNames = adapter.selectedApps.toList() + + if (packageNames.isNotEmpty()) { + auth.tryDispatchParentAction( + AddCategoryAppsAction( + categoryId = params.categoryId, + packageNames = packageNames + ) + ) + } + } + .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/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..43d6fd7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/Adapter.kt @@ -0,0 +1,180 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..66c6ea4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/BlockedTimeAreasFragment.kt @@ -0,0 +1,234 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 -> + items.value = when (isChecked) { + true -> MinuteOfWeekItems + false -> FifteenMinutesOfWeekItems + } + } + } +} 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..40d4bd0 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/BlockedTimeAreasHelpDialog.kt @@ -0,0 +1,40 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 = "BlockedTimeAreasHelpDialog" + } + + 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..4e7fb44 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/FifteenMinutesOfWeekItems.kt @@ -0,0 +1,56 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 * 15, 15) + } + + 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 + 0 + itemsPerHour * item.hour + is MinuteTile -> item.day * itemsPerDay + 0 + itemsPerHour * item.hour + 1 + item.minute * 15 + } +} 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..9fb00cc --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/Items.kt @@ -0,0 +1,33 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..b7bb87d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/MinuteOfWeekItems.kt @@ -0,0 +1,62 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..d3270b4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/MinuteTileMode.kt @@ -0,0 +1,22 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..9b71a4c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/blocked_times/copy/CopyBlockedTimeAreasDialogFragment.kt @@ -0,0 +1,170 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 = "CopyBlockedTimeAreasDialogFragment" + private const val SELECTED_START_DAY = "selectedStartDay" + + 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..12ee2c3 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/settings/CategorySettingsFragment.kt @@ -0,0 +1,134 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.text.TextUtils +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import androidx.fragment.app.Fragment +import androidx.lifecycle.Observer +import androidx.lifecycle.Transformations +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.livedata.ignoreUnchanged +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.DeleteCategoryAction +import io.timelimit.android.sync.actions.SetCategoryExtraTimeAction +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 kotlinx.android.synthetic.main.fragment_category_settings.* + +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? { + return inflater.inflate(R.layout.fragment_category_settings, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + val categoryEntry = appLogic.database.category().getCategoryByChildIdAndId(params.childId, params.categoryId) + val categoryTitle = Transformations.map(categoryEntry) { it?.title }.ignoreUnchanged() + + categoryTitle.observe(this, Observer { + if (it != null) { + edit_category_title.setText(it) + } + }) + + checkbox_delete_category.setOnCheckedChangeListener { _, isChecked -> btn_delete_category.isEnabled = isChecked } + btn_delete_category.setOnClickListener { doDeleteCategory() } + + edit_category_title_go.setOnClickListener { doRenameCategory() } + edit_category_title.setOnEditorActionListener { _, actionId, _ -> + if (actionId == EditorInfo.IME_ACTION_GO) { + doRenameCategory() + + true + } else { + false + } + } + + categoryEntry.observe(this, Observer { + if (it != null) { + val roundedCurrentTimeInMillis = (it.extraTimeInMillis / (1000 * 60)) * (1000 * 60) + + if (extra_time_selection.timeInMillis != roundedCurrentTimeInMillis) { + extra_time_selection.timeInMillis = roundedCurrentTimeInMillis + } + } + }) + + extra_time_btn_ok.setOnClickListener { + val newExtraTime = extra_time_selection.timeInMillis + + if ( + auth.tryDispatchParentAction( + SetCategoryExtraTimeAction( + categoryId = params.categoryId, + newExtraTime = newExtraTime + ) + ) + ) { + Snackbar.make(view, R.string.category_settings_extra_time_change_toast, Snackbar.LENGTH_SHORT).show() + } + } + } + + private fun doRenameCategory() { + val newTitle = edit_category_title.text.toString() + + if (TextUtils.isEmpty(newTitle)) { + Snackbar.make(edit_category_title, R.string.category_settings_rename_empty, Snackbar.LENGTH_SHORT).show() + return + } + + if ( + auth.tryDispatchParentAction( + UpdateCategoryTitleAction( + categoryId = params.categoryId, + newTitle = newTitle + ) + ) + ) { + Snackbar.make(edit_category_title, R.string.category_settings_rename_success, Snackbar.LENGTH_SHORT).show() + } + } + + private fun doDeleteCategory() { + auth.tryDispatchParentAction(DeleteCategoryAction( + categoryId = params.categoryId + )) + } +} 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..6dd2e8d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/Adapter.kt @@ -0,0 +1,132 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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 + } + + var data: List? by Delegates.observable(null as List?) { _, _, _ -> notifyDataSetChanged() } + var usedTimes: List? by Delegates.observable(null as List?) { _, _, _ -> notifyDataSetChanged() } + var handlers: Handlers? = null + + init { + setHasStableIds(true) + } + + private fun getItem(position: Int): TimeLimitRule { + return data!![position] + } + + override fun getItemId(position: Int): Long = when { + position == data!!.size -> 1 + else -> getItem(position).id.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) = 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 + ) + } + 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 ItemViewHolder).view + val dayNames = binding.root.resources.getStringArray(R.array.days_of_week_array) + val usedTime = usedTimes?.mapIndexed { index, value -> + if (item.dayMask.toInt() and (1 shl index) != 0) { + value + } else { + 0 + } + }?.sum()?.toInt() ?: 0 + + binding.maxTimeString = TimeTextUtil.time(item.maximumTimeInMillis, binding.root.context) + binding.usageAsText = TimeTextUtil.used(usedTime, binding.root.context) + binding.usageProgressInPercent = if (item.maximumTimeInMillis > 0) + (usedTime * 100 / item.maximumTimeInMillis) + else + 100 + binding.daysString = JoinUtil.join( + dayNames.filterIndexed { index, _ -> (item.dayMask.toInt() and (1 shl index)) != 0 }, + binding.root.context + ) + binding.appliesToExtraTime = item.applyToExtraTimeUsage + binding.card.setOnClickListener { handlers?.onTimeLimitRuleClicked(item) } + + binding.executePendingBindings() + } + } +} + +open class ViewHolder(view: View): RecyclerView.ViewHolder(view) +class ItemViewHolder(val view: FragmentCategoryTimeLimitRuleItemBinding): ViewHolder(view.root) + +interface Handlers { + fun onTimeLimitRuleClicked(rule: TimeLimitRule) + fun onAddTimeLimitRuleClicked() +} 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..e2e1cb0 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/CategoryTimeLimitRulesFragment.kt @@ -0,0 +1,140 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.data.Database +import io.timelimit.android.data.extensions.getDateLive +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.timeApi) + + val usedTimeItems = userDate.switchMap { + date -> + + database.usedTimes().getUsedTimesOfWeek( + categoryId = params.categoryId, + firstDayOfWeekAsEpochDay = date.dayOfEpoch - date.dayOfWeek + ) + } + + rules + .map { rules -> + rules.sortedBy { it.dayMask } + } + .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 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/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..f82f572 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/timelimit_rules/edit/EditTimeLimitRuleDialogFragment.kt @@ -0,0 +1,280 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 = "existingRule" + private const val PARAM_CATEGORY_ID = "categoryId" + private const val DIALOG_TAG = "EditTimeLimitRuleDialogFragment" + private const val STATE_RULE = "currentRule" + + 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() + + view.timeSpan.maxDays = Math.max(0, (0..6).map { (newRule.dayMask.toInt() shr it) and 1 }.sum() - 1) + } + + 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..7a3f0a6 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/usagehistory/UsageHistoryAdapter.kt @@ -0,0 +1,68 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..70c1f99 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/category/usagehistory/UsageHistoryFragment.kt @@ -0,0 +1,59 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..e991492 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/ManageChildFragment.kt @@ -0,0 +1,113 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 -> throw IllegalStateException() + } + + 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..71de9f2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/PagerAdapter.kt @@ -0,0 +1,33 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/DeleteChildView.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/DeleteChildView.kt new file mode 100644 index 0000000..d49082f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/DeleteChildView.kt @@ -0,0 +1,50 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 io.timelimit.android.databinding.DeleteChildViewBinding +import io.timelimit.android.sync.actions.RemoveUserAction +import io.timelimit.android.ui.main.ActivityViewModel + +object DeleteChildView { + fun bind( + model: ActivityViewModel, + view: DeleteChildViewBinding, + childId: String + ) { + view.btnConfirmDeleteUser.isEnabled = view.checkConfirmDeleteUser.isChecked + + view.btnConfirmDeleteUser.setOnClickListener { + model.tryDispatchParentAction( + RemoveUserAction( + userId = childId + ) + ) + } + + view.checkConfirmDeleteUser.setOnCheckedChangeListener { _, isChecked -> + if (isChecked) { + if (!model.requestAuthenticationOrReturnTrue()) { + view.checkConfirmDeleteUser.isChecked = false + } else { + view.btnConfirmDeleteUser.isEnabled = true + } + } else { + view.btnConfirmDeleteUser.isEnabled = false + } + } + } +} 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..bcab001 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/ManageChildAdvancedFragment.kt @@ -0,0 +1,130 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + +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) + + categoriesLive.observe(this, Observer { + categories -> + + 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 (!auth.tryDispatchParentAction( + UpdateCategoryTemporarilyBlockedAction( + categoryId = category.id, + blocked = !category.temporarilyBlocked + ) + )) { + checkbox.isChecked = category.temporarilyBlocked + } + } + } + + binding.blockedCategoriesCheckboxContainer.addView(checkbox) + } + }) + } + + run { + // disable time limits + + childEntry.observe(this, Observer { + child -> + + if (child != null) { + binding.disableTimeLimits.handlers = ManageDisableTimelimitsViewHelper.createHandlers( + childId = params.childId, + childTimezone = child.timeZone, + activity = activity!! + ) + + binding.disableTimeLimits.userName = child.name + } + }) + + mergeLiveData(childEntry, liveDataFromFunction { logic.timeApi.getCurrentTimeInMillis() }).map { + (child, time) -> + + if (time == null || child == null) { + null + } else { + ManageDisableTimelimitsViewHelper.getDisabledUntilString(child, time, context!!) + } + }.observe(this, Observer { + binding.disableTimeLimits.disableTimeLimitsUntilString = it + }) + } + + DeleteChildView.bind( + model = auth, + view = binding.deleteChild, + childId = params.childId + ) + + return binding.root + } +} 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..4196456 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/DisableTimelimitsUntilDateDialogFragment.kt @@ -0,0 +1,133 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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 = "childId" + private const val DIALOG_TAG = "DisableTimelimitsUntilDateDialogFragment" + } + + 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() = logic.timeApi.getCurrentTimeInMillis() + + 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..1d2ddb1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/DisableTimelimitsUntilTimeDialogFragment.kt @@ -0,0 +1,137 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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 = "childId" + private const val DIALOG_TAG = "DisableTimelimitsUntilTimeDialogFragment" + } + + 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() = logic.timeApi.getCurrentTimeInMillis() + + 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..a121519 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/advanced/managedisabletimelimits/ManageDisableTimelimitsViewHelper.kt @@ -0,0 +1,100 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.sync.actions.SetUserDisableLimitsUntilAction +import io.timelimit.android.ui.main.getActivityViewModel +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): ManageDisableTimelimitsViewHandlers { + val auth = getActivityViewModel(activity) + val logic = DefaultAppLogic.with(activity) + + fun getCurrentTime() = logic.timeApi.getCurrentTimeInMillis() + + return object : ManageDisableTimelimitsViewHandlers { + override fun disableTimeLimitsForDuration(duration: Long) { + auth.tryDispatchParentAction( + SetUserDisableLimitsUntilAction( + childId = childId, + timestamp = getCurrentTime() + duration + ) + ) + } + + override fun disableTimeLimitsForToday() { + 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 (auth.requestAuthenticationOrReturnTrue()) { + DisableTimelimitsUntilDateDialogFragment.newInstance(childId).show(activity.supportFragmentManager) + } + } + + override fun disableTimeLimitsUntilSelectedTimeOfToday() { + 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/apps/ChildAppsAdapter.kt b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsAdapter.kt new file mode 100644 index 0000000..59f5f6e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsAdapter.kt @@ -0,0 +1,152 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..4b3a87d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsFragment.kt @@ -0,0 +1,95 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.listContentLive.observe(this, Observer { + adapter.data = it + }) + + 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..897c8e6 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/ChildAppsModel.kt @@ -0,0 +1,134 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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 } + + private val childAppsLive = database.app().getApps() + 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..add4ba1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/assign/AssignAllAppsCategoryDialogFragment.kt @@ -0,0 +1,121 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.AssignAppDialogBinding +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 = "childId" + private const val EXTRA_PACKAGE_NAMES = "packageNames" + private const val TAG = "AssignAllAppsCategoryDialogFragment" + + 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 = AssignAppDialogBinding.inflate(inflater, container, false) + val list = binding.categoryList + + binding.appTitle = 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..e2cc60a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/apps/assign/AssignAppCategoryDialogFragment.kt @@ -0,0 +1,167 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.App +import io.timelimit.android.data.model.Category +import io.timelimit.android.data.model.CategoryApp +import io.timelimit.android.data.model.UserType +import io.timelimit.android.databinding.AssignAppDialogBinding +import io.timelimit.android.extensions.showSafe +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 = "childId" + private const val EXTRA_PACKAGE_NAME = "packageName" + private const val TAG = "AssignAppCategoryDialogFragment" + + 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 matchingAppEntries: LiveData> by lazy { + database.app().getAppsByPackageName(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 = AssignAppDialogBinding.inflate(inflater, container, false) + + val list = binding.categoryList + + 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.appTitle = 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..3b52b5d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/category/Adapter.kt @@ -0,0 +1,141 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + } + + 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() + }.toLong() + } + + override fun getItemViewType(position: Int) = when (getItem(position)) { + is CategoryItem -> TYPE_ITEM + CreateCategoryItem -> TYPE_ADD + CategoriesIntroductionHeader -> TYPE_INTRO + } + + 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) + ) + + 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.card.setOnClickListener { handlers?.onCategoryClicked(item.category) } + + binding.executePendingBindings() + } + CreateCategoryItem -> { + // nothing to do + } + CategoriesIntroductionHeader -> { + // 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 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..6213caa --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/category/Items.kt @@ -0,0 +1,28 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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() +data class CategoryItem( + val category: Category, + val isBlockedTimeNow: Boolean, + val remainingTimeToday: Long?, + val usedTimeToday: Long +): 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..0bb7473 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/category/ManageChildCategoriesFragment.kt @@ -0,0 +1,113 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..c452de2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/category/ManageChildCategoriesModel.kt @@ -0,0 +1,125 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 childEntry = childId.switchMap { logic.database.user().getChildUserByIdLive(it) } + + private val childTimezone = childEntry.mapToTimezone() + + private val childMinuteOfWeek = childTimezone.switchMap { timeZone -> + liveDataFromFunction { getMinuteOfWeek(logic.timeApi.getCurrentTimeInMillis(), timeZone) } + }.ignoreUnchanged() + + private val childDate = childTimezone.switchMap { timeZone -> + liveDataFromFunction { DateInTimezone.newInstance(logic.timeApi.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 = 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() + + 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 + ) + } + } + } + } + } + }.ignoreUnchanged() + + private val hasShownHint = logic.database.config().wereHintsShown(HintsToShow.CATEGORIES_INTRODUCTION) + + val listContent = hasShownHint.switchMap { hasShownHint -> + categoryItems.map { categoryItems -> + if (hasShownHint) { + categoryItems + listOf(CreateCategoryItem) + } else { + listOf(CategoriesIntroductionHeader) + categoryItems + listOf(CreateCategoryItem) + } + } + } +} 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..4222762 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/child/category/create/CreateCategoryDialogFragment.kt @@ -0,0 +1,68 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 = "CreateCategoryDialogFragment" + + 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/device/manage/InformAboutDeviceOwnerDialogFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/InformAboutDeviceOwnerDialogFragment.kt new file mode 100644 index 0000000..f5d910f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/InformAboutDeviceOwnerDialogFragment.kt @@ -0,0 +1,56 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.R +import io.timelimit.android.extensions.showSafe +import io.timelimit.android.integration.platform.android.AdminReceiver + +class InformAboutDeviceOwnerDialogFragment: DialogFragment() { + companion object { + private const val TAG = "InformAboutDeviceOwnerDialogFragment" + + val shouldShow = 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..b99e61f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceFragment.kt @@ -0,0 +1,329 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.MutableLiveData +import androidx.lifecycle.Observer +import androidx.navigation.Navigation +import com.google.android.material.snackbar.Snackbar +import io.timelimit.android.R +import io.timelimit.android.data.model.Device +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.liveDataFromValue +import io.timelimit.android.livedata.map +import io.timelimit.android.livedata.mergeLiveData +import io.timelimit.android.livedata.switchMap +import io.timelimit.android.logic.AppLogic +import io.timelimit.android.logic.DefaultAppLogic +import io.timelimit.android.sync.actions.SetDeviceUserAction +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.main.AuthenticationFab +import io.timelimit.android.ui.main.FragmentWithCustomTitle + +class ManageDeviceFragment : Fragment(), FragmentWithCustomTitle { + companion object { + private const val IS_EDITING_DEVICE_TITLE = "a" + } + + 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) + } + + private var isEditingDeviceTitle = MutableLiveData().apply { value = false } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + if (savedInstanceState != null) { + isEditingDeviceTitle.value = savedInstanceState.getBoolean(IS_EDITING_DEVICE_TITLE) + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + + outState.putBoolean(IS_EDITING_DEVICE_TITLE, isEditingDeviceTitle.value!!) + } + + 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() + + ManageDeviceManipulation.bindView( + binding = binding.manageManipulation, + deviceEntry = deviceEntry, + lifecycleOwner = this, + activityViewModel = auth + ) + + 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 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) { + startActivity( + Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN) + .putExtra( + DevicePolicyManager.EXTRA_DEVICE_ADMIN, + ComponentName(context!!, AdminReceiver::class.java) + ) + ) + } else { + InformAboutDeviceOwnerDialogFragment().show(fragmentManager!!) + } + } else { + startActivity( + Intent(Settings.ACTION_SECURITY_SETTINGS) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } + } + } + + override fun startEditDeviceTitle() { + if (auth.requestAuthenticationOrReturnTrue()) { + binding.newDeviceTitleText.setText(binding.deviceTitle) + isEditingDeviceTitle.value = true + } + } + + override fun doEditDeviceTitle() { + val newDeviceTitle = binding.newDeviceTitleText.text.toString() + + if (newDeviceTitle.isBlank()) { + Snackbar.make(binding.newDeviceTitleText, R.string.manage_device_rename_toast_empty, Snackbar.LENGTH_SHORT).show() + } else { + if (auth.tryDispatchParentAction( + UpdateDeviceNameAction( + deviceId = args.deviceId, + name = newDeviceTitle + ) + )) { + isEditingDeviceTitle.value = false + } + } + } + + 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 = logic.timeApi.getCurrentTimeInMillis() + + binding.deviceTitle = device.name + binding.modelString = device.model + binding.addedAtString = getString(R.string.manage_device_added_at, DateUtils.getRelativeTimeSpanString( + device.addedAt, + now, + DateUtils.HOUR_IN_MILLIS + + )) + 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() + } + }) + + logic.deviceId.observe(this, Observer { + ownDeviceId -> + + binding.isThisDevice = ownDeviceId == args.deviceId + }) + + isEditingDeviceTitle.observe(this, Observer { binding.isEditingDeviceTitle = 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 + ) + + return binding.root + } + + override fun onResume() { + super.onResume() + + logic.backgroundTaskLogic.syncDeviceStatusAsync() + } + + override fun getCustomTitle() = deviceEntry.map { it?.name } +} + +interface ManageDeviceFragmentHandlers { + fun openUsageStatsSettings() + fun openNotificationAccessSettings() + fun manageDeviceAdmin() + fun startEditDeviceTitle() + fun doEditDeviceTitle() + 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..8fb2943 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceIntroduction.kt @@ -0,0 +1,39 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..05cef9a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/ManageDeviceManipulation.kt @@ -0,0 +1,103 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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.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, + 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/UsageStatsAccessRequiredAndMissing.kt b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/UsageStatsAccessRequiredAndMissing.kt new file mode 100644 index 0000000..0a307d1 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/device/manage/UsageStatsAccessRequiredAndMissing.kt @@ -0,0 +1,39 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/parent/ManageParentFragment.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentFragment.kt new file mode 100644 index 0000000..f1abb56 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentFragment.kt @@ -0,0 +1,114 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 + } + }) + + if (!wereViewsCreated) { + wereViewsCreated = true + + parentUser.observe(this, Observer { + user -> + + if (user == null) { + navigation.popBackStack() + } + }) + } + + DeleteParentView.bind( + view = binding.deleteParent, + lifecycleOwner = this, + model = model.deleteParentModel + ) + + binding.handlers = object: ManageParentFragmentHandlers { + override fun onChangePasswordClicked() { + navigation.safeNavigate( + ManageParentFragmentDirections. + actionManageParentFragmentToChangeParentPasswordFragment( + params.parentId + ), + R.id.manageParentFragment + ) + } + } + + return binding.root + } + + override fun getCustomTitle() = parentUser.map { it?.name } +} + +interface ManageParentFragmentHandlers { + fun onChangePasswordClicked() +} 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..52669cf --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/ManageParentModel.kt @@ -0,0 +1,29 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/delete/DeleteParentModel.kt b/app/src/main/java/io/timelimit/android/ui/manage/parent/delete/DeleteParentModel.kt new file mode 100644 index 0000000..fe44744 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/delete/DeleteParentModel.kt @@ -0,0 +1,115 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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 } + + val statusLive = 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 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 + } + + activityViewModelLive.value!!.tryDispatchParentAction( + RemoveUserAction( + userId = userEntry.id + ) + ) + } finally { + isWorkingInternal.value = false + } + } + } +} + +enum class Status { + 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..633129c --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/delete/DeleteParentView.kt @@ -0,0 +1,54 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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/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..c05e592 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/password/change/ChangeParentPasswordFragment.kt @@ -0,0 +1,116 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..6fd9bed --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manage/parent/password/change/ChangeParentPasswordViewModel.kt @@ -0,0 +1,138 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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.ChangeParentPasswordAction +import io.timelimit.android.sync.actions.apply.ApplyActionUtil + +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 newPasswordHash = PasswordHashing.hashCoroutine(newPassword) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "created hashs") + } + + val action = ChangeParentPasswordAction( + parentUserId = parentUserId, + newPassword = newPasswordHash + ) + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "created action") + } + + val currentUserEntry = logic.database.user().getUserByIdLive(parentUserId).waitForNullableValue() + + if (currentUserEntry == null || currentUserEntry.password != userEntry.password) { + statusInternal.value = ChangeParentPasswordViewModelStatus.Failed + return@runAsync + } + + if (BuildConfig.DEBUG) { + Log.d(LOG_TAG, "validated user a second time") + } + + ApplyActionUtil.applyParentAction(action, logic.database, 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/manipulation/UnlockAfterManipulationActivity.kt b/app/src/main/java/io/timelimit/android/ui/manipulation/UnlockAfterManipulationActivity.kt new file mode 100644 index 0000000..2c8a5f7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/manipulation/UnlockAfterManipulationActivity.kt @@ -0,0 +1,85 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..1206c93 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/about/AboutFragment.kt @@ -0,0 +1,56 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.method.LinkMovementMethod +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import io.timelimit.android.databinding.FragmentAboutBinding +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) + + binding.sourceCodeUrl.movementMethod = LinkMovementMethod.getInstance() + binding.termsText.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 AboutFragmentParentHandlers { + 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..7c4de14 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/about/ResetShownHints.kt @@ -0,0 +1,40 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..535d161 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/main/MainFragment.kt @@ -0,0 +1,188 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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.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) { + 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 -> throw IllegalStateException() + } + + true + } + + fun updateShowFab(selectedPage: Int) { + showAuthButtonLive.value = when (selectedPage) { + 0 -> true + 1 -> true + 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 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 openManageParentScreen(parentId: String) { + navigation.safeNavigate( + MainFragmentDirections.actionOverviewFragmentToManageParentFragment(parentId), + 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..05e1786 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/main/PagerAdapter.kt @@ -0,0 +1,33 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/OverviewFragment.kt b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragment.kt new file mode 100644 index 0000000..a1bc7c4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragment.kt @@ -0,0 +1,109 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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.* + +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 { } + } + } + + 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 openManageDeviceScreen(deviceId: String) + fun openManageChildScreen(childId: String) + fun openManageParentScreen(parentId: String) +} 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..6724b3f --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentAdapter.kt @@ -0,0 +1,203 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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.AddItemViewBinding +import io.timelimit.android.databinding.FragmentOverviewDeviceItemBinding +import io.timelimit.android.databinding.FragmentOverviewUserItemBinding +import io.timelimit.android.databinding.GenericListHeaderBinding +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 OverviewFragmentHeaderIntro -> OverviewFragmentViewType.Introduction + } + + 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.Introduction.ordinal -> IntroViewHolder( + LayoutInflater.from(parent.context) + .inflate(R.layout.fragment_overview_intro, 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.isMissingRequiredPermission = item.isMissingRequiredPermission + binding.executePendingBindings() + + binding.card.setOnClickListener { + this.handlers?.onDeviceClicked(item.device) + } + } + is OverviewFragmentActionAddUser -> { /* nothing to do */ } + is OverviewFragmentHeaderIntro -> { /* nothing to do */ } + }.let { } + } +} + +enum class OverviewFragmentViewType { + Header, + UserItem, + DeviceItem, + AddUserItem, + Introduction +} + +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 IntroViewHolder(view: View): OverviewFragmentViewHolder(view) + +interface OverviewFragmentHandlers { + fun onAddUserClicked() + fun onUserClicked(user: User) + fun onDeviceClicked(device: Device) +} 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..83617a4 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentItem.kt @@ -0,0 +1,31 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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): 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 OverviewFragmentHeaderIntro: OverviewFragmentItem() 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..1c2f82d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/overview/OverviewFragmentModel.kt @@ -0,0 +1,104 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.timeApi.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.map { devices -> + devices.map { (device, user) -> + OverviewFragmentItemDevice( + device = device, + deviceUser = user?.first, + isCurrentDevice = device.id == thisDeviceId + ) + } + } + } + + private val hasShownIntroduction = logic.database.config().wereHintsShown(HintsToShow.OVERVIEW_INTRODUCTION) + private val introEntries = hasShownIntroduction.map { hasShownIntro -> + val result = mutableListOf() + + 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(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..6c3893e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/overview/uninstall/UninstallFragment.kt @@ -0,0 +1,58 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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 + +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 (auth.requestAuthenticationOrReturnTrue()) { + logic.platformIntegration.setEnableSystemLockdown(false) + + if (revokePermissions) { + logic.platformIntegration.disableDeviceAdmin() + } + + runAsync { + logic.appSetupLogic.dangerousResetApp() + } + } + } +} 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..e8bbb00 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/SetupDevicePermissionsFragment.kt @@ -0,0 +1,130 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..7a6acaa --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/SetupLocalModeFragment.kt @@ -0,0 +1,109 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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!! + ) + } + + 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) { + runAsync { + if (status.value != Status.Idle) { + throw IllegalStateException() + } + + status.value = Status.Running + + try { + DefaultAppLogic.with(getApplication()).appSetupLogic.setupForLocalUse(parentPassword, 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/SetupTermsFragment.kt b/app/src/main/java/io/timelimit/android/ui/setup/SetupTermsFragment.kt new file mode 100644 index 0000000..e4f246e --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/setup/SetupTermsFragment.kt @@ -0,0 +1,76 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.text.method.LinkMovementMethod +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.extensions.safeNavigate +import io.timelimit.android.logic.DefaultAppLogic +import kotlinx.android.synthetic.main.fragment_setup_terms.* + +class SetupTermsFragment : Fragment() { + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.fragment_setup_terms, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + btn_accept.setOnClickListener { + acceptTerms() + } + + btn_uninstall.setOnClickListener { + uninstall() + } + + terms_text.movementMethod = LinkMovementMethod.getInstance() + } + + private fun acceptTerms() { + Navigation.findNavController(view!!).safeNavigate( + SetupTermsFragmentDirections.actionSetupTermsFragmentToSetupDevicePermissionsFragment(), + R.id.setupTermsFragment + ) + } + + private fun uninstall() { + 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/user/create/AddUserFragment.kt b/app/src/main/java/io/timelimit/android/ui/user/create/AddUserFragment.kt new file mode 100644 index 0000000..eea27f2 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/user/create/AddUserFragment.kt @@ -0,0 +1,138 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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 } + + isPasswordRequired.observe(this, Observer { + if (it != null && it) { + binding.password.visibility = View.VISIBLE + } else { + binding.password.visibility = View.GONE + } + }) + + val isPasswordOk = binding.password.passwordOk.or(isPasswordRequired.invert()) + + // 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 = when (userType.value!!) { + UserType.Parent -> binding.password.password.value!! + UserType.Child -> "" + }, + 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..97c0425 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/user/create/AddUserModel.kt @@ -0,0 +1,134 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.crypto.PasswordHashing +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.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 = PasswordHashing.hashCoroutine(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 = null, + 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..f5fd36a --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/user/create/DefaultCategories.kt @@ -0,0 +1,102 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/EditTextBottomSheetDialog.kt b/app/src/main/java/io/timelimit/android/ui/util/EditTextBottomSheetDialog.kt new file mode 100644 index 0000000..5201fd5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/util/EditTextBottomSheetDialog.kt @@ -0,0 +1,71 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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 { + 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/view/AppFilterView.kt b/app/src/main/java/io/timelimit/android/ui/view/AppFilterView.kt new file mode 100644 index 0000000..ba9191b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/AppFilterView.kt @@ -0,0 +1,88 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..2cf9d6d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/ManageDisableTimelimitsView.kt @@ -0,0 +1,59 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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() +} 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..bb9756b --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/SelectDayView.kt @@ -0,0 +1,20 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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) +} 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..01f8221 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/SelectTimeSpanView.kt @@ -0,0 +1,132 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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) +} 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..f9670c7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/ui/view/SetPasswordView.kt @@ -0,0 +1,113 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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.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 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 */ } + } + + 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..b9483a7 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/util/JoinUtil.kt @@ -0,0 +1,47 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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() + } +} 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..5ae738d --- /dev/null +++ b/app/src/main/java/io/timelimit/android/util/PasswordValidator.kt @@ -0,0 +1,59 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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..25d75d5 --- /dev/null +++ b/app/src/main/java/io/timelimit/android/util/TimeTextUtil.kt @@ -0,0 +1,73 @@ +/* + * Open TimeLimit Copyright 2019 Jonas Lochmann + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more 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/play/contactEmail b/app/src/main/play/contactEmail new file mode 100644 index 0000000..e69de29 diff --git a/app/src/main/play/contactPhone b/app/src/main/play/contactPhone new file mode 100644 index 0000000..e69de29 diff --git a/app/src/main/play/contactWebsite b/app/src/main/play/contactWebsite new file mode 100644 index 0000000..e69de29 diff --git a/app/src/main/play/de-DE/listing/fulldescription b/app/src/main/play/de-DE/listing/fulldescription new file mode 100644 index 0000000..4e74d2d --- /dev/null +++ b/app/src/main/play/de-DE/listing/fulldescription @@ -0,0 +1,11 @@ +Mit Open 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. + +Es 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. + +Die Zeitbegrenzungen können vorübergehend deaktiviert werden. + +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/main/play/de-DE/listing/phoneScreenshots/1.png b/app/src/main/play/de-DE/listing/phoneScreenshots/1.png new file mode 100644 index 0000000..ff0253c Binary files /dev/null and b/app/src/main/play/de-DE/listing/phoneScreenshots/1.png differ diff --git a/app/src/main/play/de-DE/listing/phoneScreenshots/2.png b/app/src/main/play/de-DE/listing/phoneScreenshots/2.png new file mode 100644 index 0000000..68c77f9 Binary files /dev/null and b/app/src/main/play/de-DE/listing/phoneScreenshots/2.png differ diff --git a/app/src/main/play/de-DE/listing/shortdescription b/app/src/main/play/de-DE/listing/shortdescription new file mode 100644 index 0000000..b4a8669 --- /dev/null +++ b/app/src/main/play/de-DE/listing/shortdescription @@ -0,0 +1 @@ +Einfach die Nutzungszeit beschränken \ No newline at end of file diff --git a/app/src/main/play/de-DE/listing/title b/app/src/main/play/de-DE/listing/title new file mode 100644 index 0000000..2de5b8a --- /dev/null +++ b/app/src/main/play/de-DE/listing/title @@ -0,0 +1 @@ +Open TimeLimit diff --git a/app/src/main/play/de-DE/listing/video b/app/src/main/play/de-DE/listing/video new file mode 100644 index 0000000..e69de29 diff --git a/app/src/main/play/de-DE/whatsnew b/app/src/main/play/de-DE/whatsnew new file mode 100644 index 0000000..e69de29 diff --git a/app/src/main/play/defaultLanguage b/app/src/main/play/defaultLanguage new file mode 100644 index 0000000..f2b0341 --- /dev/null +++ b/app/src/main/play/defaultLanguage @@ -0,0 +1 @@ +en-US \ No newline at end of file diff --git a/app/src/main/play/en-US/listing/fulldescription b/app/src/main/play/en-US/listing/fulldescription new file mode 100644 index 0000000..99b9933 --- /dev/null +++ b/app/src/main/play/en-US/listing/fulldescription @@ -0,0 +1,11 @@ +With Open TimeLimit, you can limit the usage duration flexibly. You can chose different settings for different Apps. + +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. + +You can disable the time limits temporarily. + +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. diff --git a/app/src/main/play/en-US/listing/icon/icon.png b/app/src/main/play/en-US/listing/icon/icon.png new file mode 100644 index 0000000..7b48bbe Binary files /dev/null and b/app/src/main/play/en-US/listing/icon/icon.png differ diff --git a/app/src/main/play/en-US/listing/phoneScreenshots/1.png b/app/src/main/play/en-US/listing/phoneScreenshots/1.png new file mode 100644 index 0000000..f1328ab Binary files /dev/null and b/app/src/main/play/en-US/listing/phoneScreenshots/1.png differ diff --git a/app/src/main/play/en-US/listing/phoneScreenshots/2.png b/app/src/main/play/en-US/listing/phoneScreenshots/2.png new file mode 100644 index 0000000..5a27cdc Binary files /dev/null and b/app/src/main/play/en-US/listing/phoneScreenshots/2.png differ diff --git a/app/src/main/play/en-US/listing/shortdescription b/app/src/main/play/en-US/listing/shortdescription new file mode 100644 index 0000000..a65bfb2 --- /dev/null +++ b/app/src/main/play/en-US/listing/shortdescription @@ -0,0 +1 @@ +Simply limit the usage duration \ No newline at end of file diff --git a/app/src/main/play/en-US/listing/title b/app/src/main/play/en-US/listing/title new file mode 100644 index 0000000..2de5b8a --- /dev/null +++ b/app/src/main/play/en-US/listing/title @@ -0,0 +1 @@ +Open TimeLimit diff --git a/app/src/main/play/en-US/listing/video b/app/src/main/play/en-US/listing/video new file mode 100644 index 0000000..e69de29 diff --git a/app/src/main/play/en-US/whatsnew b/app/src/main/play/en-US/whatsnew new file mode 100644 index 0000000..e69de29 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..e14e3c6 --- /dev/null +++ b/app/src/main/res/anim/wizard_close_step_in.xml @@ -0,0 +1,23 @@ + + + + + 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..7492c56 --- /dev/null +++ b/app/src/main/res/anim/wizard_close_step_out.xml @@ -0,0 +1,23 @@ + + + + + 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..d1e5556 --- /dev/null +++ b/app/src/main/res/anim/wizard_open_step_in.xml @@ -0,0 +1,23 @@ + + + + + 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..2849b25 --- /dev/null +++ b/app/src/main/res/anim/wizard_open_step_out.xml @@ -0,0 +1,23 @@ + + + + + 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_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_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/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..acc4106 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,25 @@ + + + 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..d316b44 --- /dev/null +++ b/app/src/main/res/layout/activity_unlock_after_manipulation.xml @@ -0,0 +1,47 @@ + + + + + + + + +