commit 7bb472d2122ad43f248fe8f2d2bca8b26ce8119e Author: Ujwal Date: Wed Mar 4 10:48:14 2026 +0545 What's new - Reordered Settings Page. - Added "Click to Unblur" for posts. - Added Persistent Notification - Improved Grayscale Scheduling. and more. diff --git a/.fdroid.yml b/.fdroid.yml new file mode 100644 index 0000000..a345f17 --- /dev/null +++ b/.fdroid.yml @@ -0,0 +1,45 @@ +Categories: + - Connectivity + - Social Network +License: AGPL-3.0-only +AuthorName: Ujwal Chapagain +AuthorEmail: notujwal@proton.me +SourceCode: https://github.com/Ujwal223/FocusGram +IssueTracker: https://github.com/Ujwal223/FocusGram/issues +Changelog: https://github.com/Ujwal223/FocusGram/blob/main/CHANGELOG.md + +AutoName: FocusGram + +RepoType: git +Repo: https://github.com/Ujwal223/FocusGram + +Builds: + - versionName: 1.0.0 + versionCode: 3 + commit: v1.0.0 + output: build/app/outputs/flutter-apk/app-release.apk + srclibs: + - flutter@stable + prebuild: + - flutterVersion=$(sed -n -E "s/.*flutter-version:\ '(.*)'/\1/p" .github/workflows/release.yml) + - '[[ $flutterVersion ]]' + - git -C $$flutter$$ checkout -f $flutterVersion + - export PUB_CACHE=$(pwd)/.pub-cache + - .flutter/bin/flutter config --no-analytics + - .flutter/bin/flutter pub get + scanignore: + - .flutter/bin/cache + scandelete: + - .flutter + - .pub-cache + build: + - export PUB_CACHE=$(pwd)/.pub-cache + - .flutter/bin/flutter build apk --release --split-per-abi --target-platform="android-arm64" + +AutoUpdateMode: Version +UpdateCheckMode: Tags +VercodeOperation: + - '%c * 10 + 1' +UpdateCheckData: pubspec.yaml|version:\s.+\+(\d+)|.|version:\s(.+)\+ +CurrentVersion: 1.0.0 +CurrentVersionCode: 3 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..88666a0 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,54 @@ +name: "CodeQL" + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + schedule: + - cron: '15 14 * * 5' + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-latest + permissions: + security-events: write + packages: read + actions: read + contents: read + + strategy: + fail-fast: false + matrix: + include: + - language: java-kotlin + build-mode: manual + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + flutter-version: '3.38.7' + channel: 'stable' + cache: true + + - name: Install dependencies + run: flutter pub get + + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + + - name: Build Android (for CodeQL) + run: flutter build apk --debug + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{ matrix.language }}" \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..03e0358 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,12 @@ +name: release +on: + push: + tags: + - '*' +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: subosito/flutter-action@v2 + with: + flutter-version: '3.38.7' \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..80df92f --- /dev/null +++ b/.gitignore @@ -0,0 +1,55 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ +PRD.md +.agents/ +TODO.md + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ +RELEASE_GUIDE.md +android/key.properties +android/fdroid-config.properties +android/app/*.jks +upload-keystore.jks + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +.flutter/ diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..00b74be --- /dev/null +++ b/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "3b62efc2a3da49882f43c372e0bc53daef7295a6" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + - platform: android + create_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + base_revision: 3b62efc2a3da49882f43c372e0bc53daef7295a6 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..cef1663 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,13 @@ +## FocusGram 1.0.0 + +### What's new +- Reordered Settings Page. +- Added "Click to Unblur" for posts. +- Added Persistent Notification +- Improved Grayscale Scheduling. + +### Bug fixes +- Fixed a Bug Where Reels Werent playing despite Reels Sessions being ON. +- Fixed a Bug Where Session End Popup could be just dismissed and app ran Normally despite session already ended. +- Perfomance Optimizations +- Other Minor Changes. \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d21876f --- /dev/null +++ b/LICENSE @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our general public licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, there is a terrible gap in the +overall display. The GNU General Public License permits making a +modified version and letting the public access it on a server without +ever releasing its source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the modified source code to the users of that server. +Therefore, public use of a modified version, on a publicly accessible +server, gives the public access to the source code of the modified +version. + + An older license, called the GNU Affero General Public License and +published by Affero, Inc., was designed to accomplish similar goals. +This is a different license, not a version of the Affero GPL, but +Affero, Inc. has permitted us to publish this program under the Affero +GPL. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Component, but which is not part of that Component, and +(b) serves only to enable use of the work with that Component, or to +implement a Standard Interface for which an implementation is +available to the public in source code form. A "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 the + Corresponding Source is located. 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 +to be acquired, that would be infringed by some manner, permitted by +this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not convey it at all. For example, if you agree to terms that +obligate you to collect a royalty for further conveying from those to +whom you convey the Program, the only way you could satisfy both those +terms and this License would be to refrain entirely from conveying the +Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your +version supports such interaction) an opportunity to receive the +Corresponding Source of your version by providing access to the +Corresponding Source from a network server at no charge, through some +standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any +work covered by version 3 of the GNU General Public License that is +incorporated pursuant to the following paragraph. + + You may convey a covered work under this License, and concurrently +combine it with a work licensed under version 3 of the GNU General +Public License into a single combined work, and convey the resulting +work. The terms of this License will continue to apply to the part +which is the covered work, but the work with which it is combined will +remain governed by version 3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Affero General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero +General Public License "or any later version" applies to it, you have +the option of following the terms and conditions either of that +numbered version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number +of the GNU Affero General Public License, you may choose any version +ever published by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that +proxy's public statement of acceptance of a version permanently +authorizes you to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE +OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU +ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING +ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF +THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO +LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY +OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that offers the most absolute +waiver of 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. + + FocusGram - Distraction-free Instagram client + Copyright (C) 2025 Ujwal Chapagain + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add a notice on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, +see . diff --git a/README.md b/README.md new file mode 100644 index 0000000..3e3a81d --- /dev/null +++ b/README.md @@ -0,0 +1,172 @@ +
+ +FocusGram + +# FocusGram + +**Use social media on your terms.** + +[![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL_3.0-blue.svg)](LICENSE) +[![Flutter](https://img.shields.io/badge/Flutter-3.38-blue?logo=flutter&logoColor=white)](https://flutter.dev) +[![Downloads](https://img.shields.io/github/downloads/ujwal223/focusgram/total?label=downloads&color=blue&cacheSeconds=300)](https://github.com/ujwal223/focusgram/releases) + + + Download FocusGram + + +[Download APK](https://github.com/ujwal223/focusgram/releases) · [View Changelog](CHANGELOG.md) · [Report a Bug](https://github.com/ujwal223/focusgram/issues/new) + +
+ +--- + +Most people don't want to quit Instagram. They want to check their messages, post a story, and leave — without losing an hour to Reels they never meant to watch. + +FocusGram is an Android app that loads the Instagram website with the distracting parts removed. No private APIs. No data collection. No accounts. Just a cleaner way to use a platform you already use. + +FocusGram App Screenshots + + +--- + +## What it does + +**Focus tools** + +- Block Reels entirely, or allow them in timed sessions (1–15 min) with daily limits and cooldowns +- Autoplay blocker — videos won't play until you tap them +- Minimal Mode — strips everything down to Feed and DMs + +**Content filtering** + +- Hide the Explore tab, Reels tab, or Shop tab individually +- Disable Explore and suggested content entirely +- Disable Reels Entirely + +**Habit tools** + +- Screen Time Dashboard — daily usage, 7-day chart, weekly average +- Grayscale Mode — reduces the visual pull of colour; can be scheduled by time of day +- Session intentions — optionally set a reason before opening the app + +**The app itself** + +- Feels (almost) like a native app, not a browser. +- No blank loading screen — content loads in the background before you get there +- Instant updates via pull-to-refresh +- Dark mode follows your system + +--- + +## Installation + +### Direct download +1. Go to the [Releases](https://github.com/ujwal223/focusgram/releases) page +2. Download `focusgram-release.apk` +3. Open the file and allow "Install from unknown sources" if prompted + +### Uptodown +Go to the [Focusgram - Uptodown](https://focusgram.en.uptodown.com/android) page
+2. Click "Get the Latest Version"
+3. Click "Download"
+3. Open the file and allow "Install from unknown sources" if prompted + +--- + +## Privacy + +FocusGram has no access to your Instagram account credentials. It loads `instagram.com` inside a standard Android WebView — your login goes directly to Meta's servers, the same as any mobile browser. + +- No analytics +- No crash reporting +- No third-party SDKs +- No data leaves your device +- All settings and history are stored locally using Android's standard storage APIs + +--- + +## Frequently asked questions + +**Will this get my account banned?** +Unlikely. FocusGram's traffic is indistinguishable from someone using Instagram in Chrome. It does not use Instagram's private API, does not automate any actions, and does not intercept credentials. See the technical details below for specifics. + +**Is this a mod of Instagram's app?** +No. FocusGram is a separate app that loads `instagram.com` in a WebView. It does not modify Instagram's APK or use any of Meta's proprietary code. + +**Why is it free?** +Because it should be. FocusGram is built and maintained by [Ujwal Chapagain](https://github.com/Ujwal223) and released under AGPL-3.0. + +--- + +## Building from source + +
+Technical details and build instructions + +### Requirements +- Flutter stable channel (3.38+) +- Android SDK +- NDK 28.2.12676356 +- Android SDK cmdline tools 20 +- Android build tools 34 and 35 +- JDK 17 (Eclipse Adoptium 17.0.17+) + +### Build +``` +bash +flutter pub get +flutter build apk --release +``` + +### Architecture +FocusGram uses a standard Android System WebView to load `instagram.com`. All features are implemented client-side via: +- JavaScript injection (autoplay blocking, metadata extraction, SPA navigation monitoring) +- CSS injection (element hiding, grayscale, scroll behaviour) +- URL interception via NavigationDelegate (Reels blocking, Explore blocking) + +Nothing is modified server-side. The app never reads, intercepts, or stores Instagram content beyond what is explicitly listed (Reel URL, title, and thumbnail URL for the local history feature). + +### Permissions +| Permission | Reason | +|---|---| +| `INTERNET` | Load instagram.com | +| `RECEIVE_BOOT_COMPLETED` | Keep session timers accurate after device restart | +| `WAKE_LOCK` | Keep device awake during active Focus sessions | +| `FOREGROUND_SERVICE` | Run background service for session tracking | + +### Stack +| | | +|---|---| +| Framework | Flutter (Dart) | +| WebView | flutter_inappwebview (Apache 2.0) | +| Storage | shared_preferences | +| License | AGPL-3.0 | + +
+ +--- + +## Legal disclaimer + +FocusGram is an independent, free, and open-source productivity tool licensed under AGPL-3.0. It is not affiliated with, endorsed by, or associated with Meta Platforms, Inc. or Instagram in any way. + +**How it works:** FocusGram embeds a standard Android System WebView that loads `instagram.com` — the same website accessible in any mobile browser. All user-facing features are implemented exclusively via client-side modifications and are never transmitted to or processed by Meta's servers. + +**What we do not do:** +- Use Instagram's or Meta's private APIs +- Intercept, read, log, or store user credentials, session data, or any content +- Modify any server-side Meta or Instagram services +- Scrape, harvest, or collect any user data +- Claim ownership of any Meta or Instagram trademarks, logos, or intellectual property — any branding visible within the app is served directly from `instagram.com` and remains the property of Meta Platforms, Inc. + +Using FocusGram is functionally equivalent to accessing Instagram through a mobile web browser with a content blocker extension. By using FocusGram, you acknowledge that you remain bound by Instagram's own Terms of Service. + +For legal concerns, contact `notujwal@proton.me` before taking any other action. + +--- + +## License + +Copyright © 2025 Ujwal Chapagain + +Licensed under the [GNU Affero General Public License v3.0](LICENSE). You are free to use, modify, and distribute this software under the same terms. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..9fc28a3 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,16 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks +upload-keystore.jks + diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..5400393 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,82 @@ +import java.util.Properties + +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.ujwal.focusgram" + compileSdk = flutter.compileSdkVersion + buildToolsVersion = "35.0.0" + ndkVersion = flutter.ndkVersion + + val keystorePropertiesFile = rootProject.file("key.properties") + val keystoreProperties = Properties() + if (keystorePropertiesFile.exists()) { + keystoreProperties.load(keystorePropertiesFile.inputStream()) + } + + signingConfigs { + create("release") { + keyAlias = keystoreProperties["keyAlias"] as String? + keyPassword = keystoreProperties["keyPassword"] as String? + storeFile = keystoreProperties["storeFile"]?.let { file(it) } + storePassword = keystoreProperties["storePassword"] as String? + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + isCoreLibraryDesugaringEnabled = true + } + + kotlinOptions { + jvmTarget = "17" + } + + defaultConfig { + applicationId = "com.ujwal.focusgram" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = 24 + targetSdk = 35 + versionCode = 4 + versionName = "1.1.0" + } + + buildTypes { + release { + if (keystorePropertiesFile.exists()) { + signingConfig = signingConfigs.getByName("release") + } else { + signingConfig = signingConfigs.getByName("debug") + } + + // Fix for release crash: Apply proguard rules + isMinifyEnabled = true + isShrinkResources = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + + configurations.all { + exclude(group = "com.google.android.gms") + exclude(group = "com.google.firebase") + exclude(group = "com.google.android.datatransport") + exclude(group = "com.google.android.play") + exclude(group = "com.google.android.play", module = "core") + exclude(group = "com.google.android.play", module = "core-common") + } +} + +dependencies { + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5") +} + +flutter { + source = "../.." +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..ea309ba --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,37 @@ +-keep class io.flutter.** { *; } +-keep class io.flutter.plugins.** { *; } +-keep class com.pichillilorenzo.flutter_inappwebview.** { *; } +-keep class **.GeneratedPluginRegistrant { *; } + +# Strip Google Play Core (Flutter engine bundles these unnecessarily for F-Droid) +-dontwarn com.google.android.play.core.** +-dontwarn com.google.android.play.core.splitinstall.** +-dontwarn com.google.android.play.core.tasks.** +-assumenosideeffects class com.google.android.play.core.** { *; } +-assumenosideeffects class com.google.android.play.core.splitinstall.** { *; } +-assumenosideeffects class com.google.android.play.core.tasks.** { *; } + +# Flutter Wrapper +-keep class io.flutter.app.** { *; } +-keep class io.flutter.plugin.** { *; } +-keep class io.flutter.util.** { *; } +-keep class io.flutter.view.** { *; } +-keep class io.flutter.** { *; } +-keep class io.flutter.plugins.** { *; } + +# flutter_local_notifications +-keep class com.dexterous.flutterlocalnotifications.** { *; } +-keep class com.google.firebase.messaging.** { *; } +-dontwarn com.google.firebase.messaging.** + +# webview_flutter +-keep class io.flutter.plugins.webviewflutter.** { *; } + +# Keystore and common +-keep class com.ujwal.focusgram.** { *; } + +# Avoid stripping JS bridge names +-keepattributes JavascriptInterface +-keepclassmembers class * { + @android.webkit.JavascriptInterface ; +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..4a38ec5 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/ujwal/focusgram/MainActivity.kt b/android/app/src/main/kotlin/com/ujwal/focusgram/MainActivity.kt new file mode 100644 index 0000000..445ab01 --- /dev/null +++ b/android/app/src/main/kotlin/com/ujwal/focusgram/MainActivity.kt @@ -0,0 +1,5 @@ +package com.ujwal.focusgram + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..9accd00 Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..625081a Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..9c5d635 Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..341e142 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..b2f4937 Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..5f349f7 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..f9dcc18 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..7352438 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..2182cb5 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..46afce4 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..839c0d1 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..beab31f --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,4 @@ + + + #000000 + \ No newline at end of file diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/xml/network_security_config.xml b/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000..91fb43d --- /dev/null +++ b/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + instagram.com + cdninstagram.com + fbcdn.net + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..4d800c3 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/build/reports/problems/problems-report.html b/android/build/reports/problems/problems-report.html new file mode 100644 index 0000000..54f5680 --- /dev/null +++ b/android/build/reports/problems/problems-report.html @@ -0,0 +1,663 @@ + + + + + + + + + + + + + Gradle Configuration Cache + + + +
+ +
+ Loading... +
+ + + + + + diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..b3764f0 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx3G -XX:MaxMetaspaceSize=1G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e4ef43f --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..ca7fe06 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/assets/images/focusgram.ico b/assets/images/focusgram.ico new file mode 100644 index 0000000..91666f4 Binary files /dev/null and b/assets/images/focusgram.ico differ diff --git a/assets/images/focusgram.png b/assets/images/focusgram.png new file mode 100644 index 0000000..79554d0 Binary files /dev/null and b/assets/images/focusgram.png differ diff --git a/devtools_options.yaml b/devtools_options.yaml new file mode 100644 index 0000000..fa0b357 --- /dev/null +++ b/devtools_options.yaml @@ -0,0 +1,3 @@ +description: This file stores settings for Dart & Flutter DevTools. +documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states +extensions: diff --git a/fastlane/metadata/android/en-US/changelogs/1.txt b/fastlane/metadata/android/en-US/changelogs/1.txt new file mode 100644 index 0000000..45e93cb --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/1.txt @@ -0,0 +1,5 @@ +Initial open-source release of FocusGram. +- Complete Reels and Explore hiding. +- Timed Reel sessions and daily limits. +- Isolated DM Reel player. +- Privacy-first: No Firebase or trackers. diff --git a/fastlane/metadata/android/en-US/changelogs/2.txt b/fastlane/metadata/android/en-US/changelogs/2.txt new file mode 100644 index 0000000..a0b9d0b --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/2.txt @@ -0,0 +1 @@ +Same as1st version. just version pump \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/3.txt b/fastlane/metadata/android/en-US/changelogs/3.txt new file mode 100644 index 0000000..4f1c995 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/3.txt @@ -0,0 +1,7 @@ +New: Reels History, Minimal Mode, Disable Reels/Explore toggles, Autoplay Blocker, Screen Time Dashboard, Grayscale Mode, 8 content hide toggles. + +Fixes: DM keyboard bug, Reels scroll lag. + +Performance: Native nav bar, background preloading, skeleton screen, haptic feedback, smooth scrolling. + +F-Droid: Removed all Google dependencies. No Play Services in APK. \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/changelogs/4.txt b/fastlane/metadata/android/en-US/changelogs/4.txt new file mode 100644 index 0000000..62f4ec9 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/4.txt @@ -0,0 +1,6 @@ +What's new +- Reordered Settings Page. +- Added "Click to Unblur" for posts. +- Added Persistent Notification +- Improved Grayscale Scheduling. +and more. \ No newline at end of file diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt new file mode 100644 index 0000000..ecb34fa --- /dev/null +++ b/fastlane/metadata/android/en-US/full_description.txt @@ -0,0 +1,10 @@ +FocusGram is a free and open-source Android app designed to help you regain control over your social media usage. It wraps the mobile version of Instagram in a secure WebView and injects features to minimize distractions. + +Features: +- **Focus Mode**: Blur explore posts and hide reel buttons. +- **Guardrails**: Set daily usage limits and session cooldowns. +- **Mindfulness**: A mandatory breathing exercise before entering the app. +- **Privacy First**: No analytics, no tracking, and no proprietary Google Play Services requirements. +- **Hybrid Composition**: Optimized WebView performance for smooth scrolling. + +FocusGram is NOT an Instagram mod. It uses the standard web version of Instagram and applies client-side CSS and JS modifications only. diff --git a/fastlane/metadata/android/en-US/short_description.txt b/fastlane/metadata/android/en-US/short_description.txt new file mode 100644 index 0000000..285db2e --- /dev/null +++ b/fastlane/metadata/android/en-US/short_description.txt @@ -0,0 +1 @@ +A digital wellness wrapper for Instagram. diff --git a/fastlane/metadata/android/en-US/title.txt b/fastlane/metadata/android/en-US/title.txt new file mode 100644 index 0000000..f2affd7 --- /dev/null +++ b/fastlane/metadata/android/en-US/title.txt @@ -0,0 +1 @@ +FocusGram diff --git a/lib/features/loading/skeleton_screen.dart b/lib/features/loading/skeleton_screen.dart new file mode 100644 index 0000000..e0ce254 --- /dev/null +++ b/lib/features/loading/skeleton_screen.dart @@ -0,0 +1,532 @@ +import 'package:flutter/material.dart'; + +enum SkeletonType { feed, reels, explore, messages, profile, generic } + +class SkeletonScreen extends StatefulWidget { + final SkeletonType skeletonType; + + const SkeletonScreen({super.key, this.skeletonType = SkeletonType.generic}); + + @override + State createState() => _SkeletonScreenState(); +} + +class _SkeletonScreenState extends State + with SingleTickerProviderStateMixin { + late AnimationController _shimmerController; + late Animation _shimmerAnimation; + + @override + void initState() { + super.initState(); + _shimmerController = AnimationController( + duration: const Duration(milliseconds: 1200), + vsync: this, + )..repeat(); + _shimmerAnimation = Tween( + begin: -1.0, + end: 2.0, + ).animate(_shimmerController); + } + + @override + void dispose() { + _shimmerController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final baseColor = theme.colorScheme.surfaceContainerHighest.withValues( + alpha: theme.brightness == Brightness.dark ? 0.25 : 0.4, + ); + final highlightColor = theme.colorScheme.onSurface.withValues(alpha: 0.08); + + return Container( + color: theme.scaffoldBackgroundColor, + width: double.infinity, + height: double.infinity, + child: AnimatedBuilder( + animation: _shimmerAnimation, + builder: (context, child) { + return ShaderMask( + shaderCallback: (rect) { + return LinearGradient( + begin: Alignment.centerLeft, + end: Alignment.centerRight, + colors: [baseColor, highlightColor, baseColor], + stops: const [0.1, 0.3, 0.6], + transform: _SlidingGradientTransform( + slidePercent: _shimmerAnimation.value, + ), + ).createShader(rect); + }, + blendMode: BlendMode.srcATop, + child: _buildSkeletonContent(context), + ); + }, + ), + ); + } + + Widget _buildSkeletonContent(BuildContext context) { + switch (widget.skeletonType) { + case SkeletonType.feed: + return _buildFeedSkeleton(context); + case SkeletonType.reels: + return _buildReelsSkeleton(context); + case SkeletonType.explore: + return _buildExploreSkeleton(context); + case SkeletonType.messages: + return _buildMessagesSkeleton(context); + case SkeletonType.profile: + return _buildProfileSkeleton(context); + case SkeletonType.generic: + return _buildGenericSkeleton(context); + } + } + + Widget _buildFeedSkeleton(BuildContext context) { + final width = MediaQuery.of(context).size.width; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + height: 80, + padding: const EdgeInsets.symmetric(vertical: 8), + child: ListView.builder( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 12), + itemCount: 6, + itemBuilder: (context, index) => Padding( + padding: const EdgeInsets.only(right: 12), + child: Column( + children: [ + Container( + width: 56, + height: 56, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(28), + ), + ), + const SizedBox(height: 4), + Container( + width: 32, + height: 8, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + ], + ), + ), + ), + ), + Expanded( + child: ListView.builder( + padding: const EdgeInsets.symmetric(horizontal: 0), + itemCount: 3, + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 8, + ), + child: Row( + children: [ + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + ), + ), + const SizedBox(width: 8), + Container( + width: 80, + height: 12, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + ], + ), + ), + Container( + width: double.infinity, + height: width, + color: Colors.white, + ), + Padding( + padding: const EdgeInsets.all(12), + child: Row( + children: List.generate( + 3, + (i) => Padding( + padding: const EdgeInsets.only(right: 16), + child: Container( + width: 24, + height: 24, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + ), + ), + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Container( + width: width * 0.7, + height: 10, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + ), + ], + ), + ); + }, + ), + ), + ], + ); + } + + Widget _buildReelsSkeleton(BuildContext context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 120, + height: 200, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + ), + ), + const SizedBox(height: 24), + Container( + width: 150, + height: 16, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + const SizedBox(height: 12), + Container( + width: 100, + height: 12, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + ], + ), + ); + } + + Widget _buildExploreSkeleton(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(2), + child: GridView.builder( + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + crossAxisSpacing: 2, + mainAxisSpacing: 2, + ), + itemCount: 15, + itemBuilder: (context, index) { + return Container(color: Colors.white); + }, + ), + ); + } + + Widget _buildMessagesSkeleton(BuildContext context) { + return ListView.builder( + itemCount: 8, + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + child: Row( + children: [ + Container( + width: 56, + height: 56, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(28), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 100, + height: 14, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + const SizedBox(height: 6), + Container( + width: 150, + height: 12, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + ], + ), + ), + ], + ), + ); + }, + ); + } + + Widget _buildProfileSkeleton(BuildContext context) { + return SingleChildScrollView( + child: Column( + children: [ + const SizedBox(height: 24), + Container( + width: 96, + height: 96, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(48), + ), + ), + const SizedBox(height: 16), + Container( + width: 120, + height: 16, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + const SizedBox(height: 24), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: List.generate( + 3, + (index) => Column( + children: [ + Container( + width: 40, + height: 20, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + const SizedBox(height: 4), + Container( + width: 50, + height: 10, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + ], + ), + ), + ), + const SizedBox(height: 24), + GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + crossAxisSpacing: 2, + mainAxisSpacing: 2, + ), + itemCount: 9, + itemBuilder: (context, index) { + return Container(color: Colors.white); + }, + ), + ], + ), + ); + } + + Widget _buildGenericSkeleton(BuildContext context) { + final width = MediaQuery.of(context).size.width; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 16), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + children: List.generate( + 6, + (index) => Padding( + padding: const EdgeInsets.only(right: 12), + child: Column( + children: [ + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(30), + ), + ), + const SizedBox(height: 8), + Container( + width: 40, + height: 8, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + ], + ), + ), + ), + ), + ), + const SizedBox(height: 16), + Expanded( + child: ListView.builder( + padding: const EdgeInsets.symmetric(horizontal: 12), + itemCount: 3, + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.only(bottom: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(18), + ), + ), + const SizedBox(width: 12), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: width * 0.4, + height: 10, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + const SizedBox(height: 6), + Container( + width: width * 0.25, + height: 8, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + ], + ), + ], + ), + const SizedBox(height: 12), + Container( + width: double.infinity, + height: width * 1.1, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(18), + ), + ), + const SizedBox(height: 12), + Container( + width: width * 0.7, + height: 10, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + const SizedBox(height: 6), + Container( + width: width * 0.5, + height: 8, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + ), + ), + ], + ), + ); + }, + ), + ), + ], + ); + } +} + +class _SlidingGradientTransform extends GradientTransform { + final double slidePercent; + + const _SlidingGradientTransform({required this.slidePercent}); + + @override + Matrix4 transform(Rect bounds, {TextDirection? textDirection}) { + return Matrix4.translationValues(bounds.width * slidePercent, 0.0, 0.0); + } +} + +SkeletonType getSkeletonTypeFromUrl(String url) { + final parsed = Uri.tryParse(url); + if (parsed == null) return SkeletonType.generic; + final path = parsed.path.toLowerCase(); + + if (path.startsWith('/reels') || path.startsWith('/reel/')) { + return SkeletonType.reels; + } else if (path.startsWith('/explore')) { + return SkeletonType.explore; + } else if (path.startsWith('/messages') || path.startsWith('/inbox')) { + return SkeletonType.messages; + } else if (path.startsWith('/') && !path.startsWith('/accounts')) { + if (path.split('/').length <= 2) { + return SkeletonType.feed; + } + return SkeletonType.profile; + } + return SkeletonType.generic; +} diff --git a/lib/features/native_nav/native_bottom_nav.dart b/lib/features/native_nav/native_bottom_nav.dart new file mode 100644 index 0000000..35c5b9c --- /dev/null +++ b/lib/features/native_nav/native_bottom_nav.dart @@ -0,0 +1,167 @@ +import 'package:flutter/material.dart'; + +class NativeBottomNav extends StatelessWidget { + final String currentUrl; + final bool reelsEnabled; + final bool exploreEnabled; + final bool minimalMode; + final Function(String path) onNavigate; + + const NativeBottomNav({ + super.key, + required this.currentUrl, + required this.reelsEnabled, + required this.exploreEnabled, + required this.minimalMode, + required this.onNavigate, + }); + + String get _path { + final parsed = Uri.tryParse(currentUrl); + if (parsed != null && parsed.path.isNotEmpty) return parsed.path; + return currentUrl; // may already be a path from SPA callbacks + } + + bool get _onHome => _path == '/' || _path.isEmpty; + bool get _onExplore => _path.startsWith('/explore'); + bool get _onReels => _path.startsWith('/reels') || _path.startsWith('/reel/'); + bool get _onProfile => + _path.startsWith('/accounts') || + _path.contains('/profile') || + _path.split('/').where((p) => p.isNotEmpty).length == 1; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + + final bgColor = + theme.colorScheme.surface.withValues(alpha: isDark ? 0.95 : 0.98); + final iconColorInactive = + isDark ? Colors.white70 : Colors.black54; + final iconColorActive = + theme.colorScheme.primary; + + final tabs = <_NavItem>[ + _NavItem( + icon: Icons.home_outlined, + activeIcon: Icons.home, + label: 'Home', + path: '/', + active: _onHome, + enabled: true, + ), + if (!minimalMode) + _NavItem( + icon: Icons.search_outlined, + activeIcon: Icons.search, + label: 'Search', + path: '/explore/', + active: _onExplore, + enabled: exploreEnabled, + ), + _NavItem( + icon: Icons.add_box_outlined, + activeIcon: Icons.add_box, + label: 'New', + path: '/create/select/', + active: false, + enabled: true, + ), + if (!minimalMode) + _NavItem( + icon: Icons.play_circle_outline, + activeIcon: Icons.play_circle, + label: 'Reels', + path: '/reels/', + active: _onReels, + enabled: reelsEnabled, + ), + _NavItem( + icon: Icons.person_outline, + activeIcon: Icons.person, + label: 'Profile', + path: '/accounts/edit/', + active: _onProfile, + enabled: true, + ), + ]; + + return SafeArea( + top: false, + child: Container( + decoration: BoxDecoration( + color: bgColor, + border: Border( + top: BorderSide( + color: isDark ? Colors.white10 : Colors.black12, + width: 0.5, + ), + ), + ), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: tabs.map((item) { + final color = + item.active ? iconColorActive : iconColorInactive; + final opacity = item.enabled ? 1.0 : 0.35; + + return Expanded( + child: Opacity( + opacity: opacity, + child: InkWell( + onTap: item.enabled ? () => onNavigate(item.path) : null, + borderRadius: BorderRadius.circular(24), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 4, + vertical: 6, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + item.active ? item.activeIcon : item.icon, + size: 24, + color: color, + ), + const SizedBox(height: 2), + Text( + item.label, + style: TextStyle( + fontSize: 10, + color: color, + ), + ), + ], + ), + ), + ), + ), + ); + }).toList(), + ), + ), + ); + } +} + +class _NavItem { + final IconData icon; + final IconData activeIcon; + final String label; + final String path; + final bool active; + final bool enabled; + + _NavItem({ + required this.icon, + required this.activeIcon, + required this.label, + required this.path, + required this.active, + required this.enabled, + }); +} + diff --git a/lib/features/preloader/instagram_preloader.dart b/lib/features/preloader/instagram_preloader.dart new file mode 100644 index 0000000..57de8dd --- /dev/null +++ b/lib/features/preloader/instagram_preloader.dart @@ -0,0 +1,72 @@ +import 'dart:collection'; + +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; + +import '../../scripts/autoplay_blocker.dart'; +import '../../scripts/spa_navigation_monitor.dart'; +import '../../scripts/native_feel.dart'; + +class InstagramPreloader { + static HeadlessInAppWebView? _headlessWebView; + static InAppWebViewController? controller; + static final InAppWebViewKeepAlive keepAlive = InAppWebViewKeepAlive(); + static bool isReady = false; + + static Future start(String userAgent) async { + if (_headlessWebView != null) return; // don't start twice + + _headlessWebView = HeadlessInAppWebView( + keepAlive: keepAlive, + initialUrlRequest: URLRequest( + url: WebUri('https://www.instagram.com/'), + ), + initialSettings: InAppWebViewSettings( + userAgent: userAgent, + mediaPlaybackRequiresUserGesture: true, + useHybridComposition: true, + cacheEnabled: true, + cacheMode: CacheMode.LOAD_CACHE_ELSE_NETWORK, + domStorageEnabled: true, + databaseEnabled: true, + hardwareAcceleration: true, + transparentBackground: true, + safeBrowsingEnabled: false, + ), + initialUserScripts: UnmodifiableListView([ + UserScript( + source: 'window.__fgBlockAutoplay = true;', + injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START, + ), + UserScript( + source: kAutoplayBlockerJS, + injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START, + ), + UserScript( + source: kSpaNavigationMonitorScript, + injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START, + ), + UserScript( + source: kNativeFeelingScript, + injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START, + ), + ]), + onWebViewCreated: (c) { + controller = c; + }, + onLoadStop: (c, url) async { + isReady = true; + await c.evaluateJavascript(source: kNativeFeelingPostLoadScript); + }, + ); + + await _headlessWebView!.run(); + } + + static void dispose() { + _headlessWebView?.dispose(); + _headlessWebView = null; + controller = null; + isReady = false; + } +} + diff --git a/lib/features/reels_history/reels_history_screen.dart b/lib/features/reels_history/reels_history_screen.dart new file mode 100644 index 0000000..3e5f70c --- /dev/null +++ b/lib/features/reels_history/reels_history_screen.dart @@ -0,0 +1,252 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +import 'reels_history_service.dart'; + +class ReelsHistoryScreen extends StatefulWidget { + const ReelsHistoryScreen({super.key}); + + @override + State createState() => _ReelsHistoryScreenState(); +} + +class _ReelsHistoryScreenState extends State { + final _service = ReelsHistoryService(); + late Future> _future; + + @override + void initState() { + super.initState(); + _future = _service.getEntries(); + } + + Future _refresh() async { + setState(() => _future = _service.getEntries()); + } + + String _formatTimestamp(DateTime dt) => + DateFormat('EEE, MMM d • h:mm a').format(dt.toLocal()); + + String _relativeTime(DateTime dt) { + final diff = DateTime.now().difference(dt.toLocal()); + if (diff.inMinutes < 60) return '${diff.inMinutes}m ago'; + if (diff.inHours < 24) return '${diff.inHours}h ago'; + if (diff.inDays < 7) return '${diff.inDays}d ago'; + return _formatTimestamp(dt); + } + + Future _confirmClearAll() async { + final ok = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Clear Reels History?'), + content: const Text( + 'This removes all history entries stored locally on this device.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('Cancel'), + ), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: Colors.redAccent), + onPressed: () => Navigator.pop(ctx, true), + child: const Text('Clear All'), + ), + ], + ), + ); + if (ok != true || !mounted) return; + await _service.clearAll(); + await _refresh(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text( + 'Reels History', + style: TextStyle(fontSize: 17, fontWeight: FontWeight.w600), + ), + centerTitle: true, + leading: IconButton( + icon: const Icon(Icons.arrow_back_ios_new, size: 18), + onPressed: () => Navigator.pop(context), + ), + actions: [ + IconButton( + tooltip: 'Clear All', + onPressed: _confirmClearAll, + icon: const Icon(Icons.delete_outline), + ), + ], + ), + body: RefreshIndicator( + onRefresh: _refresh, + child: FutureBuilder>( + future: _future, + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Center(child: CircularProgressIndicator()); + } + + final entries = snapshot.data ?? const []; + + return ListView( + physics: const AlwaysScrollableScrollPhysics(), + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Row( + children: [ + const Icon( + Icons.lock_outline, + size: 12, + color: Colors.grey, + ), + const SizedBox(width: 6), + Text( + '${entries.length} reels stored locally on device only', + style: const TextStyle( + fontSize: 12, + color: Colors.grey, + ), + ), + ], + ), + ), + const SizedBox(height: 4), + if (entries.isEmpty) + const Padding( + padding: EdgeInsets.all(48), + child: Center( + child: Column( + children: [ + Icon( + Icons.play_circle_outline, + size: 48, + color: Colors.grey, + ), + SizedBox(height: 12), + Text( + 'No Reels history yet.\nWatch a Reel and it will appear here.', + textAlign: TextAlign.center, + style: TextStyle(color: Colors.grey), + ), + ], + ), + ), + ) + else + ...entries.map((entry) { + return Dismissible( + key: ValueKey(entry.id), + direction: DismissDirection.endToStart, + background: Container( + color: Colors.redAccent.withValues(alpha: 0.15), + alignment: Alignment.centerRight, + padding: const EdgeInsets.only(right: 20), + child: const Icon( + Icons.delete_outline, + color: Colors.redAccent, + ), + ), + onDismissed: (_) async { + await _service.deleteEntry(entry.id); + // Don't call _refresh() on dismiss — removes the entry from + // the live list already via Dismissible, avoids double setState + }, + child: ListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + leading: _ReelThumbnail(url: entry.thumbnailUrl), + title: Text( + entry.title, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 14), + ), + subtitle: Text( + _relativeTime(entry.visitedAt), + style: const TextStyle( + fontSize: 12, + color: Colors.grey, + ), + ), + trailing: const Icon( + Icons.play_circle_outline, + color: Colors.blue, + size: 20, + ), + onTap: () => Navigator.pop(context, entry.url), + ), + ); + }), + const SizedBox(height: 40), + ], + ); + }, + ), + ), + ); + } +} + +/// Thumbnail widget that correctly sends Referer + User-Agent headers +/// required by Instagram's CDN. Without these the CDN returns 403. +class _ReelThumbnail extends StatelessWidget { + final String url; + const _ReelThumbnail({required this.url}); + + @override + Widget build(BuildContext context) { + return ClipRRect( + borderRadius: BorderRadius.circular(8), + child: SizedBox( + width: 60, + height: 60, + child: url.isEmpty + ? _placeholder() + : Image.network( + url, + width: 60, + height: 60, + fit: BoxFit.cover, + headers: const { + // Instagram CDN requires a valid Referer header + 'Referer': 'https://www.instagram.com/', + 'User-Agent': + 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) ' + 'AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/22G86', + }, + errorBuilder: (_, _, _) => _placeholder(), + loadingBuilder: (_, child, progress) { + if (progress == null) return child; + return Container( + color: Colors.white10, + child: const Center( + child: SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 1.5), + ), + ), + ); + }, + ), + ), + ); + } + + Widget _placeholder() => Container( + color: Colors.white10, + child: const Icon( + Icons.play_circle_outline, + color: Colors.white30, + size: 28, + ), + ); +} diff --git a/lib/features/reels_history/reels_history_service.dart b/lib/features/reels_history/reels_history_service.dart new file mode 100644 index 0000000..67dec87 --- /dev/null +++ b/lib/features/reels_history/reels_history_service.dart @@ -0,0 +1,117 @@ +import 'dart:convert'; + +import 'package:shared_preferences/shared_preferences.dart'; + +class ReelsHistoryEntry { + final String id; + final String url; + final String title; + final String thumbnailUrl; + final DateTime visitedAt; + + const ReelsHistoryEntry({ + required this.id, + required this.url, + required this.title, + required this.thumbnailUrl, + required this.visitedAt, + }); + + Map toJson() => { + 'id': id, + 'url': url, + 'title': title, + 'thumbnailUrl': thumbnailUrl, + 'visitedAt': visitedAt.toUtc().toIso8601String(), + }; + + static ReelsHistoryEntry fromJson(Map json) { + return ReelsHistoryEntry( + id: (json['id'] as String?) ?? '', + url: (json['url'] as String?) ?? '', + title: (json['title'] as String?) ?? 'Instagram Reel', + thumbnailUrl: (json['thumbnailUrl'] as String?) ?? '', + visitedAt: DateTime.tryParse((json['visitedAt'] as String?) ?? '') ?? + DateTime.now().toUtc(), + ); + } +} + +class ReelsHistoryService { + static const String _prefsKey = 'reels_history'; + static const int _maxEntries = 200; + + SharedPreferences? _prefs; + + Future _getPrefs() async { + _prefs ??= await SharedPreferences.getInstance(); + return _prefs!; + } + + Future> getEntries() async { + final prefs = await _getPrefs(); + final raw = prefs.getString(_prefsKey); + if (raw == null || raw.isEmpty) return []; + try { + final decoded = jsonDecode(raw) as List; + final entries = decoded + .whereType() + .map((e) => ReelsHistoryEntry.fromJson(e.cast())) + .where((e) => e.url.isNotEmpty) + .toList(); + entries.sort((a, b) => b.visitedAt.compareTo(a.visitedAt)); + return entries; + } catch (_) { + return []; + } + } + + Future addEntry({ + required String url, + required String title, + required String thumbnailUrl, + }) async { + if (url.isEmpty) return; + final now = DateTime.now().toUtc(); + + final entries = await getEntries(); + final recentDuplicate = entries.any((e) { + if (e.url != url) return false; + final diff = now.difference(e.visitedAt).inSeconds.abs(); + return diff <= 60; + }); + if (recentDuplicate) return; + + final entry = ReelsHistoryEntry( + id: DateTime.now().microsecondsSinceEpoch.toString(), + url: url, + title: title.isEmpty ? 'Instagram Reel' : title, + thumbnailUrl: thumbnailUrl, + visitedAt: now, + ); + + final updated = [entry, ...entries]; + if (updated.length > _maxEntries) { + updated.removeRange(_maxEntries, updated.length); + } + await _save(updated); + } + + Future deleteEntry(String id) async { + final entries = await getEntries(); + entries.removeWhere((e) => e.id == id); + await _save(entries); + } + + Future clearAll() async { + final prefs = await _getPrefs(); + await prefs.remove(_prefsKey); + } + + Future _save(List entries) async { + final prefs = await _getPrefs(); + final jsonList = entries.map((e) => e.toJson()).toList(); + await prefs.setString(_prefsKey, jsonEncode(jsonList)); + } +} + diff --git a/lib/features/screen_time/screen_time_screen.dart b/lib/features/screen_time/screen_time_screen.dart new file mode 100644 index 0000000..d0da8fe --- /dev/null +++ b/lib/features/screen_time/screen_time_screen.dart @@ -0,0 +1,307 @@ +import 'package:fl_chart/fl_chart.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../../services/screen_time_service.dart'; + +class ScreenTimeScreen extends StatelessWidget { + const ScreenTimeScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text( + 'Screen Time', + style: TextStyle(fontSize: 17, fontWeight: FontWeight.w600), + ), + leading: IconButton( + icon: const Icon(Icons.arrow_back_ios_new, size: 18), + onPressed: () => Navigator.pop(context), + ), + ), + body: Consumer( + builder: (context, service, _) { + final data = service.secondsByDate; + final todayKey = _todayKey(); + final todaySeconds = data[todayKey] ?? 0; + + final last7 = _lastNDays(7); + final barSpots = []; + int totalSeconds = 0; + for (var i = 0; i < last7.length; i++) { + final key = last7[i]; + final sec = data[key] ?? 0; + totalSeconds += sec; + barSpots.add( + BarChartGroupData( + x: i, + barRods: [ + BarChartRodData( + toY: sec / 60.0, + width: 10, + borderRadius: BorderRadius.circular(4), + color: Colors.blueAccent, + ), + ], + ), + ); + } + + final daysWithData = data.values.isEmpty ? 0 : data.length; + final weeklyAvgMinutes = last7.isEmpty + ? 0.0 + : totalSeconds / 60.0 / last7.length; + final allTimeMinutes = totalSeconds / 60.0; + + return ListView( + padding: const EdgeInsets.all(16), + children: [ + _buildStatCard( + title: 'Today', + value: _formatDuration(todaySeconds), + ), + const SizedBox(height: 16), + _buildChartCard(barSpots, last7), + const SizedBox(height: 16), + _buildInlineStats( + weeklyAvgMinutes: weeklyAvgMinutes, + allTimeMinutes: allTimeMinutes, + daysWithData: daysWithData, + ), + const SizedBox(height: 24), + const Text( + 'All data stored locally on your device only', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12, color: Colors.grey), + ), + const SizedBox(height: 24), + Center( + child: OutlinedButton.icon( + onPressed: () => _confirmReset(context, service), + icon: const Icon(Icons.delete_outline, size: 18), + label: const Text('Reset all data'), + style: OutlinedButton.styleFrom( + foregroundColor: Colors.redAccent, + side: const BorderSide(color: Colors.redAccent), + ), + ), + ), + ], + ); + }, + ), + ); + } + + static String _todayKey() { + final now = DateTime.now(); + return '${now.year.toString().padLeft(4, '0')}-' + '${now.month.toString().padLeft(2, '0')}-' + '${now.day.toString().padLeft(2, '0')}'; + } + + static List _lastNDays(int n) { + final now = DateTime.now(); + return List.generate(n, (i) { + final d = now.subtract(Duration(days: n - 1 - i)); + return '${d.year.toString().padLeft(4, '0')}-' + '${d.month.toString().padLeft(2, '0')}-' + '${d.day.toString().padLeft(2, '0')}'; + }); + } + + Widget _buildStatCard({required String title, required String value}) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(14), + border: Border.all(color: Colors.blue.withValues(alpha: 0.2)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(title, style: const TextStyle(fontSize: 14, color: Colors.grey)), + Text( + value, + style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold), + ), + ], + ), + ); + } + + Widget _buildChartCard(List bars, List last7Keys) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(14), + border: Border.all(color: Colors.white12), + ), + height: 220, + child: BarChart( + BarChartData( + barGroups: bars, + gridData: FlGridData(show: false), + borderData: FlBorderData(show: false), + titlesData: FlTitlesData( + leftTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false), + ), + topTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false), + ), + rightTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false), + ), + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + getTitlesWidget: (value, meta) { + final index = value.toInt(); + if (index < 0 || index >= last7Keys.length) { + return const SizedBox.shrink(); + } + final label = last7Keys[index].substring( + last7Keys[index].length - 2, + ); + return Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + label, + style: const TextStyle(fontSize: 10, color: Colors.grey), + ), + ); + }, + ), + ), + ), + ), + ), + ); + } + + Widget _buildInlineStats({ + required double weeklyAvgMinutes, + required double allTimeMinutes, + required int daysWithData, + }) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.02), + borderRadius: BorderRadius.circular(14), + border: Border.all(color: Colors.white10), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + _inlineStat( + label: '7-day avg', + value: '${weeklyAvgMinutes.toStringAsFixed(1)} min', + ), + _inlineDivider(), + _inlineStat( + label: 'All-time total', + value: '${allTimeMinutes.toStringAsFixed(0)} min', + ), + _inlineDivider(), + _inlineStat(label: 'Tracked days', value: '$daysWithData'), + ], + ), + ); + } + + Widget _inlineStat({required String label, required String value}) { + return Column( + children: [ + Text( + value, + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 4), + Text(label, style: const TextStyle(fontSize: 11, color: Colors.grey)), + ], + ); + } + + Widget _inlineDivider() { + return Container( + width: 1, + height: 40, + color: Colors.white.withValues(alpha: 0.08), + ); + } + + static String _formatDuration(int seconds) { + if (seconds < 60) { + return '0:${seconds.toString().padLeft(2, '0')}'; + } + final h = seconds ~/ 3600; + final m = (seconds % 3600) ~/ 60; + if (h > 0) { + return '${h}h ${m.toString().padLeft(2, '0')}m'; + } + final s = seconds % 60; + return '${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}'; + } + + Future _confirmReset( + BuildContext context, + ScreenTimeService service, + ) async { + final first = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Reset screen time?'), + content: const Text( + 'This will clear all locally stored screen time data for the last 30 days.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.pop(ctx, true), + child: const Text( + 'Continue', + style: TextStyle(color: Colors.redAccent), + ), + ), + ], + ), + ); + if (first != true) return; + if (!context.mounted) return; + + final second = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Confirm reset'), + content: const Text( + 'Are you sure you want to permanently delete all screen time data?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('No'), + ), + TextButton( + onPressed: () => Navigator.pop(ctx, true), + child: const Text( + 'Yes, delete', + style: TextStyle(color: Colors.redAccent), + ), + ), + ], + ), + ); + if (!context.mounted) return; + if (second == true) { + await service.resetAll(); + } + } +} diff --git a/lib/features/update_checker/update_banner.dart b/lib/features/update_checker/update_banner.dart new file mode 100644 index 0000000..40fa7d3 --- /dev/null +++ b/lib/features/update_checker/update_banner.dart @@ -0,0 +1,130 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import 'update_checker_service.dart'; + +class UpdateBanner extends StatefulWidget { + final UpdateInfo updateInfo; + final VoidCallback onDismiss; + + const UpdateBanner({ + super.key, + required this.updateInfo, + required this.onDismiss, + }); + + @override + State createState() => _UpdateBannerState(); +} + +class _UpdateBannerState extends State { + bool _isExpanded = false; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + + return AnimatedContainer( + duration: const Duration(milliseconds: 200), + width: double.infinity, + decoration: BoxDecoration( + color: colorScheme.secondaryContainer, + border: Border( + bottom: BorderSide( + color: colorScheme.outlineVariant, + width: 0.5, + ), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + child: Row( + children: [ + const Text('🎉', style: TextStyle(fontSize: 16)), + const SizedBox(width: 8), + Expanded( + child: Text( + 'FocusGram ${widget.updateInfo.latestVersion} available', + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ), + IconButton( + icon: Icon( + _isExpanded ? Icons.expand_less : Icons.expand_more, + size: 18, + ), + onPressed: () { + HapticFeedback.lightImpact(); + setState(() => _isExpanded = !_isExpanded); + }, + ), + IconButton( + icon: const Icon(Icons.close, size: 18), + onPressed: () { + HapticFeedback.lightImpact(); + widget.onDismiss(); + }, + ), + ], + ), + ), + if (_isExpanded) ...[ + const Divider(height: 1), + Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + "What's new", + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Text( + _formatReleaseNotes(widget.updateInfo.whatsNew), + style: theme.textTheme.bodySmall, + ), + const SizedBox(height: 12), + SizedBox( + width: double.infinity, + child: OutlinedButton( + onPressed: () async { + final uri = Uri.parse(widget.updateInfo.releaseUrl); + await launchUrl( + uri, + mode: LaunchMode.externalApplication, + ); + }, + child: const Text('Download on GitHub'), + ), + ), + ], + ), + ), + ], + ], + ), + ); + } + + String _formatReleaseNotes(String raw) { + var text = raw; + text = text.replaceAll(RegExp(r'#{1,6}\s'), ''); + text = text.replaceAll(RegExp(r'\*\*(.*?)\*\*'), r'\1'); + text = text.replaceAll(RegExp(r'\*(.*?)\*'), r'\1'); + text = + text.replaceAll(RegExp(r'\[([^\]]+)\]\([^)]+\)'), r'\1'); // links -> text + text = text.replaceAll(RegExp(r'`([^`]+)`'), r'\1'); + return text.trim(); + } +} + diff --git a/lib/features/update_checker/update_checker_service.dart b/lib/features/update_checker/update_checker_service.dart new file mode 100644 index 0000000..9e14b18 --- /dev/null +++ b/lib/features/update_checker/update_checker_service.dart @@ -0,0 +1,105 @@ +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class UpdateInfo { + final String latestVersion; // e.g. "1.0.0" + final String releaseUrl; // html_url + final String whatsNew; // trimmed body + final bool isUpdateAvailable; + + const UpdateInfo({ + required this.latestVersion, + required this.releaseUrl, + required this.whatsNew, + required this.isUpdateAvailable, + }); +} + +class UpdateCheckerService extends ChangeNotifier { + static const String _lastDismissedKey = 'last_dismissed_update_version'; + static const String _githubUrl = + 'https://api.github.com/repos/Ujwal223/FocusGram/releases/latest'; + + UpdateInfo? _updateInfo; + bool _isDismissed = false; + + bool get hasUpdate => _updateInfo != null && !_isDismissed; + UpdateInfo? get updateInfo => hasUpdate ? _updateInfo : null; + + Future checkForUpdates() async { + try { + final response = await http + .get(Uri.parse(_githubUrl)) + .timeout(const Duration(seconds: 5)); + if (response.statusCode != 200) return; + + final data = json.decode(response.body); + final String gitVersionTag = + data['tag_name'] ?? ''; // e.g. "v0.9.8-beta.2" + final String htmlUrl = data['html_url'] ?? ''; + final String body = (data['body'] as String?) ?? ''; + + if (gitVersionTag.isEmpty || htmlUrl.isEmpty) return; + + final packageInfo = await PackageInfo.fromPlatform(); + final currentVersion = packageInfo.version; // e.g. "0.9.8-beta.2" + + if (!_isNewerVersion(gitVersionTag, currentVersion)) return; + + final prefs = await SharedPreferences.getInstance(); + final dismissedVersion = prefs.getString(_lastDismissedKey); + if (dismissedVersion == gitVersionTag) { + _isDismissed = true; + return; + } + + final cleanVersion = + gitVersionTag.startsWith('v') ? gitVersionTag.substring(1) : gitVersionTag; + + var trimmed = body.trim(); + if (trimmed.length > 1500) { + trimmed = trimmed.substring(0, 1500).trim(); + } + + _updateInfo = UpdateInfo( + latestVersion: cleanVersion, + releaseUrl: htmlUrl, + whatsNew: trimmed, + isUpdateAvailable: true, + ); + _isDismissed = false; + notifyListeners(); + } catch (e) { + debugPrint('Update check failed: $e'); + } + } + + Future dismissUpdate() async { + if (_updateInfo == null) return; + _isDismissed = true; + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_lastDismissedKey, _updateInfo!.latestVersion); + notifyListeners(); + } + + bool _isNewerVersion(String gitTag, String current) { + // Clean versions: strip 'v' and everything after '-' (beta/rc) + String cleanGit = gitTag.startsWith('v') ? gitTag.substring(1) : gitTag; + String cleanCurrent = current; + + List gitParts = cleanGit.split('-')[0].split('.'); + List currentParts = cleanCurrent.split('-')[0].split('.'); + + for (int i = 0; i < gitParts.length && i < currentParts.length; i++) { + int gitNum = int.tryParse(gitParts[i]) ?? 0; + int curNum = int.tryParse(currentParts[i]) ?? 0; + if (gitNum > curNum) return true; + if (gitNum < curNum) return false; + } + + return false; + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..172555d --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,167 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'package:app_links/app_links.dart'; +import 'services/session_manager.dart'; +import 'services/settings_service.dart'; +import 'services/screen_time_service.dart'; +import 'services/focusgram_router.dart'; +import 'services/injection_controller.dart'; +import 'screens/onboarding_page.dart'; +import 'screens/main_webview_page.dart'; +import 'screens/breath_gate_screen.dart'; +import 'screens/app_session_picker.dart'; +import 'screens/cooldown_gate_screen.dart'; +import 'services/notification_service.dart'; +import 'features/update_checker/update_checker_service.dart'; +import 'features/preloader/instagram_preloader.dart'; + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + + // Lock to portrait + await SystemChrome.setPreferredOrientations([ + DeviceOrientation.portraitUp, + DeviceOrientation.portraitDown, + ]); + + final sessionManager = SessionManager(); + final settingsService = SettingsService(); + final screenTimeService = ScreenTimeService(); + + final updateChecker = UpdateCheckerService(); + + await sessionManager.init(); + await settingsService.init(); + await screenTimeService.init(); + await NotificationService().init(); + + runApp( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: sessionManager), + ChangeNotifierProvider.value(value: settingsService), + ChangeNotifierProvider.value(value: screenTimeService), + ChangeNotifierProvider.value(value: updateChecker), + ], + child: const FocusGramApp(), + ), + ); + + // Fire and forget — preloads Instagram while app UI initialises. + unawaited(InstagramPreloader.start(InjectionController.iOSUserAgent)); +} + +class FocusGramApp extends StatelessWidget { + const FocusGramApp({super.key}); + + @override + Widget build(BuildContext context) { + final settings = context.watch(); + final isDark = settings.isDarkMode; + + return MaterialApp( + title: 'FocusGram', + debugShowCheckedModeBanner: false, + theme: ThemeData( + brightness: isDark ? Brightness.dark : Brightness.light, + colorScheme: isDark + ? ColorScheme.dark( + primary: Colors.blue.shade400, + surface: Colors.black, + ) + : ColorScheme.light(primary: Colors.blue), + scaffoldBackgroundColor: isDark ? Colors.black : Colors.white, + useMaterial3: true, + splashColor: Colors.transparent, + highlightColor: Colors.transparent, + ), + home: const InitialRouteHandler(), + ); + } +} + +/// Flow on every cold open: +/// 1. Onboarding (if first run) +/// 2. Cooldown Gate (if app-open cooldown active) +/// 3. Breath Gate (if enabled in settings) +/// 4. If an app session is already active, resume it +/// otherwise show App Session Picker +/// 5. Main WebView +class InitialRouteHandler extends StatefulWidget { + const InitialRouteHandler({super.key}); + + @override + State createState() => _InitialRouteHandlerState(); +} + +class _InitialRouteHandlerState extends State { + bool _breathCompleted = false; + bool _appSessionStarted = false; + bool _onboardingCompleted = false; + late AppLinks _appLinks; + + @override + void initState() { + super.initState(); + _appLinks = AppLinks(); + _initDeepLinks(); + } + + Future _initDeepLinks() async { + // 1. Handle background links while app is running + _appLinks.uriLinkStream.listen((uri) { + debugPrint('Incoming Deep Link: $uri'); + FocusGramRouter.pendingUrl.value = uri.toString(); + }); + + // 2. Handle the initial link that opened the app + final initialUri = await _appLinks.getInitialLink(); + if (initialUri != null) { + debugPrint('Initial Deep Link: $initialUri'); + FocusGramRouter.pendingUrl.value = initialUri.toString(); + } + } + + @override + Widget build(BuildContext context) { + final sm = context.watch(); + final settings = context.watch(); + + // Step 1: Onboarding + if (settings.isFirstRun && !_onboardingCompleted) { + return OnboardingPage( + onFinish: () => setState(() => _onboardingCompleted = true), + ); + } + + // Step 2: Cooldown gate — if too soon since last session + if (sm.isAppOpenCooldownActive) { + return const CooldownGateScreen(); + } + + // Step 3: Breath gate + if (settings.showBreathGate && !_breathCompleted) { + return BreathGateScreen( + onFinish: () => setState(() => _breathCompleted = true), + ); + } + + // Step 4: App session picker / resume existing session + if (!_appSessionStarted) { + if (sm.isAppSessionActive) { + // User already has an active app session — don't ask intention again. + _appSessionStarted = true; + } else { + return AppSessionPickerScreen( + onSessionStarted: () => setState(() => _appSessionStarted = true), + ); + } + } + + // Step 5: Main app + return const MainWebViewPage(); + } +} diff --git a/lib/screens/app_session_picker.dart b/lib/screens/app_session_picker.dart new file mode 100644 index 0000000..2490140 --- /dev/null +++ b/lib/screens/app_session_picker.dart @@ -0,0 +1,210 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../services/session_manager.dart'; + +/// Shown on every cold app open. Asks the user how long they plan to use +/// Instagram today. Uses an iOS-style scroll picker (ListWheelScrollView). +class AppSessionPickerScreen extends StatefulWidget { + final VoidCallback onSessionStarted; + const AppSessionPickerScreen({super.key, required this.onSessionStarted}); + + @override + State createState() => _AppSessionPickerScreenState(); +} + +class _AppSessionPickerScreenState extends State { + static final List _minuteOptions = [ + 5, + 10, + 15, + 20, + 25, + 30, + 35, + 40, + 45, + 50, + 55, + 60, + ]; + int _selectedIndex = 2; // default: 15 min + + @override + Widget build(BuildContext context) { + final selectedMinutes = _minuteOptions[_selectedIndex]; + + return Scaffold( + backgroundColor: Colors.black, + body: SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 32), + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + const Spacer(flex: 2), + + // Icon + Container( + width: 72, + height: 72, + decoration: BoxDecoration( + shape: BoxShape.circle, + gradient: LinearGradient( + colors: [Colors.blue.shade700, Colors.blue.shade400], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + boxShadow: [ + BoxShadow( + color: Colors.blue.withValues(alpha: 0.4), + blurRadius: 24, + spreadRadius: 4, + ), + ], + ), + child: const Icon( + Icons.timer_outlined, + color: Colors.white, + size: 36, + ), + ), + + const SizedBox(height: 28), + + const Text( + 'Set Your Intention', + style: TextStyle( + color: Colors.white, + fontSize: 26, + fontWeight: FontWeight.bold, + letterSpacing: -0.5, + ), + ), + const SizedBox(height: 10), + const Text( + 'How long do you plan to use\nInstagram right now?', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white54, + fontSize: 15, + height: 1.5, + ), + ), + + const Spacer(flex: 1), + + // iOS-style scroll picker + SizedBox( + height: 220, + child: Stack( + alignment: Alignment.center, + children: [ + // Selection highlight + Container( + height: 50, + margin: const EdgeInsets.symmetric(horizontal: 0), + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Colors.blue.withValues(alpha: 0.3), + width: 1, + ), + ), + ), + ListWheelScrollView.useDelegate( + itemExtent: 50, + physics: const FixedExtentScrollPhysics(), + perspective: 0.003, + squeeze: 1.1, + diameterRatio: 2.5, + onSelectedItemChanged: (i) { + setState(() => _selectedIndex = i); + }, + controller: FixedExtentScrollController( + initialItem: _selectedIndex, + ), + childDelegate: ListWheelChildListDelegate( + children: _minuteOptions.asMap().entries.map((entry) { + final isSelected = entry.key == _selectedIndex; + return Center( + child: RichText( + text: TextSpan( + children: [ + TextSpan( + text: '${entry.value}', + style: TextStyle( + fontSize: isSelected ? 28 : 22, + fontWeight: isSelected + ? FontWeight.bold + : FontWeight.w300, + color: isSelected + ? Colors.white + : Colors.white38, + ), + ), + TextSpan( + text: ' min', + style: TextStyle( + fontSize: isSelected ? 16 : 14, + color: isSelected + ? Colors.white70 + : Colors.white24, + ), + ), + ], + ), + ), + ); + }).toList(), + ), + ), + ], + ), + ), + + const Spacer(flex: 1), + + // Confirm button + SizedBox( + width: double.infinity, + height: 54, + child: ElevatedButton( + onPressed: () => _confirm(context, selectedMinutes), + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + elevation: 0, + ), + child: Text( + 'Start $selectedMinutes-Minute Session', + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + + const SizedBox(height: 16), + const Text( + 'You\'ll be prompted to close the app when your time is up.', + textAlign: TextAlign.center, + style: TextStyle(color: Colors.white24, fontSize: 12), + ), + const Spacer(flex: 1), + ], + ), + ), + ), + ); + } + + void _confirm(BuildContext context, int minutes) { + context.read().startAppSession(minutes); + widget.onSessionStarted(); + } +} diff --git a/lib/screens/breath_gate_screen.dart b/lib/screens/breath_gate_screen.dart new file mode 100644 index 0000000..6acf5eb --- /dev/null +++ b/lib/screens/breath_gate_screen.dart @@ -0,0 +1,143 @@ +import 'package:flutter/material.dart'; +import 'dart:async'; + +/// A mindfulness screen shown before the app opens. +/// Forces the user to take a deep 10-second breath. +class BreathGateScreen extends StatefulWidget { + final VoidCallback onFinish; + + const BreathGateScreen({super.key, required this.onFinish}); + + @override + State createState() => _BreathGateScreenState(); +} + +class _BreathGateScreenState extends State + with TickerProviderStateMixin { + late AnimationController _controller; + late Animation _scaleAnimation; + int _secondsRemaining = 10; + Timer? _timer; + bool _canContinue = false; + + @override + void initState() { + super.initState(); + + // 10-second breathing animation: 5s in, 5s out + _controller = AnimationController( + vsync: this, + duration: const Duration(seconds: 5), + ); + + _scaleAnimation = Tween( + begin: 1.0, + end: 1.5, + ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut)); + + _controller.repeat(reverse: true); + + _startCountdown(); + } + + void _startCountdown() { + _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + if (_secondsRemaining > 0) { + setState(() => _secondsRemaining--); + } else { + setState(() { + _canContinue = true; + _timer?.cancel(); + }); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + _timer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + body: Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 40.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text( + 'Are you sure you want to open FocusGram?', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.w300, + ), + ), + const SizedBox(height: 80), + + // Animated Breath Circle + ScaleTransition( + scale: _scaleAnimation, + child: Container( + width: 100, + height: 100, + decoration: BoxDecoration( + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: Colors.blue.withValues(alpha: 0.3), + blurRadius: 30, + spreadRadius: 10, + ), + ], + gradient: const RadialGradient( + colors: [Colors.blue, Colors.black], + ), + ), + ), + ), + + const SizedBox(height: 80), + + Text( + _canContinue + ? 'Breathed.' + : 'Take a deep breath for $_secondsRemaining seconds...', + style: const TextStyle( + color: Colors.white70, + fontSize: 16, + fontStyle: FontStyle.italic, + ), + ), + + const SizedBox(height: 40), + + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: _canContinue ? widget.onFinish : null, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.white, + foregroundColor: Colors.black, + disabledBackgroundColor: Colors.white10, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(25), + ), + ), + child: const Text('Continue to FocusGram'), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/screens/cooldown_gate_screen.dart b/lib/screens/cooldown_gate_screen.dart new file mode 100644 index 0000000..0904292 --- /dev/null +++ b/lib/screens/cooldown_gate_screen.dart @@ -0,0 +1,170 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../services/session_manager.dart'; + +/// Blocking screen shown when the user tries to reopen the app too soon +/// after their last session ended. Shows a countdown and a motivational quote. +class CooldownGateScreen extends StatefulWidget { + const CooldownGateScreen({super.key}); + + @override + State createState() => _CooldownGateScreenState(); +} + +class _CooldownGateScreenState extends State { + Timer? _timer; + static const List _quotes = [ + '"The discipline you show offline\nshapes the clarity you experience online."', + '"Every moment away from the screen\nis a moment given back to yourself."', + '"Boredom is the birthplace of creativity.\nLet it breathe."', + '"Your attention is your most valuable asset.\nSpend it wisely."', + '"Presence is a gift you give yourself first."', + '"Rest is not wasted time.\nIt is the foundation of focused action."', + ]; + late final String _quote; + + @override + void initState() { + super.initState(); + _quote = _quotes[DateTime.now().second % _quotes.length]; + _timer = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) setState(() {}); + }); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final sm = context.watch(); + final remaining = sm.appOpenCooldownRemainingSeconds; + final minutes = remaining ~/ 60; + final seconds = remaining % 60; + + // If cooldown expired, pop this gate + if (!sm.isAppOpenCooldownActive) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) Navigator.of(context).maybePop(); + }); + } + + return Scaffold( + backgroundColor: Colors.black, + body: SafeArea( + child: Center( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 40), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // Icon + Container( + width: 80, + height: 80, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.orange.withValues(alpha: 0.12), + border: Border.all( + color: Colors.orangeAccent.withValues(alpha: 0.4), + width: 1.5, + ), + ), + child: const Icon( + Icons.hourglass_top_rounded, + color: Colors.orangeAccent, + size: 38, + ), + ), + + const SizedBox(height: 32), + const Text( + 'Take a Break', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontSize: 28, + fontWeight: FontWeight.bold, + letterSpacing: -0.5, + ), + ), + + const SizedBox(height: 12), + const Text( + 'Your session has ended.\nCome back when the timer expires.', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white54, + fontSize: 15, + height: 1.5, + ), + ), + + const SizedBox(height: 48), + + // Countdown + Container( + padding: const EdgeInsets.symmetric( + horizontal: 32, + vertical: 20, + ), + decoration: BoxDecoration( + color: Colors.orange.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: Colors.orangeAccent.withValues(alpha: 0.25), + width: 1, + ), + ), + child: Column( + children: [ + const Text( + 'Return in', + style: TextStyle( + color: Colors.white38, + fontSize: 13, + letterSpacing: 1.2, + ), + ), + const SizedBox(height: 8), + Text( + '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}', + style: const TextStyle( + color: Colors.orangeAccent, + fontSize: 52, + fontWeight: FontWeight.w200, + letterSpacing: 4, + ), + ), + ], + ), + ), + + const SizedBox(height: 60), + + // Quote + Text( + _quote, + textAlign: TextAlign.center, + style: const TextStyle( + color: Colors.white30, + fontSize: 13, + height: 1.7, + fontStyle: FontStyle.italic, + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/screens/guardrails_page.dart b/lib/screens/guardrails_page.dart new file mode 100644 index 0000000..e3c86af --- /dev/null +++ b/lib/screens/guardrails_page.dart @@ -0,0 +1,373 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../services/session_manager.dart'; +import '../services/settings_service.dart'; +import '../utils/discipline_challenge.dart'; + +class GuardrailsPage extends StatefulWidget { + const GuardrailsPage({super.key}); + + @override + State createState() => _GuardrailsPageState(); +} + +class _GuardrailsPageState extends State { + Future _handleScheduleAction( + BuildContext context, + SessionManager sm, + Future Function() action, + ) async { + if (sm.isScheduledBlockActive) { + final ok = await DisciplineChallenge.show(context, count: 35); + if (!context.mounted || !ok) return; + } + await action(); + } + + Future _pickNewSchedule(BuildContext context, SessionManager sm) async { + final start = await showTimePicker( + context: context, + initialTime: const TimeOfDay(hour: 22, minute: 0), + helpText: 'Select Start Time', + ); + if (!context.mounted || start == null) return; + + final end = await showTimePicker( + context: context, + initialTime: const TimeOfDay(hour: 7, minute: 0), + helpText: 'Select End Time', + ); + if (!context.mounted || end == null) return; + + await sm.addSchedule( + FocusSchedule( + startHour: start.hour, + startMinute: start.minute, + endHour: end.hour, + endMinute: end.minute, + ), + ); + } + + Future _editExistingSchedule( + BuildContext context, + SessionManager sm, + int index, + FocusSchedule s, + ) async { + final start = await showTimePicker( + context: context, + initialTime: TimeOfDay(hour: s.startHour, minute: s.startMinute), + helpText: 'Edit Start Time', + ); + if (!context.mounted || start == null) return; + + final end = await showTimePicker( + context: context, + initialTime: TimeOfDay(hour: s.endHour, minute: s.endMinute), + helpText: 'Edit End Time', + ); + if (!context.mounted || end == null) return; + + await sm.updateScheduleAt( + index, + FocusSchedule( + startHour: start.hour, + startMinute: start.minute, + endHour: end.hour, + endMinute: end.minute, + ), + ); + } + + @override + Widget build(BuildContext context) { + final sm = context.watch(); + final settings = context.watch(); + final isDark = settings.isDarkMode; + + return Scaffold( + appBar: AppBar( + title: const Text( + 'Guardrails', + style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold), + ), + leading: IconButton( + icon: const Icon(Icons.arrow_back_ios_new, size: 18), + onPressed: () => Navigator.pop(context), + ), + ), + body: ListView( + children: [ + Padding( + padding: const EdgeInsets.all(16.0), + child: Text( + 'Set your limits to stay focused. Changes to these settings require a challenge.', + style: TextStyle( + color: isDark ? Colors.white54 : Colors.black54, + fontSize: 13, + ), + ), + ), + _buildFrictionSliderTile( + context: context, + sm: sm, + title: 'Daily Reel Limit', + subtitle: '${sm.dailyLimitSeconds ~/ 60} min / day', + value: (sm.dailyLimitSeconds ~/ 60).toDouble(), + min: 5, + max: 120, + divisor: 5, + isMorePermissive: (v) => v > (sm.dailyLimitSeconds ~/ 60), + warningText: + 'Increasing your limit makes it easier to scroll. Are you sure?', + onConfirmed: (v) => sm.setDailyLimitMinutes(v.toInt()), + ), + _buildFrictionSliderTile( + context: context, + sm: sm, + title: 'Session Cooldown', + subtitle: '${sm.cooldownSeconds ~/ 60} min between sessions', + value: (sm.cooldownSeconds ~/ 60).toDouble(), + min: 5, + max: 180, + divisor: 5, + isMorePermissive: (v) => v < (sm.cooldownSeconds ~/ 60), + warningText: + 'Reducing cooldown makes it easier to start new sessions. Are you sure?', + onConfirmed: (v) => sm.setCooldownMinutes(v.toInt()), + ), + Divider(color: isDark ? Colors.white10 : Colors.black12, height: 32), + SwitchListTile( + title: const Text('Scheduled Blocking'), + subtitle: Text( + 'Block Instagram during specific hours', + style: TextStyle( + color: isDark ? Colors.white54 : Colors.black54, + fontSize: 13, + ), + ), + value: sm.scheduleEnabled, + onChanged: (v) => sm.setScheduleEnabled(v), + ), + if (sm.scheduleEnabled) ...[ + ...sm.schedules.asMap().entries.map((entry) { + final idx = entry.key; + final s = entry.value; + return ListTile( + title: Text( + 'Schedule ${idx + 1}', + style: const TextStyle(fontSize: 14), + ), + subtitle: Text( + '${sm.formatTime12h(s.startHour, s.startMinute)} - ${sm.formatTime12h(s.endHour, s.endMinute)}', + style: TextStyle( + color: isDark ? Colors.white54 : Colors.black54, + fontSize: 13, + ), + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon( + Icons.edit, + color: Colors.blue, + size: 20, + ), + onPressed: () => _handleScheduleAction( + context, + sm, + () => _editExistingSchedule(context, sm, idx, s), + ), + ), + IconButton( + icon: const Icon( + Icons.delete_outline, + color: Colors.redAccent, + size: 20, + ), + onPressed: () => _handleScheduleAction( + context, + sm, + () => sm.removeScheduleAt(idx), + ), + ), + ], + ), + ); + }), + ListTile( + leading: const Icon( + Icons.add_circle_outline, + color: Colors.blueAccent, + ), + title: const Text( + 'Add Focus Hours', + style: TextStyle( + color: Colors.blueAccent, + fontWeight: FontWeight.w600, + ), + ), + onTap: () => _handleScheduleAction( + context, + sm, + () => _pickNewSchedule(context, sm), + ), + ), + ], + ], + ), + ); + } + + Widget _buildFrictionSliderTile({ + required BuildContext context, + required SessionManager sm, + required String title, + required String subtitle, + required double value, + required double min, + required double max, + required int divisor, + required bool Function(double) isMorePermissive, + required String warningText, + required Future Function(double) onConfirmed, + }) { + return _FrictionSliderTile( + title: title, + subtitle: subtitle, + value: value, + min: min, + max: max, + divisor: divisor, + isMorePermissive: isMorePermissive, + warningText: warningText, + onConfirmed: onConfirmed, + ); + } +} + +class _FrictionSliderTile extends StatefulWidget { + final String title; + final String subtitle; + final double value; + final double min; + final double max; + final int divisor; + final bool Function(double) isMorePermissive; + final String warningText; + final Future Function(double) onConfirmed; + + const _FrictionSliderTile({ + required this.title, + required this.subtitle, + required this.value, + required this.min, + required this.max, + required this.divisor, + required this.isMorePermissive, + required this.warningText, + required this.onConfirmed, + }); + + @override + State<_FrictionSliderTile> createState() => _FrictionSliderTileState(); +} + +class _FrictionSliderTileState extends State<_FrictionSliderTile> { + late double _draftValue; + bool _pendingConfirm = false; + + @override + void initState() { + super.initState(); + _draftValue = widget.value; + } + + @override + void didUpdateWidget(_FrictionSliderTile old) { + super.didUpdateWidget(old); + if (!_pendingConfirm) _draftValue = widget.value; + } + + @override + Widget build(BuildContext context) { + final settings = context.watch(); + final isDark = settings.isDarkMode; + final divisions = ((widget.max - widget.min) / widget.divisor).round(); + + return Column( + children: [ + ListTile( + title: Text(widget.title), + subtitle: Text( + '${_draftValue.toInt()} min', + style: TextStyle(color: isDark ? Colors.white70 : Colors.black54), + ), + trailing: _pendingConfirm + ? Row( + mainAxisSize: MainAxisSize.min, + children: [ + TextButton( + onPressed: () { + setState(() { + _draftValue = widget.value; + _pendingConfirm = false; + }); + }, + child: const Text('Cancel'), + ), + ElevatedButton( + onPressed: () async { + final sm = context.read(); + int wordCount = 15; + // If we are at 0 quota, increase difficulty to 35 words + if (widget.title.contains('Daily Reel Limit') && + sm.dailyRemainingSeconds <= 0) { + wordCount = 35; + } + final success = await DisciplineChallenge.show( + context, + count: wordCount, + ); + if (!context.mounted || !success) return; + await widget.onConfirmed(_draftValue); + setState(() => _pendingConfirm = false); + }, + child: const Text('Apply'), + ), + ], + ) + : null, + ), + if (_pendingConfirm) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: Text( + widget.warningText, + style: const TextStyle(color: Colors.orangeAccent, fontSize: 12), + ), + ), + Slider( + value: _draftValue, + min: widget.min, + max: widget.max, + divisions: divisions, + onChanged: (v) { + setState(() { + _draftValue = v; + _pendingConfirm = widget.isMorePermissive(v); + }); + }, + onChangeEnd: (v) { + if (!widget.isMorePermissive(v)) { + widget.onConfirmed(v); + setState(() => _pendingConfirm = false); + } + }, + ), + ], + ); + } +} diff --git a/lib/screens/main_webview_page.dart b/lib/screens/main_webview_page.dart new file mode 100644 index 0000000..d93d23c --- /dev/null +++ b/lib/screens/main_webview_page.dart @@ -0,0 +1,1843 @@ +import 'dart:async'; +import 'dart:collection'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'package:url_launcher/url_launcher.dart'; +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../services/session_manager.dart'; +import '../services/settings_service.dart'; +import '../services/injection_controller.dart'; +import '../services/injection_manager.dart'; +import '../scripts/autoplay_blocker.dart'; +import '../scripts/native_feel.dart'; +import '../scripts/haptic_bridge.dart'; +import '../scripts/spa_navigation_monitor.dart'; +import '../scripts/content_disabling.dart'; +import '../services/screen_time_service.dart'; +import '../services/navigation_guard.dart'; +import '../services/focusgram_router.dart'; +import 'package:google_fonts/google_fonts.dart'; +import '../services/notification_service.dart'; +import '../features/update_checker/update_checker_service.dart'; +import '../utils/discipline_challenge.dart'; +import 'settings_page.dart'; +import '../features/loading/skeleton_screen.dart'; +import '../features/preloader/instagram_preloader.dart'; + +class MainWebViewPage extends StatefulWidget { + const MainWebViewPage({super.key}); + + @override + State createState() => _MainWebViewPageState(); +} + +class _MainWebViewPageState extends State + with WidgetsBindingObserver { + InAppWebViewController? _controller; + late final PullToRefreshController _pullToRefreshController; + InjectionManager? _injectionManager; + final GlobalKey<_EdgePanelState> _edgePanelKey = GlobalKey<_EdgePanelState>(); + bool _showSkeleton = + true; // true from the start so skeleton covers black Scaffold before WebView first paints + bool _isLoading = true; + Timer? _watchdog; + // FIX 4: Safety timer to clear stuck loading state + Timer? _loadingTimeout; + bool _extensionDialogShown = false; + bool _lastSessionActive = false; + String _currentUrl = 'https://www.instagram.com/'; + bool _hasError = false; +bool _reelsBlockedOverlay = false; + bool _exploreBlockedOverlay = false; + bool _isPreloaded = false; + bool _minimalModeBannerDismissed = false; + DateTime _lastMainFrameLoadStartedAt = DateTime.fromMillisecondsSinceEpoch(0); + SkeletonType _skeletonType = SkeletonType.generic; + + /// Helper to determine if we are on a login/onboarding page. + bool get _isOnOnboardingPage { + final path = Uri.tryParse(_currentUrl)?.path ?? ''; + final lowerPath = path.toLowerCase(); + return lowerPath.contains('/accounts/login') || + lowerPath.contains('/accounts/emailsignup') || + lowerPath.contains('/accounts/signup') || + lowerPath.contains('/legal/') || + lowerPath.contains('/help/') || + _currentUrl.contains('instagram.com/accounts/login'); + } + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _initPullToRefresh(); + _initWebView(); + _startWatchdog(); + + // Check for updates on launch + context.read().checkForUpdates(); + + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().addListener(_onSessionChanged); + context.read().addListener(_onSettingsChanged); + _lastSessionActive = context.read().isSessionActive; + // Initialise structural snapshots so first change is detected correctly + final settings = context.read(); + _lastMinimalMode = settings.minimalModeEnabled; + _lastDisableReels = settings.disableReelsEntirely; + _lastDisableExplore = settings.disableExploreEntirely; + _lastBlockAutoplay = settings.blockAutoplay; + }); + + FocusGramRouter.pendingUrl.addListener(_onPendingUrlChanged); + } + + void _onPendingUrlChanged() { + final url = FocusGramRouter.pendingUrl.value; + if (url != null && url.isNotEmpty) { + FocusGramRouter.pendingUrl.value = null; + _controller?.loadUrl(urlRequest: URLRequest(url: WebUri(url))); + } + } + + /// Sets the isolated reel player flag in the WebView so the scroll-lock + /// knows it should block swipe-to-next-reel. + Future _setIsolatedPlayer(bool active) async { + await _controller?.evaluateJavascript( + source: 'window.__focusgramIsolatedPlayer = $active;', + ); + } + + void _onSessionChanged() { + if (!mounted) return; + final sm = context.read(); + if (_lastSessionActive != sm.isSessionActive) { + _lastSessionActive = sm.isSessionActive; + + if (_lastSessionActive) { + HapticFeedback.mediumImpact(); + } else { + HapticFeedback.heavyImpact(); + } + + if (_controller != null && _injectionManager != null) { + _injectionManager!.runAllPostLoadInjections(_currentUrl); + } + + // If session became active and we were showing overlay, hide it + if (_lastSessionActive && _reelsBlockedOverlay) { + setState(() => _reelsBlockedOverlay = false); + } + } + setState(() {}); + } + + // Debounce timer so rapid toggles don't spam reloads + Timer? _reloadDebounce; + + // Snapshot of structural settings — used to detect when a reload is needed + bool _lastMinimalMode = false; + bool _lastDisableReels = false; + bool _lastDisableExplore = false; + bool _lastBlockAutoplay = false; + + void _onSettingsChanged() { + if (!mounted) return; + final settings = context.read(); + + // 1. Apply all cosmetic changes immediately via injection + if (_controller != null) { + _controller!.evaluateJavascript( + source: 'window.__fgBlockAutoplay = ${settings.blockAutoplay}; window.__fgTapToUnblur = ${settings.blurExplore && settings.tapToUnblur};', + ); + } + if (_controller != null && _injectionManager != null) { + _injectionManager!.runAllPostLoadInjections(_currentUrl); + } + + // 2. Rebuild Flutter widget tree (e.g. overlay conditions, banner state) + setState(() {}); + + // 3. Detect structural changes that need a full reload. + // CSS injection alone can't undo Instagram's already-rendered React DOM. + final structuralChange = + settings.minimalModeEnabled != _lastMinimalMode || + settings.disableReelsEntirely != _lastDisableReels || + settings.disableExploreEntirely != _lastDisableExplore || + settings.blockAutoplay != _lastBlockAutoplay; + + _lastMinimalMode = settings.minimalModeEnabled; + _lastDisableReels = settings.disableReelsEntirely; + _lastDisableExplore = settings.disableExploreEntirely; + _lastBlockAutoplay = settings.blockAutoplay; + + if (structuralChange && _controller != null) { + // Debounce: if user toggles rapidly, only reload once they stop + _reloadDebounce?.cancel(); + _reloadDebounce = Timer(const Duration(milliseconds: 600), () { + if (mounted) _controller?.reload(); + }); + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _watchdog?.cancel(); + _loadingTimeout?.cancel(); + _reloadDebounce?.cancel(); + FocusGramRouter.pendingUrl.removeListener(_onPendingUrlChanged); + context.read().removeListener(_onSessionChanged); + context.read().removeListener(_onSettingsChanged); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (!mounted) return; + final sm = context.read(); + final screenTime = context.read(); + final settings = context.read(); + + if (state == AppLifecycleState.resumed) { + sm.setAppForeground(true); + screenTime.startTracking(); + // Cancel persistent notification when app comes to foreground + NotificationService().cancelPersistentNotification(id: 5001); + } else if (state == AppLifecycleState.paused || + state == AppLifecycleState.inactive || + state == AppLifecycleState.detached) { + sm.setAppForeground(false); + screenTime.stopTracking(); + + // Show persistent notification when schedules are active (if enabled) + if (settings.notifyPersistent) { + final isScheduleActive = sm.isScheduledBlockActive; + final isGrayscaleActive = settings.isGrayscaleActiveNow; + + if (isScheduleActive) { + NotificationService().showPersistentNotification( + id: 5001, + title: 'FocusGram - Schedule Active', + body: 'Instagram is blocked during your focus hours', + ); + } else if (isGrayscaleActive) { + NotificationService().showPersistentNotification( + id: 5001, + title: 'FocusGram - Grayscale Active', + body: 'Instagram is in grayscale mode', + ); + } + } + } + } + + void _startWatchdog() { + _watchdog = Timer.periodic(const Duration(seconds: 15), (_) { + if (!mounted) return; + final sm = context.read(); + if (sm.isAppSessionExpired && !_extensionDialogShown) { + _extensionDialogShown = true; + _showSessionExpiredDialog(sm); + } + }); + } + + // FIX 4: Cancel any existing loading timeout and start a fresh one. + // If onLoadStop or onReceivedError haven't fired after 12 seconds, + // force-clear the loading/skeleton state so the app never appears stuck. + void _resetLoadingTimeout() { + _loadingTimeout?.cancel(); + _loadingTimeout = Timer(const Duration(seconds: 12), () { + if (!mounted) return; + if (_isLoading || _showSkeleton) { + setState(() { + _isLoading = false; + _showSkeleton = false; + }); + } + }); + } + + void _showSessionExpiredDialog(SessionManager sm) { + // Helper function to handle "Close App" action + void closeApp() { + Navigator.of(context, rootNavigator: true).pop(); + sm.endAppSession(); + SystemNavigator.pop(); + } + + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) { + // Intercept back button - treat it as "Close App" action + if (!didPop) { + closeApp(); + } + }, + child: AlertDialog( + backgroundColor: const Color(0xFF1A1A1A), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + title: const Text( + 'Session Complete ✓', + style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Your planned Instagram time is up.', + style: TextStyle(color: Colors.white70), + ), + if (sm.canExtendAppSession) ...[ + const SizedBox(height: 8), + const Text( + 'You can extend once by 10 minutes.', + style: TextStyle(color: Colors.white54, fontSize: 13), + ), + ], + ], + ), + actions: [ + TextButton( + onPressed: closeApp, + child: const Text( + 'Close App', + style: TextStyle(color: Colors.redAccent), + ), + ), + if (sm.canExtendAppSession) + ElevatedButton( + onPressed: () { + Navigator.of(context, rootNavigator: true).pop(); + sm.extendAppSession(); + _extensionDialogShown = false; + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + child: const Text('+10 minutes'), + ), + ], + ), + ), + ); + } + + void _initPullToRefresh() { + _pullToRefreshController = PullToRefreshController( + settings: PullToRefreshSettings(color: Colors.blue), + onRefresh: () async { + await _controller?.reload(); + }, + ); + } + + void _initWebView() { + // Preloader disabled — keepAlive WebView silently fails when app cold-starts, + // leaving _isPreloaded = true with no content, causing permanent black screen. + // The fresh load path is reliable; the ~300ms preload gain is not worth it. + _isPreloaded = false; + + setState(() { + _currentUrl = 'https://www.instagram.com/accounts/login/'; + }); + + // If not preloaded, controller will be created in onWebViewCreated + _injectionManager = null; + + // Nothing else to do here – configuration is on the InAppWebView widget + } + + Future _signOut() async { + final cookieManager = CookieManager.instance(); + await cookieManager.deleteAllCookies(); + await InAppWebViewController.clearAllCache(); + if (mounted) { + setState(() { + _showSkeleton = true; + _isLoading = true; + _reelsBlockedOverlay = false; + }); + await _controller?.loadUrl( + urlRequest: URLRequest( + url: WebUri('https://www.instagram.com/accounts/login/'), + ), + ); + } + } + + /// Formats [seconds] as `MM:SS` for the cooldown countdown display. + static String _fmtSeconds(int seconds) { + final m = (seconds ~/ 60).toString().padLeft(2, '0'); + final s = (seconds % 60).toString().padLeft(2, '0'); + return '$m:$s'; + } + + Future _showReelSessionPicker() async { + final settings = context.read(); + if (settings.requireWordChallenge) { + final passed = await DisciplineChallenge.show(context); + if (!passed || !mounted) return; + } + _showReelSessionPickerBottomSheet(); + } + + void _showReelSessionPickerBottomSheet() { + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (context) => Container( + height: MediaQuery.of(context).size.height * 0.7, + decoration: BoxDecoration( + color: const Color(0xFF121212), + borderRadius: BorderRadius.circular(25), + ), + child: Column( + children: [ + const SizedBox(height: 16), + const Text( + 'Start Reel Session', + style: TextStyle( + color: Colors.white, + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + const Padding( + padding: EdgeInsets.all(12), + child: Text( + 'Reels will be unblocked for the duration you choose.', + textAlign: TextAlign.center, + style: TextStyle(color: Colors.white54, fontSize: 13), + ), + ), + Expanded( + child: ListView( + padding: const EdgeInsets.symmetric(horizontal: 20), + children: [ + _buildReelSessionTile(5), + _buildReelSessionTile(10), + _buildReelSessionTile(15), + const SizedBox(height: 40), + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text( + 'Cancel', + style: TextStyle(color: Colors.white38), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + + Widget _buildReelSessionTile(int mins) { + final sm = context.read(); + return ListTile( + title: Text('$mins Minutes', style: const TextStyle(color: Colors.white)), + trailing: const Icon( + Icons.arrow_forward_ios, + color: Colors.white24, + size: 14, + ), + onTap: () async { + Navigator.pop(context); + if (sm.startSession(mins)) { + HapticFeedback.mediumImpact(); + setState(() => _reelsBlockedOverlay = false); + await _controller?.loadUrl( + urlRequest: URLRequest( + url: WebUri('https://www.instagram.com/reels/'), + ), + ); + } + }, + ); + } + + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + if (_reelsBlockedOverlay) { + setState(() => _reelsBlockedOverlay = false); + await _controller?.goBack(); + return; + } + final didNavigate = + await (_controller + ?.evaluateJavascript( + source: + '(function(){' + ' var before = window.location.href;' + ' history.back();' + ' return before;' + '})()', + ) + .then((_) => true) + .catchError((_) => false)) ?? + false; + if (didNavigate == true) { + await Future.delayed(const Duration(milliseconds: 120)); + return; + } + if (await (_controller?.canGoBack() ?? Future.value(false))) { + await _controller?.goBack(); + } else { + SystemNavigator.pop(); + } + }, + child: Scaffold( + // FIX 1: Use a solid color that matches the WebView background. + // When transparentBackground is false (see WebView settings), the + // WebView renders its own white/black background. Using black here + // matches the dark-mode WebView bg and prevents "flash of white". + backgroundColor: Colors.black, + body: Stack( + children: [ + SafeArea( + child: Column( + children: [ + const _UpdateBanner(), + if (!_isOnOnboardingPage) + _BrandedTopBar( + onFocusControlTap: () => + _edgePanelKey.currentState?._toggleExpansion(), + ), + Expanded( + child: Consumer( + builder: (ctx, sm, _) { + if (sm.isScheduledBlockActive) { + return Container( + color: Colors.black, + padding: const EdgeInsets.all(32), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon( + Icons.bedtime_rounded, + color: Colors.blueAccent, + size: 80, + ), + const SizedBox(height: 24), + Text( + 'Focus Hours Active', + style: GoogleFonts.grandHotel( + color: Colors.white, + fontSize: 42, + ), + ), + const SizedBox(height: 12), + Text( + 'Instagram is blocked according to your schedule (${sm.activeScheduleText ?? 'Focus Hours'}).', + textAlign: TextAlign.center, + style: const TextStyle( + color: Colors.white70, + fontSize: 15, + height: 1.5, + ), + ), + const SizedBox(height: 48), + const Text( + 'Your future self will thank you for the extra sleep and focus.', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white38, + fontSize: 12, + fontStyle: FontStyle.italic, + ), + ), + ], + ), + ); + } + + final settings = context.read(); + + return Stack( + children: [ + InAppWebView( + keepAlive: InstagramPreloader.keepAlive, + initialUrlRequest: _isPreloaded + ? null + : URLRequest( + url: WebUri( + 'https://www.instagram.com/accounts/login/', + ), + ), + initialSettings: InAppWebViewSettings( + userAgent: InjectionController.iOSUserAgent, + mediaPlaybackRequiresUserGesture: + settings.blockAutoplay, + useHybridComposition: true, + cacheEnabled: true, + cacheMode: CacheMode.LOAD_CACHE_ELSE_NETWORK, + domStorageEnabled: true, + databaseEnabled: true, + hardwareAcceleration: true, + // FIX 2: Set to false so the WebView renders + // its own opaque background. When true + black + // Scaffold, you see black until Instagram + // finishes painting — looks like a freeze/hang. + transparentBackground: false, + safeBrowsingEnabled: false, + disableContextMenu: false, + supportZoom: false, + allowsInlineMediaPlayback: true, + verticalScrollBarEnabled: false, + horizontalScrollBarEnabled: false, + ), + initialUserScripts: UnmodifiableListView([ + UserScript( + source: + 'window.__fgBlockAutoplay = ${settings.blockAutoplay}; window.__fgTapToUnblur = ${settings.blurExplore && settings.tapToUnblur}; window.__focusgramSessionActive = ${sm.isSessionActive};', + injectionTime: + UserScriptInjectionTime.AT_DOCUMENT_START, + ), + UserScript( + source: kAutoplayBlockerJS, + injectionTime: + UserScriptInjectionTime.AT_DOCUMENT_START, + ), + UserScript( + source: kSpaNavigationMonitorScript, + injectionTime: + UserScriptInjectionTime.AT_DOCUMENT_START, + ), + UserScript( + source: kNativeFeelingScript, + injectionTime: + UserScriptInjectionTime.AT_DOCUMENT_START, + ), + if (settings.disableReelsEntirely) + UserScript( + source: kDisableReelsEntirelyCssScript, + injectionTime: + UserScriptInjectionTime.AT_DOCUMENT_START, + ), + if (settings.disableExploreEntirely) + UserScript( + source: kDisableExploreEntirelyCssScript, + injectionTime: + UserScriptInjectionTime.AT_DOCUMENT_START, + ), + UserScript( + source: kHapticBridgeScript, + injectionTime: + UserScriptInjectionTime.AT_DOCUMENT_START, + ), + ]), + pullToRefreshController: _pullToRefreshController, + onWebViewCreated: (controller) async { + _controller = controller; + + // Capture settingsService before async gap to avoid BuildContext warning + final settingsService = context + .read(); + final prefs = + await SharedPreferences.getInstance(); + _injectionManager = InjectionManager( + controller: controller, + prefs: prefs, + sessionManager: sm, + ); + _injectionManager!.setSettingsService( + settingsService, + ); + + _registerJavaScriptHandlers(controller); + + // Start safety timeout — clears loading state + // if onLoadStop never fires (e.g. network stall). + _resetLoadingTimeout(); + }, + onLoadStart: (controller, url) { + if (!mounted) return; + final u = url?.toString() ?? ''; + final lower = u.toLowerCase(); + final isOnboardingUrl = + lower.contains('/accounts/login') || + lower.contains('/accounts/emailsignup') || + lower.contains('/accounts/signup') || + lower.contains('/legal/') || + lower.contains('/help/'); + setState(() { + _isLoading = true; + _lastMainFrameLoadStartedAt = DateTime.now(); + _currentUrl = u; + _hasError = false; + _showSkeleton = !isOnboardingUrl; + // Update skeleton type based on the URL being loaded + _skeletonType = getSkeletonTypeFromUrl(u); + }); + // FIX 4: Reset the safety timeout on each new load + _resetLoadingTimeout(); + }, + onLoadStop: (controller, url) async { + _pullToRefreshController.endRefreshing(); + if (!mounted) return; + + // FIX 4: Cancel the safety timeout — load completed normally + _loadingTimeout?.cancel(); + + final current = url?.toString() ?? ''; + setState(() { + _isLoading = false; + _currentUrl = current; + _hasError = false; + }); + + await _injectionManager + ?.runAllPostLoadInjections(current); + + await controller.evaluateJavascript( + source: + InjectionController.notificationBridgeJS, + ); + + final isIsolatedReel = + current.contains('/reel/') && + !current.contains('/reels/'); + await _setIsolatedPlayer(isIsolatedReel); + + await controller.evaluateJavascript( + source: kNativeFeelingPostLoadScript, + ); + + await Future.delayed( + const Duration(milliseconds: 100), + ); + if (mounted) { + setState(() => _showSkeleton = false); + } + }, + shouldOverrideUrlLoading: + (controller, navigationAction) async { + final url = + navigationAction.request.url + ?.toString() ?? + ''; + final uri = navigationAction.request.url; + final appSettings = context + .read(); + + final disableReels = + appSettings.disableReelsEntirely; + final disableExplore = + appSettings.disableExploreEntirely; + + bool isReelsUrl(String u) => + u.contains('/reel/') || + u.contains('/reels/'); + bool isExploreUrl(String u) => + u.contains('/explore/'); + + void showBlocked(String msg) { + if (!mounted) return; + ScaffoldMessenger.of( + context, + ).showSnackBar( + SnackBar( + content: Text(msg), + behavior: SnackBarBehavior.floating, + margin: const EdgeInsets.fromLTRB( + 16, + 0, + 16, + 20, + ), + ), + ); + } + + if (disableReels && isReelsUrl(url)) { + showBlocked('Reels are disabled'); + return NavigationActionPolicy.CANCEL; + } + + if (disableExplore && isExploreUrl(url)) { + // Show overlay immediately without navigating away + setState(() => _exploreBlockedOverlay = true); + // Don't go back - just block the navigation + return NavigationActionPolicy.CANCEL; + } + + if (uri != null && + uri.host.contains('instagram.com') && + (url.contains('accounts/settings') || + url.contains('accounts/edit'))) { + return NavigationActionPolicy.ALLOW; + } + + if (url.contains('/reels/') && + !context + .read() + .isSessionActive) { + setState( + () => _reelsBlockedOverlay = true, + ); + return NavigationActionPolicy.CANCEL; + } + + if (uri != null && + !uri.host.contains('instagram.com') && + !uri.host.contains('facebook.com') && + !uri.host.contains( + 'cdninstagram.com', + ) && + !uri.host.contains('fbcdn.net')) { + await launchUrl( + uri, + mode: LaunchMode.externalApplication, + ); + return NavigationActionPolicy.CANCEL; + } + + final decision = NavigationGuard.evaluate( + url: url, + ); + if (decision.blocked) { + if (url.contains('/reels/')) { + setState( + () => _reelsBlockedOverlay = true, + ); + return NavigationActionPolicy.CANCEL; + } + return NavigationActionPolicy.CANCEL; + } + + return NavigationActionPolicy.ALLOW; + }, + onReceivedError: (controller, request, error) { + // FIX 5: Clear loading state on ANY main-frame + // error, not just HOST_LOOKUP and TIMEOUT. + // Previously, errors like CONNECTION_REFUSED or + // FAILED_URL_BLOCKED left _isLoading = true + // forever, causing the apparent "hang". + if (request.isForMainFrame == true) { + _loadingTimeout?.cancel(); + if (mounted) { + setState(() { + _isLoading = false; + _showSkeleton = false; + // Only show the full error screen for + // network-level failures, not blocked URLs + if (error.type == + WebResourceErrorType + .HOST_LOOKUP || + error.type == + WebResourceErrorType.TIMEOUT) { + _hasError = true; + } + }); + } + } + }, + ), + + if (_showSkeleton) + SkeletonScreen(skeletonType: _skeletonType), + + if (!_isOnOnboardingPage && + settings.minimalModeEnabled && + !_minimalModeBannerDismissed) + Positioned( + left: 12, + right: 12, + top: 12, + child: _MinimalModeBanner( + onDismiss: () { + HapticFeedback.lightImpact(); + setState( + () => _minimalModeBannerDismissed = true, + ); + }, + ), + ), + + // Instagram's native bottom nav is used directly. + // NativeBottomNav overlay removed — faster, looks native, + // and reels tap naturally hits shouldOverrideUrlLoading. + ], + ); + }, + ), + ), + ], + ), + ), + if (_hasError) + _NoInternetScreen( + onRetry: () { + setState(() => _hasError = false); + _controller?.reload(); + }, + ), + if (_isLoading) + Positioned( + top: + (_isOnOnboardingPage ? 0 : 60) + + MediaQuery.of(context).padding.top, + left: 0, + right: 0, + child: const _InstagramGradientProgressBar(), + ), +_EdgePanel(key: _edgePanelKey), + + if (_exploreBlockedOverlay) + Positioned.fill( + child: Consumer( + builder: (ctx, settings, _) { + final isDark = settings.isDarkMode; + final bg = isDark ? Colors.black : Colors.white; + final textMain = isDark ? Colors.white : Colors.black; + final textDim = isDark ? Colors.white70 : Colors.black87; + final textSub = isDark ? Colors.white38 : Colors.black45; + + return Container( + color: bg.withValues(alpha: 0.95), + padding: const EdgeInsets.all(32), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon( + Icons.explore_off_rounded, + color: Colors.orangeAccent, + size: 80, + ), + const SizedBox(height: 24), + Text( + 'Explore is Disabled', + style: GoogleFonts.grandHotel( + color: textMain, + fontSize: 42, + ), + ), + const SizedBox(height: 12), + Text( + 'Explore is disabled in your FocusGram settings.', + textAlign: TextAlign.center, + style: TextStyle( + color: textDim, + fontSize: 15, + height: 1.5, + ), + ), + const SizedBox(height: 48), + Text( + 'You can re-enable Explore in Settings > Focus.', + textAlign: TextAlign.center, + style: TextStyle( + color: textSub, + fontSize: 12, + ), + ), + const SizedBox(height: 20), + TextButton( + onPressed: () { + setState(() => _exploreBlockedOverlay = false); + _controller?.goBack(); + }, + child: Text( + 'Go Back', + style: TextStyle(color: textSub), + ), + ), + ], + ), + ); + }, + ), + ), + + if (_reelsBlockedOverlay) + Positioned.fill( + child: Consumer( + builder: (ctx, settings, _) { + final isDark = settings.isDarkMode; + final bg = isDark ? Colors.black : Colors.white; + final textMain = isDark ? Colors.white : Colors.black; + final textDim = isDark ? Colors.white70 : Colors.black87; + final textSub = isDark ? Colors.white38 : Colors.black45; + + return Container( + color: bg.withValues(alpha: 0.95), + padding: const EdgeInsets.all(32), + child: Consumer( + builder: (ctx, sm, _) { + final onCooldown = sm.isCooldownActive; + final quotaFinished = sm.dailyRemainingSeconds <= 0; + final reelsHardDisabled = + settings.disableReelsEntirely; + + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + quotaFinished + ? Icons.timer_off_rounded + : Icons.lock_clock_rounded, + color: quotaFinished + ? Colors.redAccent + : Colors.blueAccent, + size: 80, + ), + const SizedBox(height: 24), + Text( + quotaFinished + ? 'Daily Quota Finished' + : (reelsHardDisabled + ? 'Reels are Disabled' + : 'Reels are Blocked'), + style: GoogleFonts.grandHotel( + color: textMain, + fontSize: 42, + ), + ), + const SizedBox(height: 12), + Text( + quotaFinished + ? 'You have reached your planned limit for today. Step away and focus on what matters most.' + : (reelsHardDisabled + ? 'Reels are disabled in your settings.' + : 'Start a planned reel session to access the feed. Use Instagram for connection, not distraction.'), + textAlign: TextAlign.center, + style: TextStyle( + color: textDim, + fontSize: 15, + height: 1.5, + ), + ), + const SizedBox(height: 48), + if (quotaFinished) ...[ + Text( + 'Your discipline is your strength.', + style: TextStyle( + color: Colors.greenAccent.withValues( + alpha: 0.8, + ), + fontStyle: FontStyle.italic, + ), + ), + const SizedBox(height: 24), + Text( + 'To adjust your daily limit, go to Settings > Guardrails.', + textAlign: TextAlign.center, + style: TextStyle( + color: textSub, + fontSize: 12, + ), + ), + ] else if (reelsHardDisabled) ...[ + Text( + 'You can re-enable Reels in Settings > Focus.', + textAlign: TextAlign.center, + style: TextStyle( + color: textSub, + fontSize: 12, + ), + ), + ] else if (onCooldown) ...[ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 28, + vertical: 14, + ), + decoration: BoxDecoration( + color: Colors.orange.withValues( + alpha: 0.12, + ), + borderRadius: BorderRadius.circular(30), + border: Border.all( + color: Colors.orange.withValues( + alpha: 0.4, + ), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon( + Icons.hourglass_bottom_rounded, + color: Colors.orangeAccent, + size: 18, + ), + const SizedBox(width: 8), + Text( + 'Cooldown: ${_fmtSeconds(sm.cooldownRemainingSeconds)}', + style: const TextStyle( + color: Colors.orangeAccent, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + const SizedBox(height: 8), + Text( + 'Wait for the cooldown to expire before starting a new session.', + textAlign: TextAlign.center, + style: TextStyle( + color: textSub, + fontSize: 12, + ), + ), + ] else + ElevatedButton( + onPressed: _showReelSessionPicker, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blueAccent, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric( + horizontal: 40, + vertical: 16, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(30), + ), + ), + child: const Text( + 'Start Session', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + ), + const SizedBox(height: 20), + TextButton( + onPressed: () { + setState(() => _reelsBlockedOverlay = false); + _controller?.goBack(); + }, + child: Text( + 'Go Back', + style: TextStyle(color: textSub), + ), + ), + ], + ); + }, + ), + ); + }, + ), + ), + ], + ), + ), + ); + } + + void _registerJavaScriptHandlers(InAppWebViewController controller) { + controller.addJavaScriptHandler( + handlerName: 'FocusGramNotificationChannel', + callback: (args) { + if (!mounted) return null; + final settings = context.read(); + final msg = (args.isNotEmpty ? args[0] : '') as String; + + if (DateTime.now().difference(_lastMainFrameLoadStartedAt).inSeconds < + 6) { + return null; + } + + String title = ''; + String body = ''; + bool isDM = false; + + if (msg.contains(': ')) { + final parts = msg.split(': '); + title = parts[0]; + body = parts.sublist(1).join(': '); + isDM = + title.toLowerCase().contains('message') || + title.toLowerCase().contains('direct'); + } else { + isDM = msg == 'DM'; + title = isDM ? 'Instagram Message' : 'Instagram Notification'; + body = isDM + ? 'Someone messaged you' + : 'New activity in notifications'; + } + + if (isDM && !settings.notifyDMs) return null; + if (!isDM && !settings.notifyActivity) return null; + + try { + NotificationService().showNotification( + // Use hash of message for unique ID - prevents random duplicate notifications + id: (msg.hashCode.abs() % 100000) + 2000, + title: title, + body: body, + ); + } catch (_) {} + return null; + }, + ); + + controller.addJavaScriptHandler( + handlerName: 'FocusGramBlocked', + callback: (args) { + if (!mounted) return null; + final what = (args.isNotEmpty ? args[0] : '') as String? ?? ''; + final text = what == 'reels' + ? 'Reels are disabled' + : (what == 'explore' ? 'Explore is disabled' : 'Content disabled'); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(text), + behavior: SnackBarBehavior.floating, + margin: const EdgeInsets.fromLTRB(16, 0, 16, 20), + ), + ); + return null; + }, + ); + + controller.addJavaScriptHandler( + handlerName: 'FocusGramShareChannel', + callback: (args) { + if (!mounted) return; + try { + final data = (args.isNotEmpty ? args[0] : '') as String; + String url = data; + try { + final match = RegExp(r'"url":"([^"]+)"').firstMatch(data); + if (match != null) url = match.group(1) ?? data; + } catch (_) {} + Clipboard.setData(ClipboardData(text: url)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Link copied (tracking removed)'), + backgroundColor: Color(0xFF1A1A2E), + behavior: SnackBarBehavior.floating, + margin: EdgeInsets.fromLTRB(16, 0, 16, 20), + ), + ); + } catch (_) {} + }, + ); + + controller.addJavaScriptHandler( + handlerName: 'FocusGramThemeChannel', + callback: (args) { + final value = (args.isNotEmpty ? args[0] : '') as String; + context.read().setDarkMode(value == 'dark'); + }, + ); + + controller.addJavaScriptHandler( + handlerName: 'Haptic', + callback: (args) { + HapticFeedback.lightImpact(); + return null; + }, + ); + + controller.addJavaScriptHandler( + handlerName: 'UrlChange', + callback: (args) async { + final url = (args.isNotEmpty ? args[0] : '') as String? ?? ''; + await _injectionManager?.runAllPostLoadInjections(url); + if (!mounted) return; + setState(() { + _currentUrl = url; + // SPA navigations never fire onLoadStop — clear skeleton here + // so it doesn't stay visible forever (e.g. when navigating to DMs) + _showSkeleton = false; + _isLoading = false; + }); + + final settings = context.read(); + final disableReels = settings.disableReelsEntirely; + final disableExplore = settings.disableExploreEntirely; + + final path = Uri.tryParse(url)?.path ?? url; + final isReels = path.startsWith('/reels') || path.startsWith('/reel/'); + final isExplore = path.startsWith('/explore'); + + // Block reel navigation that slipped through (e.g. DM-embedded reels) + if (disableReels && isReels) { + setState(() => _reelsBlockedOverlay = true); + await _controller?.goBack(); + return; + } + + if (_controller != null) { + if (disableExplore && isExplore) { + await _controller!.loadUrl( + urlRequest: URLRequest(url: WebUri('https://www.instagram.com/')), + ); + } + } + + // Update isolated player flag for DM-embedded reels + final isIsolatedReel = + path.contains('/reel/') && !path.startsWith('/reels'); + await _setIsolatedPlayer(isIsolatedReel); + + return null; + }, + ); + } +} + +// ─── Supporting widgets (unchanged) ────────────────────────────────────────── + +class _MinimalModeBanner extends StatelessWidget { + final VoidCallback onDismiss; + + const _MinimalModeBanner({required this.onDismiss}); + + @override + Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Material( + color: Colors.transparent, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + decoration: BoxDecoration( + color: (isDark ? Colors.black : Colors.white).withValues(alpha: 0.92), + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: isDark ? Colors.white12 : Colors.black12, + width: 0.5, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: isDark ? 0.35 : 0.12), + blurRadius: 18, + spreadRadius: 2, + ), + ], + ), + child: Row( + children: [ + Expanded( + child: Text( + 'Minimal mode — Feed & DMs only 🎯', + style: TextStyle( + color: isDark ? Colors.white : Colors.black, + fontWeight: FontWeight.w600, + fontSize: 13, + ), + ), + ), + InkWell( + onTap: onDismiss, + borderRadius: BorderRadius.circular(20), + child: Padding( + padding: const EdgeInsets.all(4), + child: Icon( + Icons.close, + size: 18, + color: isDark ? Colors.white70 : Colors.black54, + ), + ), + ), + ], + ), + ), + ); + } +} + +class _EdgePanel extends StatefulWidget { + const _EdgePanel({super.key}); + @override + State<_EdgePanel> createState() => _EdgePanelState(); +} + +class _EdgePanelState extends State<_EdgePanel> { + bool _isExpanded = false; + void _toggleExpansion() => setState(() => _isExpanded = !_isExpanded); + + @override + Widget build(BuildContext context) { + final sm = context.watch(); + final int remaining = sm.remainingSessionSeconds; + final double progress = sm.perSessionSeconds > 0 + ? (remaining / sm.perSessionSeconds).clamp(0.0, 1.0) + : 0; + Color barColor = progress < 0.2 + ? Colors.redAccent + : (progress < 0.5 ? Colors.yellowAccent : Colors.blueAccent); + + final settings = context.watch(); + final isDark = settings.isDarkMode; + final reelsHardDisabled = + settings.disableReelsEntirely; + final panelBg = isDark ? const Color(0xFF121212) : Colors.white; + final textDim = isDark ? Colors.white70 : Colors.black87; + final textSub = isDark ? Colors.white30 : Colors.black38; + final border = isDark ? Colors.white12 : Colors.black12; + + return Stack( + children: [ + if (_isExpanded) + Positioned.fill( + child: GestureDetector( + onTap: _toggleExpansion, + behavior: HitTestBehavior.opaque, + child: Container( + color: Colors.black.withValues(alpha: isDark ? 0.15 : 0.05), + ), + ), + ), + AnimatedPositioned( + duration: const Duration(milliseconds: 350), + curve: Curves.easeOutQuart, + left: _isExpanded ? 0 : -220, + top: MediaQuery.of(context).size.height * 0.25 + 30, + child: Container( + width: 210, + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: panelBg.withValues(alpha: 0.98), + borderRadius: const BorderRadius.only( + topRight: Radius.circular(28), + bottomRight: Radius.circular(28), + ), + border: Border.all(color: border, width: 0.5), + boxShadow: [ + BoxShadow( + color: (isDark ? Colors.black : Colors.black12).withValues( + alpha: 0.3, + ), + blurRadius: 30, + spreadRadius: 5, + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'FOCUS CONTROL', + style: TextStyle( + color: Colors.blueAccent, + fontSize: 10, + fontWeight: FontWeight.bold, + letterSpacing: 1.5, + ), + ), + IconButton( + icon: Icon( + Icons.chevron_left_rounded, + color: textDim, + size: 28, + ), + onPressed: _toggleExpansion, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + ), + ], + ), + const SizedBox(height: 32), + Text( + 'REEL SESSION', + style: TextStyle( + color: textSub, + fontSize: 11, + letterSpacing: 1, + ), + ), + const SizedBox(height: 8), + Text( + sm.isSessionActive + ? _formatTime(sm.remainingSessionSeconds) + : 'Off', + style: TextStyle( + color: barColor, + fontSize: 40, + fontWeight: FontWeight.w200, + letterSpacing: 2, + ), + ), + const SizedBox(height: 20), + _buildStatRow( + 'REEL QUOTA', + '${sm.dailyRemainingSeconds ~/ 60}m Left', + Icons.timer_outlined, + isDark: isDark, + ), + _buildStatRow( + 'AUTO-CLOSE', + _formatTime(sm.appSessionRemainingSeconds), + Icons.hourglass_empty_rounded, + isDark: isDark, + ), + _buildStatRow( + 'COOLDOWN', + sm.isCooldownActive + ? _formatTime(sm.cooldownRemainingSeconds) + : 'Off', + Icons.coffee_rounded, + isWarning: sm.isCooldownActive, + isDark: isDark, + ), + if (!reelsHardDisabled && + !sm.isSessionActive && + sm.dailyRemainingSeconds > 0) ...[ + const SizedBox(height: 12), + SizedBox( + width: double.infinity, + child: ElevatedButton( + onPressed: () { + context + .findAncestorStateOfType<_MainWebViewPageState>() + ?._showReelSessionPicker(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blueAccent, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(vertical: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + child: const Text( + 'Start Session', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ] else if (reelsHardDisabled) ...[ + const SizedBox(height: 10), + Text( + 'Reels disabled in settings', + style: TextStyle(color: textSub, fontSize: 11), + ), + ], + const SizedBox(height: 32), + Divider(color: isDark ? Colors.white10 : Colors.black12), + const SizedBox(height: 8), + ListTile( + onTap: () { + _toggleExpansion(); + context + .findAncestorStateOfType<_MainWebViewPageState>() + ?._signOut(); + }, + leading: const Icon( + Icons.logout_rounded, + color: Colors.redAccent, + size: 20, + ), + title: const Text( + 'Switch Account', + style: TextStyle( + color: Colors.redAccent, + fontSize: 13, + fontWeight: FontWeight.bold, + ), + ), + dense: true, + contentPadding: EdgeInsets.zero, + ), + ], + ), + ), + ), + ], + ); + } + + Widget _buildStatRow( + String label, + String value, + IconData icon, { + bool isWarning = false, + bool isDark = true, + }) { + final textMain = isDark ? Colors.white : Colors.black; + final textSub = isDark ? Colors.white38 : Colors.black38; + return Padding( + padding: const EdgeInsets.only(bottom: 20), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: isWarning + ? Colors.redAccent.withValues(alpha: 0.1) + : (isDark ? Colors.white : Colors.black).withValues( + alpha: 0.05, + ), + borderRadius: BorderRadius.circular(10), + ), + child: Icon( + icon, + color: isWarning + ? Colors.redAccent + : (isDark ? Colors.white70 : Colors.black54), + size: 16, + ), + ), + const SizedBox(width: 16), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: TextStyle( + color: textSub, + fontSize: 9, + fontWeight: FontWeight.bold, + letterSpacing: 1, + ), + ), + const SizedBox(height: 2), + Text( + value, + style: TextStyle( + color: isWarning ? Colors.redAccent : textMain, + fontSize: 18, + fontWeight: FontWeight.w600, + fontFeatures: const [FontFeature.tabularFigures()], + ), + ), + ], + ), + ], + ), + ); + } + + String _formatTime(int seconds) { + final m = seconds ~/ 60; + final s = seconds % 60; + return '${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}'; + } +} + +class _BrandedTopBar extends StatelessWidget { + final VoidCallback? onFocusControlTap; + const _BrandedTopBar({this.onFocusControlTap}); + @override + Widget build(BuildContext context) { + final isDark = context.watch().isDarkMode; + final barBg = isDark ? Colors.black : Colors.white; + final textMain = isDark ? Colors.white : Colors.black; + final iconColor = isDark ? Colors.white70 : Colors.black54; + final border = isDark ? Colors.white12 : Colors.black12; + + return Container( + height: 60, + decoration: BoxDecoration( + color: barBg, + border: Border(bottom: BorderSide(color: border, width: 0.5)), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + IconButton( + icon: Icon(Icons.settings_outlined, color: iconColor, size: 22), + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const SettingsPage()), + ), + ), + Text( + 'FocusGram', + style: GoogleFonts.grandHotel( + color: textMain, + fontSize: 32, + letterSpacing: 0.5, + ), + ), + IconButton( + icon: const Icon( + Icons.timer_outlined, + color: Colors.blueAccent, + size: 22, + ), + onPressed: onFocusControlTap, + ), + ], + ), + ), + ); + } +} + +class _InstagramGradientProgressBar extends StatelessWidget { + const _InstagramGradientProgressBar(); + @override + Widget build(BuildContext context) { + return SizedBox( + height: 2.5, + child: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + colors: [ + Color(0xFFFEDA75), + Color(0xFFFA7E1E), + Color(0xFFD62976), + Color(0xFF962FBF), + Color(0xFF4F5BD5), + ], + begin: Alignment.centerLeft, + end: Alignment.centerRight, + ), + ), + ), + ); + } +} + +class _UpdateBanner extends StatelessWidget { + const _UpdateBanner(); + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, update, _) { + if (!update.hasUpdate) return const SizedBox.shrink(); + + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [Colors.blue.shade700, Colors.blue.shade900], + ), + ), + child: Row( + children: [ + const Icon( + Icons.system_update_alt, + color: Colors.white, + size: 18, + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Update Available: ${update.updateInfo?.latestVersion ?? ''}', + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.bold, + fontSize: 13, + ), + ), + const SizedBox(height: 2), + InkWell( + onTap: () { + final url = update.updateInfo?.releaseUrl; + if (url != null && url.isNotEmpty) { + launchUrl( + Uri.parse(url), + mode: LaunchMode.externalApplication, + ); + } + }, + child: const Text( + 'Download on GitHub →', + style: TextStyle( + color: Colors.white70, + fontSize: 12, + decoration: TextDecoration.underline, + ), + ), + ), + ], + ), + ), + IconButton( + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + onPressed: () => update.dismissUpdate(), + icon: const Icon(Icons.close, color: Colors.white70, size: 18), + ), + ], + ), + ); + }, + ); + } +} + +class _NoInternetScreen extends StatelessWidget { + final VoidCallback onRetry; + const _NoInternetScreen({required this.onRetry}); + @override + Widget build(BuildContext context) { + final isDark = context.watch().isDarkMode; + return Container( + color: isDark ? Colors.black : Colors.white, + width: double.infinity, + height: double.infinity, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.wifi_off_rounded, + color: isDark ? Colors.white24 : Colors.black12, + size: 80, + ), + const SizedBox(height: 24), + Text( + 'No Connection', + style: TextStyle( + color: isDark ? Colors.white : Colors.black, + fontSize: 20, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Text( + 'Please check your internet settings.', + style: TextStyle( + color: isDark ? Colors.white38 : Colors.black38, + fontSize: 14, + ), + ), + const SizedBox(height: 40), + ElevatedButton( + onPressed: onRetry, + style: ElevatedButton.styleFrom( + backgroundColor: isDark ? Colors.white : Colors.black, + foregroundColor: isDark ? Colors.black : Colors.white, + padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + ), + child: const Text('Retry'), + ), + ], + ), + ); + } +} diff --git a/lib/screens/onboarding_page.dart b/lib/screens/onboarding_page.dart new file mode 100644 index 0000000..7eb495d --- /dev/null +++ b/lib/screens/onboarding_page.dart @@ -0,0 +1,398 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:app_settings/app_settings.dart'; +import '../services/settings_service.dart'; +import '../services/notification_service.dart'; + +class OnboardingPage extends StatefulWidget { + final VoidCallback onFinish; + + const OnboardingPage({super.key, required this.onFinish}); + + @override + State createState() => _OnboardingPageState(); +} + +class _OnboardingPageState extends State { + final PageController _pageController = PageController(); + int _currentPage = 0; + + // Pages: Welcome, Session Management, Link Handling, Blur Settings, Notifications + static const int _kTotalPages = 5; + + static const int _kBlurPage = 3; + static const int _kLinkPage = 2; + static const int _kNotifPage = 4; + + @override + Widget build(BuildContext context) { + final settings = context.watch(); + + final List slides = [ + // ── Page 0: Welcome ───────────────────────────────────────────────── + _StaticSlide( + icon: Icons.auto_awesome, + color: Colors.blue, + title: 'Welcome to FocusGram', + description: + 'The distraction-free way to use Instagram. We help you stay focused by blocking Reels and Explore content.', + ), + + // ── Page 1: Session Management ─────────────────────────────────────── + _StaticSlide( + icon: Icons.timer, + color: Colors.orange, + title: 'Session Management', + description: + 'Plan your usage. Set daily limits and use timed sessions to stay in control of your time.', + ), + + // ── Page 2: Open links ─────────────────────────────────────────────── + _StaticSlide( + icon: Icons.link, + color: Colors.cyan, + title: 'Open Links in FocusGram', + description: + 'To open Instagram links directly here: Tap "Configure", then "Open by default" → "Add link" and select all.', + isAppSettingsPage: true, + ), + + // ── Page 3: Blur Settings ──────────────────────────────────────────── + _BlurSettingsSlide(settings: settings), + + // ── Page 4: Notifications ──────────────────────────────────────────── + _StaticSlide( + icon: Icons.notifications_active, + color: Colors.green, + title: 'Stay Notified', + description: + 'We need notification permissions to alert you when your session is over or a new message arrives.', + isPermissionPage: true, + permission: Permission.notification, + ), + ]; + + return Scaffold( + backgroundColor: Colors.black, + body: Stack( + children: [ + PageView.builder( + controller: _pageController, + onPageChanged: (index) => setState(() => _currentPage = index), + itemCount: _kTotalPages, + itemBuilder: (context, index) => slides[index], + ), + Positioned( + bottom: 50, + left: 0, + right: 0, + child: Column( + children: [ + // Dot indicators + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate( + _kTotalPages, + (index) => AnimatedContainer( + duration: const Duration(milliseconds: 250), + margin: const EdgeInsets.symmetric(horizontal: 4), + width: _currentPage == index ? 12 : 8, + height: 8, + decoration: BoxDecoration( + color: _currentPage == index + ? Colors.blue + : Colors.white24, + borderRadius: BorderRadius.circular(4), + ), + ), + ), + ), + const SizedBox(height: 32), + // CTA button + Padding( + padding: const EdgeInsets.symmetric(horizontal: 32), + child: SizedBox( + width: double.infinity, + height: 56, + child: Builder( + builder: (context) { + final isLast = _currentPage == _kTotalPages - 1; + final isLink = _currentPage == _kLinkPage; + final isNotif = _currentPage == _kNotifPage; + final isBlur = _currentPage == _kBlurPage; + + String label; + if (isLast) { + label = 'Get Started'; + } else if (isLink) { + label = 'Configure'; + } else if (isNotif) { + label = 'Allow Notifications'; + } else if (isBlur) { + label = 'Save & Continue'; + } else { + label = 'Next'; + } + + return ElevatedButton( + onPressed: () async { + if (isLink) { + await AppSettings.openAppSettings( + type: AppSettingsType.settings, + ); + } else if (isNotif) { + await Permission.notification.request(); + await NotificationService().init(); + } + + if (!context.mounted) return; + if (isLast) { + _finish(context); + } else { + _pageController.nextPage( + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + ); + } + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + ), + child: Text( + label, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + ); + }, + ), + ), + ), + // Skip button (available on all pages except last) + if (_currentPage < _kTotalPages - 1) + TextButton( + onPressed: () => _finish(context), + child: const Text( + 'Skip', + style: TextStyle(color: Colors.white38, fontSize: 14), + ), + ), + ], + ), + ), + ], + ), + ); + } + + void _finish(BuildContext context) { + context.read().setFirstRunCompleted(); + widget.onFinish(); + } +} + +// ── Static info slide ────────────────────────────────────────────────────────── + +class _StaticSlide extends StatelessWidget { + final IconData icon; + final Color color; + final String title; + final String description; + final bool isPermissionPage; + final bool isAppSettingsPage; + final Permission? permission; + + const _StaticSlide({ + required this.icon, + required this.color, + required this.title, + required this.description, + this.isPermissionPage = false, + this.isAppSettingsPage = false, + this.permission, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(40, 40, 40, 160), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, size: 120, color: color), + const SizedBox(height: 48), + Text( + title, + textAlign: TextAlign.center, + style: const TextStyle( + color: Colors.white, + fontSize: 32, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 16), + Text( + description, + textAlign: TextAlign.center, + style: const TextStyle( + color: Colors.white70, + fontSize: 18, + height: 1.5, + ), + ), + ], + ), + ); + } +} + +// ── Blur settings slide ──────────────────────────────────────────────────────── + +class _BlurSettingsSlide extends StatelessWidget { + final SettingsService settings; + + const _BlurSettingsSlide({required this.settings}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(32, 40, 32, 160), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header + Center( + child: Icon( + Icons.blur_on_rounded, + size: 90, + color: Colors.purpleAccent, + ), + ), + const SizedBox(height: 36), + const Center( + child: Text( + 'Distraction Shield', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontSize: 30, + fontWeight: FontWeight.bold, + ), + ), + ), + const SizedBox(height: 12), + const Center( + child: Text( + 'Blur feeds you don\'t want to be tempted by. You can change these anytime in Settings.', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white60, + fontSize: 16, + height: 1.5, + ), + ), + ), + const SizedBox(height: 40), + + // Blur Home Feed toggle + _BlurToggleTile( + icon: Icons.home_rounded, + label: 'Blur Home Feed', + subtitle: 'Posts in your feed will be blurred until tapped', + value: settings.blurReels, + onChanged: (v) => settings.setBlurReels(v), + ), + const SizedBox(height: 16), + + // Blur Explore toggle + _BlurToggleTile( + icon: Icons.explore_rounded, + label: 'Blur Explore Feed', + subtitle: 'Explore thumbnails stay blurred until you tap', + value: settings.blurExplore, + onChanged: (v) => settings.setBlurExplore(v), + ), + ], + ), + ); + } +} + +class _BlurToggleTile extends StatelessWidget { + final IconData icon; + final String label; + final String subtitle; + final bool value; + final ValueChanged onChanged; + + const _BlurToggleTile({ + required this.icon, + required this.label, + required this.subtitle, + required this.value, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + decoration: BoxDecoration( + color: value + ? Colors.purpleAccent.withValues(alpha: 0.12) + : Colors.white.withValues(alpha: 0.06), + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: value + ? Colors.purpleAccent.withValues(alpha: 0.5) + : Colors.white.withValues(alpha: 0.1), + width: 1, + ), + ), + child: Row( + children: [ + Icon( + icon, + color: value ? Colors.purpleAccent : Colors.white38, + size: 28, + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: TextStyle( + color: value ? Colors.white : Colors.white70, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 2), + Text( + subtitle, + style: const TextStyle(color: Colors.white38, fontSize: 12), + ), + ], + ), + ), + Switch( + value: value, + onChanged: onChanged, + activeThumbColor: Colors.purpleAccent, + ), + ], + ), + ); + } +} diff --git a/lib/screens/reel_player_overlay.dart b/lib/screens/reel_player_overlay.dart new file mode 100644 index 0000000..1dcc789 --- /dev/null +++ b/lib/screens/reel_player_overlay.dart @@ -0,0 +1,133 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; +import '../services/injection_controller.dart'; +import '../services/session_manager.dart'; +import 'package:provider/provider.dart'; + +/// An isolated player for a single Reel opened from a DM. +/// Uses JS history interception to lock the user to the initial reel URL. +class ReelPlayerOverlay extends StatefulWidget { + final String url; + const ReelPlayerOverlay({super.key, required this.url}); + + @override + State createState() => _ReelPlayerOverlayState(); +} + +class _ReelPlayerOverlayState extends State { + DateTime? _startTime; + + @override + void initState() { + super.initState(); + _startTime = DateTime.now(); + } + + @override + void dispose() { + // Record viewing time toward daily count + if (_startTime != null) { + final durationSeconds = DateTime.now().difference(_startTime!).inSeconds; + if (mounted) { + context.read().accrueSeconds(durationSeconds); + } + } + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.black, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white), + onPressed: () => Navigator.pop(context), + ), + title: const Text( + 'Reel', + style: TextStyle(color: Colors.white, fontSize: 16), + ), + actions: [ + Padding( + padding: const EdgeInsets.only(right: 12), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: Colors.orange.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.orangeAccent, width: 0.5), + ), + child: const Text( + 'Locked', + style: TextStyle(color: Colors.orangeAccent, fontSize: 11), + ), + ), + ), + ], + ), + body: InAppWebView( + initialUrlRequest: URLRequest(url: WebUri(widget.url)), + initialSettings: InAppWebViewSettings( + userAgent: InjectionController.iOSUserAgent, + mediaPlaybackRequiresUserGesture: true, + useHybridComposition: true, + cacheEnabled: true, + cacheMode: CacheMode.LOAD_CACHE_ELSE_NETWORK, + domStorageEnabled: true, + databaseEnabled: true, + hardwareAcceleration: true, + transparentBackground: true, + safeBrowsingEnabled: false, + supportZoom: false, + allowsInlineMediaPlayback: true, + verticalScrollBarEnabled: false, + horizontalScrollBarEnabled: false, + ), + onWebViewCreated: (controller) { + // Controller is not stored; this overlay is self-contained. + }, + onLoadStop: (controller, url) async { + // Set isolated player flag to ensure scroll-lock applies even if a session is active globally + await controller.evaluateJavascript( + source: 'window.__focusgramIsolatedPlayer = true;', + ); + // Apply scroll-lock via MutationObserver: prevents swiping to next reel + await controller.evaluateJavascript( + source: InjectionController.reelsMutationObserverJS, + ); + // Also apply FocusGram baseline CSS (hides bottom nav etc.) + await controller.evaluateJavascript( + source: InjectionController.buildInjectionJS( + sessionActive: true, + blurExplore: false, + blurReels: false, + tapToUnblur: false, + enableTextSelection: true, + hideSuggestedPosts: false, + hideSponsoredPosts: false, + hideLikeCounts: false, + hideFollowerCounts: false, + // hideStoriesBar removed per user request + hideExploreTab: false, + hideReelsTab: false, + hideShopTab: false, + disableReelsEntirely: false, + ), + ); + }, + shouldOverrideUrlLoading: (controller, action) async { + // Keep this overlay locked to instagram.com pages only + final uri = action.request.url; + if (uri == null) return NavigationActionPolicy.CANCEL; + if (!uri.host.contains('instagram.com')) { + return NavigationActionPolicy.CANCEL; + } + return NavigationActionPolicy.ALLOW; + }, + ), + ); + } +} diff --git a/lib/screens/session_modal.dart b/lib/screens/session_modal.dart new file mode 100644 index 0000000..25e9aa8 --- /dev/null +++ b/lib/screens/session_modal.dart @@ -0,0 +1,138 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../services/session_manager.dart'; +import '../utils/discipline_challenge.dart'; + +class SessionModal extends StatefulWidget { + const SessionModal({super.key}); + + @override + State createState() => _SessionModalState(); +} + +class _SessionModalState extends State { + double _customMinutes = 5.0; + + @override + Widget build(BuildContext context) { + final sm = context.watch(); + + return Container( + padding: const EdgeInsets.all(24), + decoration: const BoxDecoration( + color: Color(0xFF121212), + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Start Reel Session', + style: TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold, + ), + ), + IconButton( + onPressed: () => Navigator.pop(context), + icon: const Icon(Icons.close, color: Colors.white54), + ), + ], + ), + const SizedBox(height: 8), + Text( + 'Remaining Daily: ${sm.dailyRemainingSeconds ~/ 60}m', + style: const TextStyle(color: Colors.white70), + ), + if (sm.isCooldownActive) + Padding( + padding: const EdgeInsets.only(top: 8.0), + child: Text( + 'Cooldown active: ${sm.cooldownRemainingSeconds ~/ 60}m ${sm.cooldownRemainingSeconds % 60}s left', + style: const TextStyle(color: Colors.orangeAccent), + ), + ), + const SizedBox(height: 24), + const Text( + 'Presets', + style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600), + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [1, 5, 10, 15].map((m) { + return Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4.0), + child: ElevatedButton( + onPressed: (sm.isCooldownActive || sm.isDailyLimitExhausted) + ? null + : () => _start(m), + style: ElevatedButton.styleFrom( + backgroundColor: Colors.white12, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(vertical: 12), + ), + child: Text('${m}m'), + ), + ), + ); + }).toList(), + ), + const SizedBox(height: 32), + const Text( + 'Custom Duration', + style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600), + ), + Slider( + value: _customMinutes, + min: 1, + max: 30, + divisions: 29, + label: '${_customMinutes.toInt()}m', + onChanged: (v) => setState(() => _customMinutes = v), + ), + const SizedBox(height: 24), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: (sm.isCooldownActive || sm.isDailyLimitExhausted) + ? null + : () => _start(_customMinutes.toInt()), + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blue, + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + child: const Text( + 'Start Session', + style: TextStyle(fontSize: 16), + ), + ), + ), + const SizedBox(height: 16), + ], + ), + ); + } + + void _start(int minutes) async { + final sm = context.read(); + + // Always require word challenge for reel sessions (User request) + final success = await DisciplineChallenge.show(context); + if (!success) return; + + if (sm.startSession(minutes)) { + if (mounted) Navigator.pop(context); + } + } +} diff --git a/lib/screens/settings_page.dart b/lib/screens/settings_page.dart new file mode 100644 index 0000000..fe77f14 --- /dev/null +++ b/lib/screens/settings_page.dart @@ -0,0 +1,1004 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:url_launcher/url_launcher.dart'; +import '../services/session_manager.dart'; +import '../services/settings_service.dart'; +import '../services/focusgram_router.dart'; +import '../features/screen_time/screen_time_screen.dart'; +import 'guardrails_page.dart'; + +// ─── Main Settings Page ─────────────────────────────────────────────────────── + +class SettingsPage extends StatelessWidget { + const SettingsPage({super.key}); + + @override + Widget build(BuildContext context) { + final sm = context.watch(); + final settings = context.watch(); + final isDark = settings.isDarkMode; + + return Scaffold( + appBar: AppBar( + title: const Text( + 'Settings', + style: TextStyle(fontSize: 17, fontWeight: FontWeight.w600), + ), + centerTitle: true, + leading: IconButton( + icon: const Icon(Icons.arrow_back_ios_new, size: 18), + onPressed: () => Navigator.pop(context), + ), + ), + body: ListView( + children: [ + _buildStatsRow(sm), + + const _SectionHeader(title: 'FOCUS & BLOCKING'), + _SubmoduleTile( + icon: Icons.block_rounded, + iconColor: Colors.redAccent, + title: 'Focus Mode', + subtitle: settings.minimalModeEnabled + ? 'Minimal mode on' + : 'Blocking, friction, media', + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const FocusSettingsPage()), + ), + ), + _SubmoduleTile( + icon: Icons.timer_outlined, + iconColor: Colors.blueAccent, + title: 'Time Control & Guardrails', + subtitle: 'Daily limit, cooldown, scheduled blocking', + enabled: + !(settings.disableReelsEntirely || settings.minimalModeEnabled), + disabledSubtitle: 'Reels are fully disabled', + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const GuardrailsPage()), + ), + ), + + const _SectionHeader(title: 'APPEARANCE'), + _SubmoduleTile( + icon: Icons.palette_outlined, + iconColor: Colors.purpleAccent, + title: 'Appearance', + subtitle: settings.grayscaleEnabled + ? 'Grayscale on' + : settings.grayscaleSchedules.isNotEmpty + ? 'Grayscale scheduled (${settings.grayscaleSchedules.length} schedules)' + : 'Theme, grayscale', + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const AppearancePage()), + ), + ), + + const _SectionHeader(title: 'PRIVACY & NOTIFICATIONS'), + _SubmoduleTile( + icon: Icons.lock_outline, + iconColor: Colors.tealAccent, + title: 'Privacy & Notifications', + subtitle: 'Session end alerts', + onTap: () => Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const PrivacyNotificationsPage(), + ), + ), + ), + + const _SectionHeader(title: 'STATS & HISTORY'), + _SubmoduleTile( + icon: Icons.bar_chart_rounded, + iconColor: Colors.greenAccent, + title: 'Screen Time Dashboard', + subtitle: 'Daily & weekly usage', + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const ScreenTimeScreen()), + ), + ), + + const _SectionHeader(title: 'ABOUT'), + FutureBuilder( + future: PackageInfo.fromPlatform(), + builder: (context, snapshot) => ListTile( + title: const Text('Version'), + trailing: Text( + snapshot.data?.version ?? '…', + style: const TextStyle(color: Colors.grey), + ), + ), + ), + ListTile( + title: const Text('GitHub'), + trailing: const Icon(Icons.open_in_new, size: 14), + onTap: () => launchUrl( + Uri.parse('https://github.com/Ujwal223/FocusGram'), + mode: LaunchMode.externalApplication, + ), + ), + ListTile( + title: const Text('Legal Disclaimer'), + trailing: const Icon(Icons.info_outline, size: 14), + onTap: () => _showLegalDisclaimer(context), + ), + ListTile( + title: const Text('Open Source Licenses'), + trailing: const Icon(Icons.arrow_forward_ios, size: 14), + onTap: () => showLicensePage(context: context), + ), + + const Divider(height: 40, indent: 16, endIndent: 16), + ListTile( + leading: const Icon( + Icons.settings_outlined, + color: Colors.purpleAccent, + ), + title: const Text('Instagram Settings'), + subtitle: const Text( + 'Open native Instagram account settings', + style: TextStyle(fontSize: 12), + ), + trailing: const Icon( + Icons.open_in_new, + color: Colors.white24, + size: 14, + ), + onTap: () { + Navigator.pop(context); + FocusGramRouter.pendingUrl.value = + 'https://www.instagram.com/accounts/settings/?entrypoint=profile'; + }, + ), + const SizedBox(height: 40), + Center( + child: Text( + 'FocusGram · Built with 💖 by Ujwal Chapagain', + style: TextStyle( + color: isDark ? Colors.white12 : Colors.black12, + fontSize: 12, + ), + ), + ), + const SizedBox(height: 24), + ], + ), + ); + } + + Widget _buildStatsRow(SessionManager sm) { + return Container( + margin: const EdgeInsets.fromLTRB(16, 20, 16, 4), + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.05), + borderRadius: BorderRadius.circular(14), + border: Border.all(color: Colors.blue.withValues(alpha: 0.1)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + _statCell('Opens Today', '${sm.dailyOpenCount}×', Colors.blue), + _dividerCell(), + _statCell( + 'Reels Used', + '${sm.dailyUsedSeconds ~/ 60}m', + Colors.orangeAccent, + ), + _dividerCell(), + _statCell( + 'Remaining', + '${sm.dailyRemainingSeconds ~/ 60}m', + Colors.greenAccent, + ), + ], + ), + ); + } + + Widget _statCell(String label, String value, Color color) => Column( + children: [ + Text( + value, + style: TextStyle( + color: color, + fontSize: 22, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 4), + Text(label, style: const TextStyle(color: Colors.grey, fontSize: 11)), + ], + ); + + Widget _dividerCell() => Container( + width: 1, + height: 36, + color: Colors.blue.withValues(alpha: 0.1), + ); + + void _showLegalDisclaimer(BuildContext context) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Legal Disclaimer'), + content: const SingleChildScrollView( + child: Text( + 'FocusGram is an independent, free, and open-source productivity tool ' + 'licensed under AGPL-3.0. Not affiliated with Meta or Instagram.\n\n' + 'How it works: FocusGram embeds a standard Android System WebView that loads instagram.com. \n' + 'All user-facing features are implemented exclusively via client-side modifications and are never transmitted to or processed by Meta servers.\n\n' + 'All features are client-side only. We do not use private APIs, ' + 'intercept credentials, scrape, harvest or collect any user data.', + style: TextStyle(fontSize: 13, height: 1.4), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close'), + ), + ], + ), + ); + } +} + +// ─── Focus Settings ─────────────────────────────────────────────────────────── + +class FocusSettingsPage extends StatelessWidget { + const FocusSettingsPage({super.key}); + + @override + Widget build(BuildContext context) { + final settings = context.watch(); + return Scaffold( + appBar: _subAppBar(context, 'Focus Mode'), + body: ListView( + children: [ + const _SectionHeader(title: 'BLOCKING'), + Container( + margin: const EdgeInsets.fromLTRB(16, 0, 16, 8), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.07), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Colors.blue.withValues(alpha: 0.12)), + ), + child: const Row( + children: [ + Icon(Icons.info_outline, size: 14, color: Colors.blueAccent), + SizedBox(width: 8), + Expanded( + child: Text( + 'Blocking changes apply immediately. The page reloads automatically in the background.', + style: TextStyle(fontSize: 11, color: Colors.blueAccent), + ), + ), + ], + ), + ), + ListTile( + leading: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.redAccent.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(10), + ), + child: const Icon(Icons.shield_rounded, color: Colors.redAccent, size: 20), + ), + title: const Text('Minimal Mode', style: TextStyle(fontSize: 15)), + subtitle: Text( + settings.minimalModeEnabled ? 'Enabled - tap to customize' : 'Disabled - tap to configure', + style: TextStyle(fontSize: 12, color: settings.minimalModeEnabled ? Colors.greenAccent : Colors.grey), + ), + trailing: Switch( + value: settings.minimalModeEnabled, + onChanged: (v) async { + await settings.setMinimalModeEnabled(v); + HapticFeedback.selectionClick(); + }, + ), + onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const MinimalModeSubmenuPage())), + ), + + const _SectionHeader(title: 'FRICTION'), + _SwitchTile( + title: 'Mindfulness Gate', + subtitle: 'Breath screen before opening Instagram', + value: settings.showBreathGate, + onChanged: (v) => settings.setShowBreathGate(v), + ), + _SwitchTile( + title: 'Strict Mode (Word Challenge)', + subtitle: 'Must type a phrase before starting a Reel session', + value: settings.requireWordChallenge, + onChanged: (v) => settings.setRequireWordChallenge(v), + ), + const _SectionHeader(title: 'MEDIA'), + _SwitchTile( + title: 'Block Autoplay Videos', + subtitle: 'Videos won\'t play until you tap them', + value: settings.blockAutoplay, + onChanged: (v) => settings.setBlockAutoplay(v), + ), + _SwitchTile( + title: 'Blur Feed & Explore', + subtitle: 'Blurs post thumbnails until tapped', + value: settings.blurExplore, + onChanged: (v) => settings.setBlurExplore(v), + ), + // Tap to Unblur as child toggle (shown directly under Blur Feed when enabled) + if (settings.blurExplore) + Padding( + padding: const EdgeInsets.only(left: 32), + child: _SwitchTile( + title: 'Tap to Unblur', + subtitle: 'First tap reveals the post (doesn\'t open it)', + value: settings.tapToUnblur, + onChanged: (v) => settings.setTapToUnblur(v), + ), + ), + + const SizedBox(height: 40), + ], + ), + ); + } +} + +// ─── Minimal Mode Submenu ───────────────────────────────────────────────────── + +class MinimalModeSubmenuPage extends StatefulWidget { + const MinimalModeSubmenuPage({super.key}); + + @override + State createState() => _MinimalModeSubmenuPageState(); +} + +class _MinimalModeSubmenuPageState extends State { + late bool _blurExplore; + late bool _disableReelsEntirely; + late bool _disableExploreEntirely; + + @override + void initState() { + super.initState(); + final settings = context.read(); + _blurExplore = settings.blurExplore; + _disableReelsEntirely = settings.disableReelsEntirely; + _disableExploreEntirely = settings.disableExploreEntirely; + } + + void _updateSetting(String key, bool value) { + final settings = context.read(); + setState(() { + switch (key) { + case 'blurExplore': + _blurExplore = value; + settings.setBlurExplore(value); + break; + case 'disableReelsEntirely': + _disableReelsEntirely = value; + settings.setDisableReelsEntirelyInternal(value); + break; + case 'disableExploreEntirely': + _disableExploreEntirely = value; + settings.setDisableExploreEntirelyInternal(value); + break; + } + }); + HapticFeedback.selectionClick(); + } + + Future _turnOnMinimalMode() async { + final settings = context.read(); + await settings.setMinimalModeEnabled(true); + setState(() { + _blurExplore = true; + _disableReelsEntirely = true; + _disableExploreEntirely = true; + }); + HapticFeedback.mediumImpact(); + } + + Future _turnOffMinimalMode() async { + final settings = context.read(); + await settings.setMinimalModeEnabled(false); + // Refresh local state after turning off + setState(() { + _blurExplore = settings.blurExplore; + _disableReelsEntirely = settings.disableReelsEntirely; + _disableExploreEntirely = settings.disableExploreEntirely; + }); + HapticFeedback.mediumImpact(); + } + + @override + Widget build(BuildContext context) { + final settings = context.watch(); + final isDark = settings.isDarkMode; + final isMinimalModeEnabled = settings.minimalModeEnabled; + + return Scaffold( + appBar: _subAppBar(context, 'Minimal Mode'), + body: ListView( + children: [ + Container( + margin: const EdgeInsets.all(16), + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + gradient: LinearGradient( + colors: isMinimalModeEnabled + ? [Colors.redAccent.withValues(alpha: 0.2), Colors.red.withValues(alpha: 0.1)] + : [Colors.grey.withValues(alpha: 0.1), Colors.grey.withValues(alpha: 0.05)], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: isMinimalModeEnabled ? Colors.redAccent.withValues(alpha: 0.3) : Colors.grey.withValues(alpha: 0.2), + ), + ), + child: Column( + children: [ + Icon( + isMinimalModeEnabled ? Icons.shield_rounded : Icons.shield_outlined, + color: isMinimalModeEnabled ? Colors.redAccent : Colors.grey, + size: 48, + ), + const SizedBox(height: 12), + Text( + isMinimalModeEnabled ? 'Minimal Mode Active' : 'Minimal Mode Disabled', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: isMinimalModeEnabled ? Colors.redAccent : Colors.grey, + ), + ), + const SizedBox(height: 8), + Text( + isMinimalModeEnabled + ? 'Distractions are blocked. Customize which features stay enabled below.' + : 'Turn on to block all distractions at once, or customize individual settings below.', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 13, color: isDark ? Colors.white54 : Colors.black54), + ), + const SizedBox(height: 16), + SizedBox( + width: double.infinity, + child: ElevatedButton( + onPressed: isMinimalModeEnabled ? _turnOffMinimalMode : _turnOnMinimalMode, + style: ElevatedButton.styleFrom( + backgroundColor: isMinimalModeEnabled ? Colors.grey : Colors.redAccent, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + child: Text(isMinimalModeEnabled ? 'Turn Off Minimal Mode' : 'Turn On Minimal Mode'), + ), + ), + ], + ), + ), + + const _SectionHeader(title: 'CUSTOMIZE SETTINGS'), + + Container( + margin: const EdgeInsets.fromLTRB(16, 0, 16, 8), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.07), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Colors.blue.withValues(alpha: 0.12)), + ), + child: const Row( + children: [ + Icon(Icons.touch_app_rounded, size: 14, color: Colors.blueAccent), + SizedBox(width: 8), + Expanded( + child: Text( + 'Toggle settings below to customize what gets enabled when Minimal Mode is turned ON.', + style: TextStyle(fontSize: 11, color: Colors.blueAccent), + ), + ), + ], + ), + ), + + _SwitchTile( + title: 'Blur Feed & Explore', + subtitle: 'Blurs post thumbnails until tapped', + value: _blurExplore, + onChanged: (v) => _updateSetting('blurExplore', v), + ), + _SwitchTile( + title: 'Disable Reels Entirely', + subtitle: 'Block all Reels with no session option', + value: _disableReelsEntirely, + onChanged: (v) => _updateSetting('disableReelsEntirely', v), + ), + _SwitchTile( + title: 'Disable Explore Entirely', + subtitle: 'Block Explore completely (not just blur)', + value: _disableExploreEntirely, + onChanged: (v) => _updateSetting('disableExploreEntirely', v), + ), + + const SizedBox(height: 40), + ], + ), + ); + } +} + +// ─── Appearance ─────────────────────────────────────────────────────────────── + +class AppearancePage extends StatefulWidget { + const AppearancePage({super.key}); + + @override + State createState() => _AppearancePageState(); +} + +class _AppearancePageState extends State { + Future _addSchedule(BuildContext context, SettingsService settings) async { + TimeOfDay? startTime = await showTimePicker( + context: context, + initialTime: const TimeOfDay(hour: 21, minute: 0), + helpText: 'Select start time', + ); + + if (startTime == null || !context.mounted) return; + + TimeOfDay? endTime = await showTimePicker( + context: context, + initialTime: const TimeOfDay(hour: 6, minute: 0), + helpText: 'Select end time', + ); + + if (endTime == null || !context.mounted) return; + + final newSchedule = { + 'enabled': true, + 'startTime': '${startTime.hour.toString().padLeft(2, '0')}:${startTime.minute.toString().padLeft(2, '0')}', + 'endTime': '${endTime.hour.toString().padLeft(2, '0')}:${endTime.minute.toString().padLeft(2, '0')}', + }; + + await settings.addGrayscaleSchedule(newSchedule); + } + + Future _editSchedule(BuildContext context, SettingsService settings, int index) async { + final schedules = settings.grayscaleSchedules; + if (index >= schedules.length) return; + + final current = schedules[index]; + final startParts = (current['startTime'] as String).split(':'); + final endParts = (current['endTime'] as String).split(':'); + + // Capture context before async gap + final capturedContext = context; + + TimeOfDay? startTime = await showTimePicker( + context: capturedContext, + initialTime: TimeOfDay( + hour: int.parse(startParts[0]), + minute: int.parse(startParts[1]), + ), + helpText: 'Select start time', + ); + + if (startTime == null || !capturedContext.mounted) return; + + TimeOfDay? endTime = await showTimePicker( + context: capturedContext, + initialTime: TimeOfDay( + hour: int.parse(endParts[0]), + minute: int.parse(endParts[1]), + ), + helpText: 'Select end time', + ); + + if (endTime == null || !capturedContext.mounted) return; + + final updatedSchedule = { + ...current, + 'startTime': '${startTime.hour.toString().padLeft(2, '0')}:${startTime.minute.toString().padLeft(2, '0')}', + 'endTime': '${endTime.hour.toString().padLeft(2, '0')}:${endTime.minute.toString().padLeft(2, '0')}', + }; + + await settings.updateGrayscaleSchedule(index, updatedSchedule); + } + + Future _toggleSchedule(SettingsService settings, int index) async { + final schedules = List>.from(settings.grayscaleSchedules); + if (index >= schedules.length) return; + + schedules[index] = { + ...schedules[index], + 'enabled': !(schedules[index]['enabled'] as bool), + }; + + await settings.setGrayscaleSchedules(schedules); + } + + Future _deleteSchedule(SettingsService settings, int index) async { + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Delete Schedule'), + content: const Text('Are you sure you want to delete this schedule?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('Delete'), + ), + ], + ), + ); + + if (confirmed == true) { + await settings.removeGrayscaleSchedule(index); + } + } + + String _formatTimeRange(Map schedule) { + return '${schedule['startTime']} - ${schedule['endTime']}'; + } + + @override + Widget build(BuildContext context) { + final settings = context.watch(); + final isDark = settings.isDarkMode; + return Scaffold( + appBar: _subAppBar(context, 'Appearance'), + body: ListView( + children: [ + const _SectionHeader(title: 'DISPLAY'), + _SwitchTile( + title: 'Grayscale Mode', + subtitle: 'Makes Instagram black & white — reduces dopamine response', + value: settings.grayscaleEnabled, + onChanged: (v) => settings.setGrayscaleEnabled(v), + ), + const _SectionHeader(title: 'GRAYSCALE SCHEDULES'), + Container( + margin: const EdgeInsets.fromLTRB(16, 0, 16, 12), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.07), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.blue.withValues(alpha: 0.15)), + ), + child: const Text( + 'Auto-enable grayscale during specific hours. Similar to Scheduled Blocking in Guardrails. You can add multiple schedules.', + style: TextStyle(fontSize: 12, height: 1.5), + ), + ), + + // Status indicator + if (settings.grayscaleSchedules.isNotEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: settings.isGrayscaleActiveNow ? Colors.green.withValues(alpha: 0.1) : Colors.orange.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: settings.isGrayscaleActiveNow ? Colors.green.withValues(alpha: 0.3) : Colors.orange.withValues(alpha: 0.3)), + ), + child: Row( + children: [ + Icon( + settings.isGrayscaleActiveNow ? Icons.check_circle : Icons.schedule, + color: settings.isGrayscaleActiveNow ? Colors.greenAccent : Colors.orangeAccent, + size: 20 + ), + const SizedBox(width: 12), + Expanded( + child: Text( + settings.isGrayscaleActiveNow + ? 'Grayscale is active now' + : 'Grayscale is currently inactive', + style: TextStyle( + fontSize: 13, + color: settings.isGrayscaleActiveNow ? Colors.greenAccent : Colors.orangeAccent + ), + ), + ), + ], + ), + ), + ), + + // Schedule list + ...List.generate(settings.grayscaleSchedules.length, (index) { + final schedule = settings.grayscaleSchedules[index]; + final isEnabled = schedule['enabled'] as bool; + return ListTile( + leading: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: (isEnabled ? Colors.purpleAccent : Colors.grey).withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(10), + ), + child: Icon( + isEnabled ? Icons.play_circle_outline : Icons.pause_circle_outline, + color: isEnabled ? Colors.purpleAccent : Colors.grey, + size: 20, + ), + ), + title: Text( + _formatTimeRange(schedule), + style: TextStyle( + color: isEnabled ? Colors.purpleAccent : Colors.grey, + fontWeight: FontWeight.w500, + ), + ), + subtitle: Text( + isEnabled ? 'Active' : 'Disabled', + style: TextStyle(fontSize: 12, color: isDark ? Colors.white54 : Colors.black45), + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Switch( + value: isEnabled, + onChanged: (v) => _toggleSchedule(settings, index), + ), + PopupMenuButton( + onSelected: (value) { + if (value == 'edit') { + _editSchedule(context, settings, index); + } else if (value == 'delete') { + _deleteSchedule(settings, index); + } + }, + itemBuilder: (context) => [ + const PopupMenuItem( + value: 'edit', + child: Row( + children: [ + Icon(Icons.edit, size: 18), + SizedBox(width: 8), + Text('Edit'), + ], + ), + ), + const PopupMenuItem( + value: 'delete', + child: Row( + children: [ + Icon(Icons.delete, size: 18, color: Colors.red), + SizedBox(width: 8), + Text('Delete', style: TextStyle(color: Colors.red)), + ], + ), + ), + ], + ), + ], + ), + onTap: () => _editSchedule(context, settings, index), + ); + }), + + // Add schedule button + ListTile( + leading: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: Colors.green.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(10), + ), + child: const Icon(Icons.add_circle_outline, color: Colors.green, size: 20), + ), + title: const Text('Add Schedule', style: TextStyle(color: Colors.green)), + subtitle: Text( + 'Add a new grayscale schedule', + style: TextStyle(fontSize: 12, color: isDark ? Colors.white54 : Colors.black45), + ), + onTap: () => _addSchedule(context, settings), + ), + + const SizedBox(height: 40), + ], + ), + ); + } +} + +// ─── Privacy & Notifications ────────────────────────────────────────────────── + +class PrivacyNotificationsPage extends StatelessWidget { + const PrivacyNotificationsPage({super.key}); + + @override + Widget build(BuildContext context) { + final settings = context.watch(); + return Scaffold( + appBar: _subAppBar(context, 'Privacy & Notifications'), + body: ListView( + children: [ + const _SectionHeader(title: 'NOTIFICATIONS'), + Container( + margin: const EdgeInsets.fromLTRB(16, 0, 16, 12), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.07), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.blue.withValues(alpha: 0.15)), + ), + child: const Text( + 'FocusGram can show notifications when your Focus session ends. ' + 'Instagram\'s own notification system handles background alerts.', + style: TextStyle(fontSize: 12, height: 1.5), + ), + ), + _SwitchTile( + title: 'Session End Notification', + subtitle: 'Notify when Focus session time is up', + value: settings.notifySessionEnd, + onChanged: (v) => settings.setNotifySessionEnd(v), + ), + _SwitchTile( + title: 'Persistent Notification', + subtitle: 'Show ongoing notification while using Instagram', + value: settings.notifyPersistent, + onChanged: (v) => settings.setNotifyPersistent(v), + ), + + const _SectionHeader(title: 'INSTA NOTIFICATIONS'), + _SwitchTile( + title: 'DM Notifications', + subtitle: 'Show notification when someone messages you', + value: settings.notifyDMs, + onChanged: (v) => settings.setNotifyDMs(v), + ), + _SwitchTile( + title: 'Activity Notifications', + subtitle: 'Likes, comments, follows and other activity', + value: settings.notifyActivity, + onChanged: (v) => settings.setNotifyActivity(v), + ), + + const SizedBox(height: 40), + ], + ), + ); + } +} + +// ─── Shared widgets ─────────────────────────────────────────────────────────── + +PreferredSizeWidget _subAppBar(BuildContext context, String title) => AppBar( + title: Text( + title, + style: const TextStyle(fontSize: 17, fontWeight: FontWeight.w600), + ), + centerTitle: true, + leading: IconButton( + icon: const Icon(Icons.arrow_back_ios_new, size: 18), + onPressed: () => Navigator.pop(context), + ), +); + +class _SubmoduleTile extends StatelessWidget { + final IconData icon; + final Color iconColor; + final String title; + final String subtitle; + final String? disabledSubtitle; + final bool enabled; + final VoidCallback onTap; + + const _SubmoduleTile({ + required this.icon, + required this.iconColor, + required this.title, + required this.subtitle, + this.disabledSubtitle, + this.enabled = true, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return ListTile( + leading: Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: (enabled ? iconColor : Colors.grey).withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(icon, color: enabled ? iconColor : Colors.grey, size: 20), + ), + title: Text( + title, + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w500, + color: enabled ? null : Colors.grey, + ), + ), + subtitle: Text( + enabled ? subtitle : (disabledSubtitle ?? subtitle), + style: const TextStyle(fontSize: 12), + ), + trailing: const Icon( + Icons.arrow_forward_ios, + size: 14, + color: Colors.grey, + ), + onTap: enabled ? onTap : null, + ); + } +} + +class _SwitchTile extends StatelessWidget { + final String title; + final String? subtitle; + final bool value; + final ValueChanged onChanged; + + const _SwitchTile({ + required this.title, + this.subtitle, + required this.value, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return SwitchListTile( + title: Text( + title, + style: const TextStyle(fontSize: 15), + ), + subtitle: subtitle != null + ? Text( + subtitle ?? '', + style: const TextStyle(fontSize: 12), + ) + : null, + value: value, + onChanged: onChanged, + ); + } +} + +class _SectionHeader extends StatelessWidget { + final String title; + const _SectionHeader({required this.title}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 24, 16, 8), + child: Text( + title, + style: const TextStyle( + color: Colors.grey, + fontSize: 11, + fontWeight: FontWeight.bold, + letterSpacing: 1.2, + ), + ), + ); + } +} diff --git a/lib/scripts/autoplay_blocker.dart b/lib/scripts/autoplay_blocker.dart new file mode 100644 index 0000000..2f5e294 --- /dev/null +++ b/lib/scripts/autoplay_blocker.dart @@ -0,0 +1,225 @@ +/// JavaScript to block autoplaying videos on Instagram feed/explore while: +/// - Allowing videos to play normally when "Block Autoplay Videos" is OFF +/// - Allowing user-initiated playback on click when blocking is ON +/// - NEVER blocking reels (they should always play normally per user request) +/// +/// This script: +/// - Overrides HTMLVideoElement.prototype.play before Instagram initialises. +/// - PAUSES any playing videos immediately when autoplay is blocked (only for feed/explore). +/// - Returns Promise.resolve() for blocked autoplay calls (never throws). +/// - Uses a per-element flag set by user clicks to permanently allow that video to play. +/// - Strips the autoplay attribute from dynamically added