commit b594facb51767bbb7f3b733a2afc0d2d69770e2b Author: fiatcode Date: Mon Oct 20 16:43:59 2025 +0700 initial commit (migrated) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..6f33486 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,35 @@ +name: Flutter Test + +on: + push: + branches: [ "main", "dev" ] + pull_request: + branches: [ "main", "dev" ] + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Setup repository + uses: actions/checkout@v4 + + - name: Setup Flutter + uses: subosito/flutter-action@v2 + with: + channel: 'stable' + + - name: Install dependencies + run: flutter pub get + + - name: Verify formatting + run: dart format --set-exit-if-changed . + + - name: Populate auto-generated code + run: dart run build_runner build --delete-conflicting-outputs + + - name: Analyze project source + run: flutter analyze . + + - name: Run tests + run: flutter test \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2014d1c --- /dev/null +++ b/.gitignore @@ -0,0 +1,47 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# 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/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# 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 + +# env files +.env +lib/core/env.g.dart diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..eeac26e --- /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: "80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819 + base_revision: 80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819 + - platform: ios + create_revision: 80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819 + base_revision: 80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819 + + # 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/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..565a5d2 --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# Kuwot +Daily quote app with beautiful pics from [Unsplash](https://unsplash.com/), built with Flutter 🚀 + +# Environment Variables +## Visual Studio Code +Add or modify `.vscode/launch.json`, fills out the required environment variables. + +```json +{ + "version": "0.2.0", + "configurations": [ + { + "name": "kuwot-app (dev)", + "request": "launch", + "type": "dart", + "args": [ + "--dart-define=QUOTE_API_SCHEME=http", + "--dart-define=QUOTE_API_HOST=10.0.2.2", + "--dart-define=QUOTE_API_PORT=8080", + "--dart-define=AUTH_PUBLIC_KEY=keep_looking", + "--dart-define=SENTRY_DSN=optional" + ] + } + ] +} +``` + +## Android Studio (or IntelliJ) +Add or modify `run/debug configurations`, add the following environment variables to the `Additional run args` field. + +``` +--dart-define=QUOTE_API_SCHEME=http +--dart-define=QUOTE_API_HOST=10.0.2.2 +--dart-define=QUOTE_API_PORT=8080 +--dart-define=AUTH_PUBLIC_KEY=keep_looking +--dart-define=SENTRY_DSN=optional +``` diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..84acf28 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,7 @@ +include: package:flutter_lints/flutter.yaml + +analyzer: + errors: + invalid_annotation_target: ignore + exclude: + - '**/*.g.dart' \ No newline at end of file diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..52561eb --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app +key.properties +keystore.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..092d9c6 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,109 @@ +plugins { + id "com.android.application" + id "kotlin-android" + id "dev.flutter.flutter-gradle-plugin" +} + +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +def keystoreProperties = new Properties() +def keystorePropertiesFile = rootProject.file('keystore.properties') +if (keystorePropertiesFile.exists()) { + keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) +} + +android { + namespace "com.dhemasnurjaya.kuwot" + compileSdk flutter.compileSdkVersion + ndkVersion flutter.ndkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = '17' + } + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId "com.dhemasnurjaya.kuwot" + // You can update the following values to match your application needs. + // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. + minSdkVersion flutter.minSdkVersion + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + } + + signingConfigs { + release { + if (System.getenv()["CI"]) { // CI=true is exported by Codemagic + storeFile file(System.getenv()["CM_KEYSTORE_PATH"]) + storePassword System.getenv()["CM_KEYSTORE_PASSWORD"] + keyAlias System.getenv()["CM_KEY_ALIAS"] + keyPassword System.getenv()["CM_KEY_PASSWORD"] + } else { + keyAlias keystoreProperties['keyAlias'] + keyPassword keystoreProperties['keyPassword'] + storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null + storePassword keystoreProperties['storePassword'] + } + } + } + + buildTypes { + release { + // Enables code shrinking, obfuscation, and optimization for only + // your project's release build type. Make sure to use a build + // variant with `debuggable false`. + minifyEnabled true + + // Enables resource shrinking, which is performed by the + // Android Gradle plugin. + shrinkResources true + + // Includes the default ProGuard rules files that are packaged with + // the Android Gradle plugin. To learn more, go to the section about + // R8 configuration files. + proguardFiles getDefaultProguardFile( + 'proguard-android-optimize.txt'), + 'proguard-rules.pro' + + // Signing with the debug keys for now, so `flutter run --release` works. + // signingConfig signingConfigs.debug + signingConfig signingConfigs.release + } + } +} + +flutter { + source '../..' +} + +dependencies { + def billing_version = "7.0.0" + + implementation "com.android.billingclient:billing:$billing_version" +} 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..8add617 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/dhemasnurjaya/kuwot/MainActivity.kt b/android/app/src/main/kotlin/com/dhemasnurjaya/kuwot/MainActivity.kt new file mode 100644 index 0000000..4d9da24 --- /dev/null +++ b/android/app/src/main/kotlin/com/dhemasnurjaya/kuwot/MainActivity.kt @@ -0,0 +1,5 @@ +package com.dhemasnurjaya.kuwot + +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..7a56e12 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..f65cea6 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..54052d5 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..7ae617b 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..51d1782 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..527df5b 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..6c66818 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..6f27a0f 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..aa53ee2 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..63cdcfd 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..ab98328 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,4 @@ + + + #ffffff + \ 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/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000..bc157bd --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,18 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = '../build' +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(':app') +} + +tasks.register("clean", Delete) { + delete rootProject.buildDir +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..73c3168 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx4G +android.useAndroidX=true +android.enableJetifier=true +android.defaults.buildfeatures.buildconfig=true +android.nonTransitiveRClass=false +android.nonFinalResIds=false diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..02767eb --- /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.13-all.zip diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..65541b2 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,26 @@ +pluginManagement { + def flutterSdkPath = { + def properties = new Properties() + file("local.properties").withInputStream { properties.load(it) } + def flutterSdkPath = properties.getProperty("flutter.sdk") + assert flutterSdkPath != null, "flutter.sdk not set in local.properties" + return flutterSdkPath + } + settings.ext.flutterSdkPath = flutterSdkPath() + + includeBuild("${settings.ext.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.12.2" apply false + id "org.jetbrains.kotlin.android" version "2.2.10" apply false +} + +include ":app" diff --git a/assets/pngs/chat-quote-fill.png b/assets/pngs/chat-quote-fill.png new file mode 100644 index 0000000..158618e Binary files /dev/null and b/assets/pngs/chat-quote-fill.png differ diff --git a/assets/pngs/chat-quote.png b/assets/pngs/chat-quote.png new file mode 100644 index 0000000..4682451 Binary files /dev/null and b/assets/pngs/chat-quote.png differ diff --git a/assets/pngs/web-icon.png b/assets/pngs/web-icon.png new file mode 100644 index 0000000..1b72579 Binary files /dev/null and b/assets/pngs/web-icon.png differ diff --git a/assets/svgs/chat-quote-fill.svg b/assets/svgs/chat-quote-fill.svg new file mode 100644 index 0000000..e573dbf --- /dev/null +++ b/assets/svgs/chat-quote-fill.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/assets/svgs/chat-quote.svg b/assets/svgs/chat-quote.svg new file mode 100644 index 0000000..f49b954 --- /dev/null +++ b/assets/svgs/chat-quote.svg @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/codemagic.yaml b/codemagic.yaml new file mode 100644 index 0000000..9fc3c6b --- /dev/null +++ b/codemagic.yaml @@ -0,0 +1,65 @@ +workflows: + android-workflow: + name: Android Workflow + instance_type: mac_mini_m2 + max_build_duration: 30 + + triggering: + events: + - push + branch_patterns: + - pattern: 'dev' + include: true + source: false + + environment: + android_signing: + - dhemasnurjaya_keystore + groups: + - app_secrets + - google_play_credentials + vars: + PACKAGE_NAME: "com.dhemasnurjaya.kuwot" + GOOGLE_PLAY_TRACK: "alpha" + flutter: stable + + cache: + cache_paths: + - $HOME/.gradle/caches + - $FLUTTER_ROOT/.pub-cache + + scripts: + - name: Set up local.properties + script: | + echo "flutter.sdk=$HOME/programs/flutter" > "$CM_BUILD_DIR/android/local.properties" + - name: Get Flutter packages + script: | + flutter packages pub get + - name: Flutter analyze + script: | + flutter analyze + - name: Flutter unit tests + script: | + flutter test + ignore_failure: false + - name: Build AAB with Flutter + script: | + BUILD_NUMBER=$(($(google-play get-latest-build-number --package-name "$PACKAGE_NAME" --tracks="$GOOGLE_PLAY_TRACK") + 1)) + flutter build appbundle --release \ + --dart-define=QUOTE_API_SCHEME=$QUOTE_API_SCHEME \ + --dart-define=QUOTE_API_HOST=$QUOTE_API_HOST \ + --dart-define=AUTH_PUBLIC_KEY=$AUTH_PUBLIC_KEY \ + --dart-define=SENTRY_DSN=$SENTRY_DSN \ + --build-name=1.1.$BUILD_NUMBER \ + --build-number=$BUILD_NUMBER + + artifacts: + - build/**/outputs/**/*.aab + - build/**/outputs/**/mapping.txt + - flutter_drive.log + + publishing: + google_play: + credentials: $GCLOUD_SERVICE_ACCOUNT_CREDENTIALS + track: $GOOGLE_PLAY_TRACK + submit_as_draft: true 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/lib/core/app_updater.dart b/lib/core/app_updater.dart new file mode 100644 index 0000000..70a59a1 --- /dev/null +++ b/lib/core/app_updater.dart @@ -0,0 +1,22 @@ +import 'package:in_app_update/in_app_update.dart'; + +/// A wrapper of in-app update plugin +abstract class AppUpdater { + /// Check for in-app update + Future checkForUpdate(); + + /// Start update process + Future update(); +} + +class AppUpdaterImpl implements AppUpdater { + @override + Future checkForUpdate() async { + return InAppUpdate.checkForUpdate(); + } + + @override + Future update() async { + return InAppUpdate.performImmediateUpdate(); + } +} diff --git a/lib/core/data/local/config.dart b/lib/core/data/local/config.dart new file mode 100644 index 0000000..98b2c7f --- /dev/null +++ b/lib/core/data/local/config.dart @@ -0,0 +1,11 @@ +/// Config base class +abstract class Config { + /// Get config value + Future get(); + + /// Set config value + Future set(T value); + + /// Remove config value + Future remove(); +} diff --git a/lib/core/data/local/theme_mode_config.dart b/lib/core/data/local/theme_mode_config.dart new file mode 100644 index 0000000..a0dea3a --- /dev/null +++ b/lib/core/data/local/theme_mode_config.dart @@ -0,0 +1,47 @@ +import 'package:kuwot/core/data/local/config.dart'; +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Theme mode shared preferences key +const themeModeConfigKey = 'themeMode'; + +/// Theme mode configuration +class ThemeModeConfig extends Config { + /// Default constructor + ThemeModeConfig({required this.sharedPreferences}); + + /// Shared preferences instance + final SharedPreferences sharedPreferences; + + @override + Future get() async { + final mode = sharedPreferences.getString(themeModeConfigKey); + switch (mode) { + case 'dark': + return ThemeMode.dark; + case 'light': + return ThemeMode.light; + case 'system': + return ThemeMode.system; + default: + return ThemeMode.system; + } + } + + @override + Future set(ThemeMode value) async { + switch (value) { + case ThemeMode.dark: + await sharedPreferences.setString(themeModeConfigKey, 'dark'); + case ThemeMode.light: + await sharedPreferences.setString(themeModeConfigKey, 'light'); + case ThemeMode.system: + await sharedPreferences.setString(themeModeConfigKey, 'system'); + } + } + + @override + Future remove() async { + await sharedPreferences.remove(themeModeConfigKey); + } +} diff --git a/lib/core/data/local/translation_target_config.dart b/lib/core/data/local/translation_target_config.dart new file mode 100644 index 0000000..55c175b --- /dev/null +++ b/lib/core/data/local/translation_target_config.dart @@ -0,0 +1,45 @@ +import 'dart:convert'; + +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:kuwot/core/data/local/config.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +part 'translation_target_config.freezed.dart'; +part 'translation_target_config.g.dart'; + +const translationTargetConfigKey = 'translationTarget'; +const defaultTranslationTarget = TranslationTarget(id: 'en', name: 'English'); + +@freezed +abstract class TranslationTarget with _$TranslationTarget { + const factory TranslationTarget({required String id, required String name}) = + _TranslationTarget; + + factory TranslationTarget.fromJson(Map json) => + _$TranslationTargetFromJson(json); +} + +class TranslationTargetConfig extends Config { + TranslationTargetConfig({required this.sharedPreferences}); + + final SharedPreferences sharedPreferences; + + @override + Future get() async { + final data = sharedPreferences.getString(translationTargetConfigKey); + return data != null ? TranslationTarget.fromJson(jsonDecode(data)) : null; + } + + @override + Future set(TranslationTarget value) async { + await sharedPreferences.setString( + translationTargetConfigKey, + jsonEncode(value.toJson()), + ); + } + + @override + Future remove() async { + await sharedPreferences.remove(translationTargetConfigKey); + } +} diff --git a/lib/core/data/local/translation_target_config.freezed.dart b/lib/core/data/local/translation_target_config.freezed.dart new file mode 100644 index 0000000..d8c9b33 --- /dev/null +++ b/lib/core/data/local/translation_target_config.freezed.dart @@ -0,0 +1,280 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'translation_target_config.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; + +/// @nodoc +mixin _$TranslationTarget { + + String get id; String get name; +/// Create a copy of TranslationTarget +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$TranslationTargetCopyWith get copyWith => _$TranslationTargetCopyWithImpl(this as TranslationTarget, _$identity); + + /// Serializes this TranslationTarget to a JSON map. + Map toJson(); + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is TranslationTarget&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,id,name); + +@override +String toString() { + return 'TranslationTarget(id: $id, name: $name)'; +} + + +} + +/// @nodoc +abstract mixin class $TranslationTargetCopyWith<$Res> { + factory $TranslationTargetCopyWith(TranslationTarget value, $Res Function(TranslationTarget) _then) = _$TranslationTargetCopyWithImpl; +@useResult +$Res call({ + String id, String name +}); + + + + +} +/// @nodoc +class _$TranslationTargetCopyWithImpl<$Res> + implements $TranslationTargetCopyWith<$Res> { + _$TranslationTargetCopyWithImpl(this._self, this._then); + + final TranslationTarget _self; + final $Res Function(TranslationTarget) _then; + +/// Create a copy of TranslationTarget +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? name = null,}) { + return _then(_self.copyWith( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable +as String, + )); +} + +} + + +/// Adds pattern-matching-related methods to [TranslationTarget]. +extension TranslationTargetPatterns on TranslationTarget { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _TranslationTarget value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _TranslationTarget() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _TranslationTarget value) $default,){ +final _that = this; +switch (_that) { +case _TranslationTarget(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _TranslationTarget value)? $default,){ +final _that = this; +switch (_that) { +case _TranslationTarget() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( String id, String name)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _TranslationTarget() when $default != null: +return $default(_that.id,_that.name);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( String id, String name) $default,) {final _that = this; +switch (_that) { +case _TranslationTarget(): +return $default(_that.id,_that.name);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String id, String name)? $default,) {final _that = this; +switch (_that) { +case _TranslationTarget() when $default != null: +return $default(_that.id,_that.name);case _: + return null; + +} +} + +} + +/// @nodoc +@JsonSerializable() + +class _TranslationTarget implements TranslationTarget { + const _TranslationTarget({required this.id, required this.name}); + factory _TranslationTarget.fromJson(Map json) => _$TranslationTargetFromJson(json); + +@override final String id; +@override final String name; + +/// Create a copy of TranslationTarget +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$TranslationTargetCopyWith<_TranslationTarget> get copyWith => __$TranslationTargetCopyWithImpl<_TranslationTarget>(this, _$identity); + +@override +Map toJson() { + return _$TranslationTargetToJson(this, ); +} + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _TranslationTarget&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,id,name); + +@override +String toString() { + return 'TranslationTarget(id: $id, name: $name)'; +} + + +} + +/// @nodoc +abstract mixin class _$TranslationTargetCopyWith<$Res> implements $TranslationTargetCopyWith<$Res> { + factory _$TranslationTargetCopyWith(_TranslationTarget value, $Res Function(_TranslationTarget) _then) = __$TranslationTargetCopyWithImpl; +@override @useResult +$Res call({ + String id, String name +}); + + + + +} +/// @nodoc +class __$TranslationTargetCopyWithImpl<$Res> + implements _$TranslationTargetCopyWith<$Res> { + __$TranslationTargetCopyWithImpl(this._self, this._then); + + final _TranslationTarget _self; + final $Res Function(_TranslationTarget) _then; + +/// Create a copy of TranslationTarget +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? name = null,}) { + return _then(_TranslationTarget( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +// dart format on diff --git a/lib/core/data/local/translation_target_config.g.dart b/lib/core/data/local/translation_target_config.g.dart new file mode 100644 index 0000000..c6a73ac --- /dev/null +++ b/lib/core/data/local/translation_target_config.g.dart @@ -0,0 +1,13 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'translation_target_config.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_TranslationTarget _$TranslationTargetFromJson(Map json) => + _TranslationTarget(id: json['id'] as String, name: json['name'] as String); + +Map _$TranslationTargetToJson(_TranslationTarget instance) => + {'id': instance.id, 'name': instance.name}; diff --git a/lib/core/domain/no_params.dart b/lib/core/domain/no_params.dart new file mode 100644 index 0000000..705dd18 --- /dev/null +++ b/lib/core/domain/no_params.dart @@ -0,0 +1,8 @@ +import 'package:equatable/equatable.dart'; + +class NoParams extends Equatable { + const NoParams(); + + @override + List get props => []; +} diff --git a/lib/core/domain/use_case.dart b/lib/core/domain/use_case.dart new file mode 100644 index 0000000..e46f6f3 --- /dev/null +++ b/lib/core/domain/use_case.dart @@ -0,0 +1,9 @@ +import 'package:fpdart/fpdart.dart'; +import 'package:kuwot/core/error/failure.dart'; + +/// [TReturnType] is the return type of a successful use case call. +/// [TParams] are the parameters that are required to call the use case. +abstract class UseCase { + /// Execute the use case + Future> call(TParams params); +} diff --git a/lib/core/either_extensions.dart b/lib/core/either_extensions.dart new file mode 100644 index 0000000..b240342 --- /dev/null +++ b/lib/core/either_extensions.dart @@ -0,0 +1,11 @@ +import 'package:fpdart/fpdart.dart'; + +typedef Function1 = R Function(T t); + +extension EitherFutureX on Future> { + Future> chain( + Function1>> f, + ) async { + return (await this).fold(left, f); + } +} diff --git a/lib/core/env.dart b/lib/core/env.dart new file mode 100644 index 0000000..770b8ca --- /dev/null +++ b/lib/core/env.dart @@ -0,0 +1,31 @@ +// ignore_for_file: public_member_api_docs + +abstract class Env { + String get quoteApiScheme; + + String get quoteApiHost; + + int? get quoteApiPort; + + String get authPublicKey; + + String get sentryDsn; +} + +class EnvImpl implements Env { + @override + String get quoteApiScheme => const String.fromEnvironment('QUOTE_API_SCHEME'); + + @override + String get quoteApiHost => const String.fromEnvironment('QUOTE_API_HOST'); + + @override + int? get quoteApiPort => + int.tryParse(const String.fromEnvironment('QUOTE_API_PORT')); + + @override + String get authPublicKey => const String.fromEnvironment('AUTH_PUBLIC_KEY'); + + @override + String get sentryDsn => const String.fromEnvironment('SENTRY_DSN'); +} diff --git a/lib/core/error/exception.dart b/lib/core/error/exception.dart new file mode 100644 index 0000000..5190957 --- /dev/null +++ b/lib/core/error/exception.dart @@ -0,0 +1,16 @@ +/// Exception class for server error +/// Generally, this exception is thrown when the server returns an error response +class ServerException implements Exception { + const ServerException(this.message); + + final String message; +} + +/// Exception class for unauthorized client error +/// this exception is thrown when the client is not authorized +/// to access the resource (server returns 401) +class UnauthorizedException implements Exception { + const UnauthorizedException(this.message); + + final String message; +} diff --git a/lib/core/error/failure.dart b/lib/core/error/failure.dart new file mode 100644 index 0000000..dcdeb2b --- /dev/null +++ b/lib/core/error/failure.dart @@ -0,0 +1,28 @@ +import 'package:equatable/equatable.dart'; + +/// Base class for all failures +abstract class Failure extends Equatable { + /// Default constructor + const Failure({required this.message, this.cause}); + + /// Message of the failure + final String message; + + /// Cause of the failure + final Exception? cause; + + @override + List get props => [message, cause]; +} + +class ClientFailure extends Failure { + const ClientFailure({required super.message, super.cause}); +} + +class ServerFailure extends Failure { + const ServerFailure({required super.message, super.cause}); +} + +class UnknownFailure extends Failure { + const UnknownFailure({required super.message, super.cause}); +} diff --git a/lib/core/error/reporter.dart b/lib/core/error/reporter.dart new file mode 100644 index 0000000..dd3691a --- /dev/null +++ b/lib/core/error/reporter.dart @@ -0,0 +1,8 @@ +import 'package:sentry_flutter/sentry_flutter.dart'; + +/// Report error to Sentry +void reportError({required dynamic error, StackTrace? stackTrace}) { + if (error == null) return; + + Sentry.captureException(error, stackTrace: stackTrace); +} diff --git a/lib/core/error/server_error_model.dart b/lib/core/error/server_error_model.dart new file mode 100644 index 0000000..2f90f31 --- /dev/null +++ b/lib/core/error/server_error_model.dart @@ -0,0 +1,13 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'server_error_model.freezed.dart'; +part 'server_error_model.g.dart'; + +@freezed +abstract class ServerErrorModel with _$ServerErrorModel { + const factory ServerErrorModel({required String message, required int code}) = + _ServerErrorModel; + + factory ServerErrorModel.fromJson(Map json) => + _$ServerErrorModelFromJson(json); +} diff --git a/lib/core/error/server_error_model.freezed.dart b/lib/core/error/server_error_model.freezed.dart new file mode 100644 index 0000000..23ca69d --- /dev/null +++ b/lib/core/error/server_error_model.freezed.dart @@ -0,0 +1,280 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'server_error_model.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; + +/// @nodoc +mixin _$ServerErrorModel { + + String get message; int get code; +/// Create a copy of ServerErrorModel +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$ServerErrorModelCopyWith get copyWith => _$ServerErrorModelCopyWithImpl(this as ServerErrorModel, _$identity); + + /// Serializes this ServerErrorModel to a JSON map. + Map toJson(); + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is ServerErrorModel&&(identical(other.message, message) || other.message == message)&&(identical(other.code, code) || other.code == code)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,message,code); + +@override +String toString() { + return 'ServerErrorModel(message: $message, code: $code)'; +} + + +} + +/// @nodoc +abstract mixin class $ServerErrorModelCopyWith<$Res> { + factory $ServerErrorModelCopyWith(ServerErrorModel value, $Res Function(ServerErrorModel) _then) = _$ServerErrorModelCopyWithImpl; +@useResult +$Res call({ + String message, int code +}); + + + + +} +/// @nodoc +class _$ServerErrorModelCopyWithImpl<$Res> + implements $ServerErrorModelCopyWith<$Res> { + _$ServerErrorModelCopyWithImpl(this._self, this._then); + + final ServerErrorModel _self; + final $Res Function(ServerErrorModel) _then; + +/// Create a copy of ServerErrorModel +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? message = null,Object? code = null,}) { + return _then(_self.copyWith( +message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable +as String,code: null == code ? _self.code : code // ignore: cast_nullable_to_non_nullable +as int, + )); +} + +} + + +/// Adds pattern-matching-related methods to [ServerErrorModel]. +extension ServerErrorModelPatterns on ServerErrorModel { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _ServerErrorModel value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _ServerErrorModel() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _ServerErrorModel value) $default,){ +final _that = this; +switch (_that) { +case _ServerErrorModel(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _ServerErrorModel value)? $default,){ +final _that = this; +switch (_that) { +case _ServerErrorModel() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( String message, int code)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _ServerErrorModel() when $default != null: +return $default(_that.message,_that.code);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( String message, int code) $default,) {final _that = this; +switch (_that) { +case _ServerErrorModel(): +return $default(_that.message,_that.code);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String message, int code)? $default,) {final _that = this; +switch (_that) { +case _ServerErrorModel() when $default != null: +return $default(_that.message,_that.code);case _: + return null; + +} +} + +} + +/// @nodoc +@JsonSerializable() + +class _ServerErrorModel implements ServerErrorModel { + const _ServerErrorModel({required this.message, required this.code}); + factory _ServerErrorModel.fromJson(Map json) => _$ServerErrorModelFromJson(json); + +@override final String message; +@override final int code; + +/// Create a copy of ServerErrorModel +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$ServerErrorModelCopyWith<_ServerErrorModel> get copyWith => __$ServerErrorModelCopyWithImpl<_ServerErrorModel>(this, _$identity); + +@override +Map toJson() { + return _$ServerErrorModelToJson(this, ); +} + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _ServerErrorModel&&(identical(other.message, message) || other.message == message)&&(identical(other.code, code) || other.code == code)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,message,code); + +@override +String toString() { + return 'ServerErrorModel(message: $message, code: $code)'; +} + + +} + +/// @nodoc +abstract mixin class _$ServerErrorModelCopyWith<$Res> implements $ServerErrorModelCopyWith<$Res> { + factory _$ServerErrorModelCopyWith(_ServerErrorModel value, $Res Function(_ServerErrorModel) _then) = __$ServerErrorModelCopyWithImpl; +@override @useResult +$Res call({ + String message, int code +}); + + + + +} +/// @nodoc +class __$ServerErrorModelCopyWithImpl<$Res> + implements _$ServerErrorModelCopyWith<$Res> { + __$ServerErrorModelCopyWithImpl(this._self, this._then); + + final _ServerErrorModel _self; + final $Res Function(_ServerErrorModel) _then; + +/// Create a copy of ServerErrorModel +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? message = null,Object? code = null,}) { + return _then(_ServerErrorModel( +message: null == message ? _self.message : message // ignore: cast_nullable_to_non_nullable +as String,code: null == code ? _self.code : code // ignore: cast_nullable_to_non_nullable +as int, + )); +} + + +} + +// dart format on diff --git a/lib/core/error/server_error_model.g.dart b/lib/core/error/server_error_model.g.dart new file mode 100644 index 0000000..437e1ca --- /dev/null +++ b/lib/core/error/server_error_model.g.dart @@ -0,0 +1,16 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'server_error_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_ServerErrorModel _$ServerErrorModelFromJson(Map json) => + _ServerErrorModel( + message: json['message'] as String, + code: (json['code'] as num).toInt(), + ); + +Map _$ServerErrorModelToJson(_ServerErrorModel instance) => + {'message': instance.message, 'code': instance.code}; diff --git a/lib/core/network/network.dart b/lib/core/network/network.dart new file mode 100644 index 0000000..9c236e1 --- /dev/null +++ b/lib/core/network/network.dart @@ -0,0 +1,51 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; +import 'package:kuwot/core/error/exception.dart'; + +/// Network interface +abstract class Network { + /// Get data from uri + Future get(Uri uri, {Map? headers}); + + /// Post data to uri + Future post(Uri uri, {Map? headers, Object? body}); +} + +/// Network implementation +class NetworkImpl implements Network { + final _client = http.Client(); + + @override + Future get(Uri uri, {Map? headers}) async { + if (kDebugMode) { + print('GET: $uri, headers: $headers'); + } + final response = await _client.get(uri, headers: headers); + final stringResponse = utf8.decode(response.bodyBytes); + + if (response.statusCode == HttpStatus.unauthorized) { + throw UnauthorizedException(stringResponse); + } + + if (response.statusCode != HttpStatus.ok) { + throw ServerException(stringResponse); + } + + return stringResponse; + } + + @override + Future post( + Uri uri, { + Map? headers, + Object? body, + }) async { + if (kDebugMode) { + print('POST: $uri, headers: $headers, body: $body'); + } + final response = await _client.post(uri, headers: headers, body: body); + return utf8.decode(response.bodyBytes); + } +} diff --git a/lib/core/presentation/bloc/app_bloc_observer.dart b/lib/core/presentation/bloc/app_bloc_observer.dart new file mode 100644 index 0000000..fe40d97 --- /dev/null +++ b/lib/core/presentation/bloc/app_bloc_observer.dart @@ -0,0 +1,21 @@ +// ignore_for_file: public_member_api_docs, strict_raw_type + +import 'dart:developer' as dev; + +import 'package:flutter_bloc/flutter_bloc.dart'; + +class AppBlocObserver extends BlocObserver { + @override + void onError(BlocBase bloc, Object error, StackTrace stackTrace) { + dev.log("[bloc_error] $bloc\nerror: $error\nstacktrace: $stackTrace"); + super.onError(bloc, error, stackTrace); + } + + @override + void onChange(BlocBase bloc, Change change) { + dev.log( + "[${bloc.runtimeType}] ${DateTime.now().toIso8601String()}\nFrom: ${change.currentState}\nNext: ${change.nextState}", + ); + super.onChange(bloc, change); + } +} diff --git a/lib/core/presentation/bloc/config/theme_mode_cubit.dart b/lib/core/presentation/bloc/config/theme_mode_cubit.dart new file mode 100644 index 0000000..0125801 --- /dev/null +++ b/lib/core/presentation/bloc/config/theme_mode_cubit.dart @@ -0,0 +1,24 @@ +import 'package:kuwot/core/data/local/config.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +/// Theme mode cubit for theme mode management +class ThemeModeCubit extends Cubit { + /// Default [ThemeMode] is [ThemeMode.system] + ThemeModeCubit({ + required this.themeModeConfig, + required this.initialThemeMode, + }) : super(initialThemeMode); + + /// Theme mode config + final Config themeModeConfig; + + /// Initial theme mode + final ThemeMode initialThemeMode; + + /// Set theme mode + void setThemeMode(ThemeMode themeMode) { + themeModeConfig.set(themeMode); + emit(themeMode); + } +} diff --git a/lib/core/presentation/bloc/config/translation_target_cubit.dart b/lib/core/presentation/bloc/config/translation_target_cubit.dart new file mode 100644 index 0000000..3656c46 --- /dev/null +++ b/lib/core/presentation/bloc/config/translation_target_cubit.dart @@ -0,0 +1,18 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:kuwot/core/data/local/config.dart'; +import 'package:kuwot/core/data/local/translation_target_config.dart'; + +class TranslationTargetCubit extends Cubit { + TranslationTargetCubit({ + required this.translationTargetConfig, + required this.initialTranslationTarget, + }) : super(initialTranslationTarget); + + final Config translationTargetConfig; + final TranslationTarget initialTranslationTarget; + + void set(TranslationTarget translationTarget) { + translationTargetConfig.set(translationTarget); + emit(translationTarget); + } +} diff --git a/lib/core/presentation/bloc/error_state.dart b/lib/core/presentation/bloc/error_state.dart new file mode 100644 index 0000000..3929980 --- /dev/null +++ b/lib/core/presentation/bloc/error_state.dart @@ -0,0 +1,6 @@ +abstract class ErrorState { + final String message; + final Exception? cause; + + const ErrorState({required this.message, this.cause}); +} diff --git a/lib/core/presentation/error_retry_snackbar.dart b/lib/core/presentation/error_retry_snackbar.dart new file mode 100644 index 0000000..1ba7510 --- /dev/null +++ b/lib/core/presentation/error_retry_snackbar.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; + +class ErrorRetrySnackbar { + final BuildContext context; + final String errorMessage; + final VoidCallback onRetry; + + const ErrorRetrySnackbar( + this.context, { + required this.errorMessage, + required this.onRetry, + }); + + SnackBar _build() { + return SnackBar( + behavior: SnackBarBehavior.floating, + duration: const Duration(days: 1), + backgroundColor: Colors.red[600], + content: Text(errorMessage), + action: SnackBarAction( + textColor: Colors.white, + label: 'RETRY', + onPressed: () { + onRetry(); + ScaffoldMessenger.of(context).hideCurrentSnackBar(); + }, + ), + ); + } + + static void show( + BuildContext context, { + required String errorMessage, + required VoidCallback onRetry, + }) { + ScaffoldMessenger.of(context).showSnackBar( + ErrorRetrySnackbar( + context, + errorMessage: errorMessage, + onRetry: onRetry, + )._build(), + ); + } +} diff --git a/lib/core/presentation/theme/app_theme.dart b/lib/core/presentation/theme/app_theme.dart new file mode 100644 index 0000000..97efe40 --- /dev/null +++ b/lib/core/presentation/theme/app_theme.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; +import 'package:google_fonts/google_fonts.dart'; + +/// App light theme +ThemeData lightTheme = ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF343A40)), + useMaterial3: true, + fontFamily: GoogleFonts.dmSans().fontFamily, +); + +/// App dark theme +ThemeData darkTheme = ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: const Color(0xFF212529), + brightness: Brightness.dark, + ), + useMaterial3: true, + fontFamily: GoogleFonts.dmSans().fontFamily, +); diff --git a/lib/core/router/app_router.dart b/lib/core/router/app_router.dart new file mode 100644 index 0000000..d28b934 --- /dev/null +++ b/lib/core/router/app_router.dart @@ -0,0 +1,13 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:kuwot/core/router/app_router.gr.dart'; + +@AutoRouterConfig() +class AppRouter extends RootStackRouter { + @override + List get routes => [ + AutoRoute(page: AppUpdateRoute.page, initial: true), + AutoRoute(page: QuoteRoute.page), + AutoRoute(page: AppSettingsRoute.page), + AutoRoute(page: DonationRoute.page), + ]; +} diff --git a/lib/core/router/app_router.gr.dart b/lib/core/router/app_router.gr.dart new file mode 100644 index 0000000..d21a59a --- /dev/null +++ b/lib/core/router/app_router.gr.dart @@ -0,0 +1,83 @@ +// dart format width=80 +// GENERATED CODE - DO NOT MODIFY BY HAND + +// ************************************************************************** +// AutoRouterGenerator +// ************************************************************************** + +// ignore_for_file: type=lint +// coverage:ignore-file + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'package:auto_route/auto_route.dart' as _i5; +import 'package:kuwot/features/app_settings/presentation/app_settings_page.dart' + as _i1; +import 'package:kuwot/features/in_app_purchase/presentation/donation_page.dart' + as _i3; +import 'package:kuwot/features/in_app_update/presentation/app_update_page.dart' + as _i2; +import 'package:kuwot/features/quote/presentation/quote_page.dart' as _i4; + +/// generated route for +/// [_i1.AppSettingsPage] +class AppSettingsRoute extends _i5.PageRouteInfo { + const AppSettingsRoute({List<_i5.PageRouteInfo>? children}) + : super(AppSettingsRoute.name, initialChildren: children); + + static const String name = 'AppSettingsRoute'; + + static _i5.PageInfo page = _i5.PageInfo( + name, + builder: (data) { + return const _i1.AppSettingsPage(); + }, + ); +} + +/// generated route for +/// [_i2.AppUpdatePage] +class AppUpdateRoute extends _i5.PageRouteInfo { + const AppUpdateRoute({List<_i5.PageRouteInfo>? children}) + : super(AppUpdateRoute.name, initialChildren: children); + + static const String name = 'AppUpdateRoute'; + + static _i5.PageInfo page = _i5.PageInfo( + name, + builder: (data) { + return const _i2.AppUpdatePage(); + }, + ); +} + +/// generated route for +/// [_i3.DonationPage] +class DonationRoute extends _i5.PageRouteInfo { + const DonationRoute({List<_i5.PageRouteInfo>? children}) + : super(DonationRoute.name, initialChildren: children); + + static const String name = 'DonationRoute'; + + static _i5.PageInfo page = _i5.PageInfo( + name, + builder: (data) { + return const _i3.DonationPage(); + }, + ); +} + +/// generated route for +/// [_i4.QuotePage] +class QuoteRoute extends _i5.PageRouteInfo { + const QuoteRoute({List<_i5.PageRouteInfo>? children}) + : super(QuoteRoute.name, initialChildren: children); + + static const String name = 'QuoteRoute'; + + static _i5.PageInfo page = _i5.PageInfo( + name, + builder: (data) { + return const _i4.QuotePage(); + }, + ); +} diff --git a/lib/core/time.dart b/lib/core/time.dart new file mode 100644 index 0000000..8972f0d --- /dev/null +++ b/lib/core/time.dart @@ -0,0 +1,13 @@ +/// Humble class for time related operations. +abstract class Time { + /// Get unix timestamp in seconds. + int getUnixTimestamp(); +} + +/// Implementation of [Time] using [DateTime]. +class TimeImpl implements Time { + @override + int getUnixTimestamp() { + return DateTime.now().millisecondsSinceEpoch ~/ 1000; + } +} diff --git a/lib/features/app_settings/presentation/app_settings_page.dart b/lib/features/app_settings/presentation/app_settings_page.dart new file mode 100644 index 0000000..f8e32b7 --- /dev/null +++ b/lib/features/app_settings/presentation/app_settings_page.dart @@ -0,0 +1,64 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:kuwot/core/presentation/bloc/config/theme_mode_cubit.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:kuwot/features/app_settings/presentation/widgets/about_widget.dart'; +import 'package:package_info_plus/package_info_plus.dart'; + +@RoutePage() +class AppSettingsPage extends StatefulWidget { + const AppSettingsPage({super.key}); + + @override + State createState() => _AppSettingsPageState(); +} + +class _AppSettingsPageState extends State { + @override + Widget build(BuildContext context) { + final themeSetting = Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('App Theme'), + DropdownButton( + items: const [ + DropdownMenuItem(value: ThemeMode.system, child: Text('System')), + DropdownMenuItem(value: ThemeMode.light, child: Text('Light')), + DropdownMenuItem(value: ThemeMode.dark, child: Text('Dark')), + ], + value: context.watch().state, + onChanged: (value) { + context.read().setThemeMode(value!); + }, + ), + ], + ); + final appVersion = Center( + child: FutureBuilder( + future: PackageInfo.fromPlatform(), + builder: (context, snapshot) { + if (snapshot.hasData) { + return Text( + 'v${snapshot.data!.version} (${snapshot.data!.buildNumber})', + ); + } + return const Text('...'); + }, + ), + ); + + return Scaffold( + appBar: AppBar(title: const Text('App Settings')), + body: ListView( + padding: const EdgeInsets.symmetric(horizontal: 16), + children: [ + themeSetting, + const SizedBox(height: 20), + appVersion, + const SizedBox(height: 20), + const AboutWidget(), + ], + ), + ); + } +} diff --git a/lib/features/app_settings/presentation/widgets/about_widget.dart b/lib/features/app_settings/presentation/widgets/about_widget.dart new file mode 100644 index 0000000..2aaf38a --- /dev/null +++ b/lib/features/app_settings/presentation/widgets/about_widget.dart @@ -0,0 +1,69 @@ +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher_string.dart'; + +class AboutWidget extends StatelessWidget { + const AboutWidget({super.key}); + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('Links & Credits', style: Theme.of(context).textTheme.titleMedium), + const Divider(), + _buildCreditItem( + context, + title: 'Kuwot App Source', + description: + 'Source code for this app. Any suggestions or contributions are welcome.', + url: 'https://github.com/dhemasnurjaya/kuwot-app', + ), + _buildCreditItem( + context, + title: 'Quotes-500K', + description: + 'Large quotes dataset by Shivali Goel, Rishi Madhok, Shweta Garg. Initially created for "Proposing Contextually Relevant Quotes for Images" journal.', + url: 'https://github.com/ShivaliGoel/Quotes-500K', + ), + _buildCreditItem( + context, + title: 'Unsplash', + description: + 'Over 6 million free high-resolution photos and illustrations brought to you by the world’s most generous community of contributors.', + url: 'https://unsplash.com/', + ), + ], + ); + } + + Widget _buildCreditItem( + BuildContext context, { + required String title, + required String description, + required String url, + }) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(title, style: Theme.of(context).textTheme.titleMedium), + Text(description), + const SizedBox(height: 4), + GestureDetector( + child: Text( + url, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + decoration: TextDecoration.underline, + color: Colors.indigoAccent, + decorationColor: Colors.indigoAccent, + ), + ), + onTap: () async { + await launchUrlString(url); + }, + ), + const SizedBox(height: 16), + ], + ); + } +} diff --git a/lib/features/in_app_purchase/data/data_sources/remote/in_app_purchase_remote_data_source.dart b/lib/features/in_app_purchase/data/data_sources/remote/in_app_purchase_remote_data_source.dart new file mode 100644 index 0000000..d5be500 --- /dev/null +++ b/lib/features/in_app_purchase/data/data_sources/remote/in_app_purchase_remote_data_source.dart @@ -0,0 +1,48 @@ +import 'package:in_app_purchase/in_app_purchase.dart'; + +const _consumableProductIds = { + 'donate_consumable_low', + 'donate_consumable_mid', + 'donate_consumable_high', +}; + +abstract class InAppPurchaseRemoteDataSource { + Stream> get purchaseStream; + + Future> getConsumableProducts(); + + Future purchaseConsumableProduct(ProductDetails product); + + Future completePurchase(PurchaseDetails purchaseDetails); +} + +class InAppPurchaseRemoteDataSourceImpl + implements InAppPurchaseRemoteDataSource { + InAppPurchaseRemoteDataSourceImpl({required this.iap}); + + final InAppPurchase iap; + + @override + Stream> get purchaseStream => iap.purchaseStream; + + @override + Future> getConsumableProducts() async { + final response = await iap.queryProductDetails(_consumableProductIds); + final productDetails = response.productDetails; + productDetails.sort((a, b) => a.price.compareTo(b.price)); + return productDetails; + } + + @override + Future purchaseConsumableProduct(ProductDetails product) async { + final response = await iap.buyConsumable( + purchaseParam: PurchaseParam(productDetails: product), + ); + return response; + } + + @override + Future completePurchase(PurchaseDetails purchaseDetails) { + return iap.completePurchase(purchaseDetails); + } +} diff --git a/lib/features/in_app_purchase/data/repositories/in_app_purchase_repository_impl.dart b/lib/features/in_app_purchase/data/repositories/in_app_purchase_repository_impl.dart new file mode 100644 index 0000000..36f7236 --- /dev/null +++ b/lib/features/in_app_purchase/data/repositories/in_app_purchase_repository_impl.dart @@ -0,0 +1,51 @@ +import 'package:fpdart/fpdart.dart'; +import 'package:in_app_purchase/in_app_purchase.dart'; +import 'package:kuwot/core/error/failure.dart'; +import 'package:kuwot/features/in_app_purchase/data/data_sources/remote/in_app_purchase_remote_data_source.dart'; +import 'package:kuwot/features/in_app_purchase/domain/repositories/in_app_purchase_repository.dart'; + +class InAppPurchaseRepositoryImpl implements InAppPurchaseRepository { + InAppPurchaseRepositoryImpl({required this.inAppPurchaseDataSource}); + + final InAppPurchaseRemoteDataSource inAppPurchaseDataSource; + + @override + Stream> get purchaseStream => + inAppPurchaseDataSource.purchaseStream; + + @override + Future>> getConsumableProducts() async { + try { + final response = await inAppPurchaseDataSource.getConsumableProducts(); + return right(response); + } catch (e) { + return left(UnknownFailure(message: e.toString())); + } + } + + @override + Future> purchaseConsumableProduct( + ProductDetails product, + ) async { + try { + final response = await inAppPurchaseDataSource.purchaseConsumableProduct( + product, + ); + return right(response); + } catch (e) { + return left(UnknownFailure(message: e.toString())); + } + } + + @override + Future> completePurchase( + PurchaseDetails purchaseDetails, + ) async { + try { + await inAppPurchaseDataSource.completePurchase(purchaseDetails); + return right(null); + } on Exception catch (e) { + return left(UnknownFailure(message: e.toString())); + } + } +} diff --git a/lib/features/in_app_purchase/domain/repositories/in_app_purchase_repository.dart b/lib/features/in_app_purchase/domain/repositories/in_app_purchase_repository.dart new file mode 100644 index 0000000..dcfa10c --- /dev/null +++ b/lib/features/in_app_purchase/domain/repositories/in_app_purchase_repository.dart @@ -0,0 +1,17 @@ +import 'package:fpdart/fpdart.dart'; +import 'package:in_app_purchase/in_app_purchase.dart'; +import 'package:kuwot/core/error/failure.dart'; + +abstract class InAppPurchaseRepository { + Stream> get purchaseStream; + + Future>> getConsumableProducts(); + + Future> purchaseConsumableProduct( + ProductDetails product, + ); + + Future> completePurchase( + PurchaseDetails purchaseDetails, + ); +} diff --git a/lib/features/in_app_purchase/domain/use_case/get_consumable_products.dart b/lib/features/in_app_purchase/domain/use_case/get_consumable_products.dart new file mode 100644 index 0000000..511199c --- /dev/null +++ b/lib/features/in_app_purchase/domain/use_case/get_consumable_products.dart @@ -0,0 +1,17 @@ +import 'package:fpdart/fpdart.dart'; +import 'package:in_app_purchase/in_app_purchase.dart'; +import 'package:kuwot/core/domain/no_params.dart'; +import 'package:kuwot/core/domain/use_case.dart'; +import 'package:kuwot/core/error/failure.dart'; +import 'package:kuwot/features/in_app_purchase/domain/repositories/in_app_purchase_repository.dart'; + +class GetConsumableProducts extends UseCase, NoParams> { + final InAppPurchaseRepository repository; + + GetConsumableProducts(this.repository); + + @override + Future>> call(NoParams params) async { + return repository.getConsumableProducts(); + } +} diff --git a/lib/features/in_app_purchase/domain/use_case/listen_purchase.dart b/lib/features/in_app_purchase/domain/use_case/listen_purchase.dart new file mode 100644 index 0000000..9d291ef --- /dev/null +++ b/lib/features/in_app_purchase/domain/use_case/listen_purchase.dart @@ -0,0 +1,21 @@ +import 'dart:async'; + +import 'package:fpdart/fpdart.dart'; +import 'package:in_app_purchase/in_app_purchase.dart'; +import 'package:kuwot/core/domain/no_params.dart'; +import 'package:kuwot/core/domain/use_case.dart'; +import 'package:kuwot/core/error/failure.dart'; +import 'package:kuwot/features/in_app_purchase/domain/repositories/in_app_purchase_repository.dart'; + +class ListenPurchase + implements UseCase>, NoParams> { + ListenPurchase(this.repository); + + final InAppPurchaseRepository repository; + + @override + Future>>> call(NoParams params) { + // it always return right because I dont think it will throw an error + return Future.value(right(repository.purchaseStream)); + } +} diff --git a/lib/features/in_app_purchase/domain/use_case/purchase_consumable_product.dart b/lib/features/in_app_purchase/domain/use_case/purchase_consumable_product.dart new file mode 100644 index 0000000..a5ddff3 --- /dev/null +++ b/lib/features/in_app_purchase/domain/use_case/purchase_consumable_product.dart @@ -0,0 +1,29 @@ +import 'package:equatable/equatable.dart'; +import 'package:fpdart/fpdart.dart'; +import 'package:in_app_purchase/in_app_purchase.dart'; +import 'package:kuwot/core/domain/use_case.dart'; +import 'package:kuwot/core/error/failure.dart'; +import 'package:kuwot/features/in_app_purchase/domain/repositories/in_app_purchase_repository.dart'; + +class PurchaseConsumableProduct + extends UseCase { + final InAppPurchaseRepository repository; + + PurchaseConsumableProduct(this.repository); + + @override + Future> call( + PurchaseConsumableProductParams params, + ) async { + return repository.purchaseConsumableProduct(params.productDetails); + } +} + +class PurchaseConsumableProductParams extends Equatable { + final ProductDetails productDetails; + + const PurchaseConsumableProductParams({required this.productDetails}); + + @override + List get props => [productDetails]; +} diff --git a/lib/features/in_app_purchase/presentation/bloc/in_app_purchase_bloc.dart b/lib/features/in_app_purchase/presentation/bloc/in_app_purchase_bloc.dart new file mode 100644 index 0000000..2995cb6 --- /dev/null +++ b/lib/features/in_app_purchase/presentation/bloc/in_app_purchase_bloc.dart @@ -0,0 +1,59 @@ +import 'dart:async'; + +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:in_app_purchase/in_app_purchase.dart'; +import 'package:kuwot/core/domain/no_params.dart'; +import 'package:kuwot/core/presentation/bloc/error_state.dart'; +import 'package:kuwot/features/in_app_purchase/domain/use_case/get_consumable_products.dart'; +import 'package:kuwot/features/in_app_purchase/domain/use_case/purchase_consumable_product.dart'; + +part 'in_app_purchase_events.dart'; +part 'in_app_purchase_states.dart'; + +class InAppPurchaseBloc extends Bloc { + InAppPurchaseBloc({ + required this.getConsumableProducts, + required this.purchaseConsumableProduct, + }) : super(const InAppPurchaseInitialState()) { + on(_getConsumableProducts); + on(_purchaseConsumableProduct); + } + + final GetConsumableProducts getConsumableProducts; + final PurchaseConsumableProduct purchaseConsumableProduct; + + Future _getConsumableProducts( + GetConsumableProductsEvent event, + Emitter emit, + ) async { + emit(const GettingConsumableProductsState()); + final result = await getConsumableProducts(const NoParams()); + result.fold( + (failure) { + emit(PurchaseErrorState(message: failure.message)); + }, + (products) { + emit(ConsumableProductsLoadedState(products)); + }, + ); + } + + Future _purchaseConsumableProduct( + PurchaseConsumableProductEvent event, + Emitter emit, + ) async { + emit(PurchasingConsumableProductState(event.productDetails)); + final result = await purchaseConsumableProduct( + PurchaseConsumableProductParams(productDetails: event.productDetails), + ); + result.fold( + (failure) { + emit(PurchaseErrorState(message: failure.message)); + }, + (success) { + emit(ConsumableProductPurchasedState(result: success)); + }, + ); + } +} diff --git a/lib/features/in_app_purchase/presentation/bloc/in_app_purchase_events.dart b/lib/features/in_app_purchase/presentation/bloc/in_app_purchase_events.dart new file mode 100644 index 0000000..be425c6 --- /dev/null +++ b/lib/features/in_app_purchase/presentation/bloc/in_app_purchase_events.dart @@ -0,0 +1,21 @@ +part of 'in_app_purchase_bloc.dart'; + +abstract class InAppPurchaseEvent extends Equatable { + const InAppPurchaseEvent(); +} + +class GetConsumableProductsEvent extends InAppPurchaseEvent { + const GetConsumableProductsEvent(); + + @override + List get props => []; +} + +class PurchaseConsumableProductEvent extends InAppPurchaseEvent { + final ProductDetails productDetails; + + const PurchaseConsumableProductEvent(this.productDetails); + + @override + List get props => [productDetails]; +} diff --git a/lib/features/in_app_purchase/presentation/bloc/in_app_purchase_states.dart b/lib/features/in_app_purchase/presentation/bloc/in_app_purchase_states.dart new file mode 100644 index 0000000..bb01fde --- /dev/null +++ b/lib/features/in_app_purchase/presentation/bloc/in_app_purchase_states.dart @@ -0,0 +1,59 @@ +part of 'in_app_purchase_bloc.dart'; + +abstract class InAppPurchaseState extends Equatable { + const InAppPurchaseState(); +} + +class InAppPurchaseInitialState extends InAppPurchaseState { + const InAppPurchaseInitialState(); + + @override + List get props => []; +} + +class GettingConsumableProductsState extends InAppPurchaseState { + const GettingConsumableProductsState(); + + @override + List get props => []; +} + +class ConsumableProductsLoadedState extends InAppPurchaseState { + final List products; + + const ConsumableProductsLoadedState(this.products); + + @override + List get props => [products]; +} + +class PurchasingConsumableProductState extends InAppPurchaseState { + final ProductDetails productDetails; + + const PurchasingConsumableProductState(this.productDetails); + + @override + List get props => [productDetails]; +} + +class ConsumableProductPurchasedState extends InAppPurchaseState { + const ConsumableProductPurchasedState({required this.result}); + + final bool result; + + @override + List get props => [result]; +} + +class PurchaseErrorState extends InAppPurchaseState implements ErrorState { + @override + final String message; + + @override + final Exception? cause; + + const PurchaseErrorState({required this.message, this.cause}); + + @override + List get props => [message, cause]; +} diff --git a/lib/features/in_app_purchase/presentation/bloc/purchase_details_cubit.dart b/lib/features/in_app_purchase/presentation/bloc/purchase_details_cubit.dart new file mode 100644 index 0000000..0e427d3 --- /dev/null +++ b/lib/features/in_app_purchase/presentation/bloc/purchase_details_cubit.dart @@ -0,0 +1,34 @@ +import 'dart:async'; + +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:in_app_purchase/in_app_purchase.dart'; +import 'package:kuwot/features/in_app_purchase/domain/repositories/in_app_purchase_repository.dart'; + +/// Cubit that listens to purchase details stream from [InAppPurchaseRepository] +class PurchaseDetailsCubit extends Cubit> { + /// Repository to get purchase details stream + final InAppPurchaseRepository repository; + + /// Subscription to purchase details stream + StreamSubscription>? _purchaseDetailsSubscription; + + PurchaseDetailsCubit(this.repository) : super([]) { + // listen to purchase details stream and emit the event to the UI + _purchaseDetailsSubscription = repository.purchaseStream.listen((event) { + emit(event); + + // complete the purchases + event + .where((element) => element.status == PurchaseStatus.purchased) + .forEach((element) { + unawaited(repository.completePurchase(element)); + }); + }); + } + + @override + Future close() { + _purchaseDetailsSubscription?.cancel(); + return super.close(); + } +} diff --git a/lib/features/in_app_purchase/presentation/donation_page.dart b/lib/features/in_app_purchase/presentation/donation_page.dart new file mode 100644 index 0000000..34985ab --- /dev/null +++ b/lib/features/in_app_purchase/presentation/donation_page.dart @@ -0,0 +1,92 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:in_app_purchase/in_app_purchase.dart'; +import 'package:kuwot/features/in_app_purchase/presentation/bloc/in_app_purchase_bloc.dart'; + +@RoutePage() +class DonationPage extends StatefulWidget { + const DonationPage({super.key}); + + @override + State createState() => _DonationPageState(); +} + +class _DonationPageState extends State { + final _donationMessage = + 'I built this app with love and coffee. If you find it useful, please consider buying me a coffee. Your donation will help me keep the app running and updated. Thank you! ☕'; + + final List _products = []; + + @override + void initState() { + super.initState(); + + // get consumable products + context.read().add(const GetConsumableProductsEvent()); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Coffee time?')), + body: BlocListener( + listener: (context, state) { + if (state is ConsumableProductsLoadedState) { + setState(() { + _products.clear(); + _products.addAll(state.products); + }); + } + }, + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 16), + child: Text(_donationMessage), + ), + ..._buildProductList(), + ], + ), + ), + ); + } + + List _buildProductList() { + return _products.map((product) { + final title = product.title.replaceAll('(Kuwot)', ''); + final description = product.description.replaceAll( + RegExp(r'[\r\n]+'), + '', + ); + final productCard = Card( + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () => context.read().add( + PurchaseConsumableProductEvent(product), + ), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(title, style: Theme.of(context).textTheme.bodyLarge), + Text(description), + const SizedBox(height: 8), + Text( + product.price, + style: Theme.of( + context, + ).textTheme.bodySmall?.copyWith(fontWeight: FontWeight.bold), + ), + ], + ), + ), + ), + ); + + return productCard; + }).toList(); + } +} diff --git a/lib/features/in_app_purchase/presentation/in_app_purchase_listener.dart b/lib/features/in_app_purchase/presentation/in_app_purchase_listener.dart new file mode 100644 index 0000000..5e66911 --- /dev/null +++ b/lib/features/in_app_purchase/presentation/in_app_purchase_listener.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:in_app_purchase/in_app_purchase.dart'; +import 'package:kuwot/features/in_app_purchase/presentation/bloc/purchase_details_cubit.dart'; +import 'package:kuwot/utilities.dart'; + +class InAppPurchaseListener extends StatelessWidget { + const InAppPurchaseListener({required this.child, super.key}); + + final Widget child; + + @override + Widget build(BuildContext context) { + return BlocListener>( + listener: (context, state) { + if (state.last.status == PurchaseStatus.purchased) { + showSnackbar('Coffee received, thank you! ☕'); + } + + if (state.last.status == PurchaseStatus.pending) { + showSnackbar('Coffee is on the way! ☕'); + } + + if (state.last.status == PurchaseStatus.error) { + showSnackbar('Something went wrong, failed to send coffee 😢'); + } + }, + child: child, + ); + } +} diff --git a/lib/features/in_app_update/presentation/app_update_page.dart b/lib/features/in_app_update/presentation/app_update_page.dart new file mode 100644 index 0000000..83ba4f7 --- /dev/null +++ b/lib/features/in_app_update/presentation/app_update_page.dart @@ -0,0 +1,58 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_svg/svg.dart'; +import 'package:kuwot/core/router/app_router.gr.dart'; +import 'package:kuwot/features/in_app_update/presentation/bloc/in_app_update_bloc.dart'; + +@RoutePage() +class AppUpdatePage extends StatefulWidget { + const AppUpdatePage({super.key}); + + @override + State createState() => _AppUpdatePageState(); +} + +class _AppUpdatePageState extends State { + @override + void initState() { + // check for update + context.read().add(const InAppUpdateCheckEvent()); + + super.initState(); + } + + @override + Widget build(BuildContext context) { + return BlocListener( + listener: (context, state) { + if (state is InAppUpdateAvailableState) { + context.read().add(const InAppUpdateStartEvent()); + } + + if (state is InAppUpdateUnavailableState) { + AutoRouter.of(context).replace(const QuoteRoute()); + } + }, + child: Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SvgPicture.asset( + 'assets/svgs/chat-quote.svg', + colorFilter: ColorFilter.mode( + Theme.of(context).colorScheme.onSurface, + BlendMode.srcIn, + ), + height: 100, + ), + const SizedBox(height: 20), + const SizedBox(width: 100, child: LinearProgressIndicator()), + ], + ), + ), + ), + ); + } +} diff --git a/lib/features/in_app_update/presentation/bloc/in_app_update_bloc.dart b/lib/features/in_app_update/presentation/bloc/in_app_update_bloc.dart new file mode 100644 index 0000000..94958bb --- /dev/null +++ b/lib/features/in_app_update/presentation/bloc/in_app_update_bloc.dart @@ -0,0 +1,41 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:in_app_update/in_app_update.dart'; +import 'package:kuwot/core/app_updater.dart'; + +part 'in_app_update_bloc_events.dart'; +part 'in_app_update_bloc_states.dart'; + +class InAppUpdateBloc extends Bloc { + InAppUpdateBloc({required this.appUpdater}) + : super(const InAppUpdateInitialState()) { + on(_onInAppUpdateCheckEvent); + on(_onInAppUpdateStartEvent); + } + + final AppUpdater appUpdater; + + Future _onInAppUpdateCheckEvent( + InAppUpdateCheckEvent event, + Emitter emit, + ) async { + try { + emit(const InAppUpdateCheckingState()); + final updateInfo = await appUpdater.checkForUpdate(); + if (updateInfo.updateAvailability == UpdateAvailability.updateAvailable) { + emit(const InAppUpdateAvailableState()); + } else { + emit(const InAppUpdateUnavailableState()); + } + } on Exception catch (_) { + emit(const InAppUpdateUnavailableState()); + } + } + + Future _onInAppUpdateStartEvent( + InAppUpdateStartEvent event, + Emitter emit, + ) async { + await appUpdater.update(); + } +} diff --git a/lib/features/in_app_update/presentation/bloc/in_app_update_bloc_events.dart b/lib/features/in_app_update/presentation/bloc/in_app_update_bloc_events.dart new file mode 100644 index 0000000..ad1671b --- /dev/null +++ b/lib/features/in_app_update/presentation/bloc/in_app_update_bloc_events.dart @@ -0,0 +1,19 @@ +part of 'in_app_update_bloc.dart'; + +abstract class InAppUpdateEvent extends Equatable { + const InAppUpdateEvent(); +} + +class InAppUpdateCheckEvent extends InAppUpdateEvent { + const InAppUpdateCheckEvent(); + + @override + List get props => []; +} + +class InAppUpdateStartEvent extends InAppUpdateEvent { + const InAppUpdateStartEvent(); + + @override + List get props => []; +} diff --git a/lib/features/in_app_update/presentation/bloc/in_app_update_bloc_states.dart b/lib/features/in_app_update/presentation/bloc/in_app_update_bloc_states.dart new file mode 100644 index 0000000..d7280f0 --- /dev/null +++ b/lib/features/in_app_update/presentation/bloc/in_app_update_bloc_states.dart @@ -0,0 +1,33 @@ +part of 'in_app_update_bloc.dart'; + +abstract class InAppUpdateState extends Equatable { + const InAppUpdateState(); +} + +class InAppUpdateInitialState extends InAppUpdateState { + const InAppUpdateInitialState(); + + @override + List get props => []; +} + +class InAppUpdateCheckingState extends InAppUpdateState { + const InAppUpdateCheckingState(); + + @override + List get props => []; +} + +class InAppUpdateAvailableState extends InAppUpdateState { + const InAppUpdateAvailableState(); + + @override + List get props => []; +} + +class InAppUpdateUnavailableState extends InAppUpdateState { + const InAppUpdateUnavailableState(); + + @override + List get props => []; +} diff --git a/lib/features/quote/data/data_sources/remote/kuwot_api_remote_data_source.dart b/lib/features/quote/data/data_sources/remote/kuwot_api_remote_data_source.dart new file mode 100644 index 0000000..b2561da --- /dev/null +++ b/lib/features/quote/data/data_sources/remote/kuwot_api_remote_data_source.dart @@ -0,0 +1,84 @@ +import 'dart:convert'; + +import 'package:kuwot/core/env.dart'; +import 'package:kuwot/core/network/network.dart'; +import 'package:kuwot/features/quote/data/models/image_model.dart'; +import 'package:kuwot/features/quote/data/models/quote_model.dart'; +import 'package:kuwot/features/quote/data/models/translation_model.dart'; + +const imagesPerPage = 10; + +abstract class KuwotApiRemoteDataSource { + Future getQuote({String? query}); + + Future getTranslatedQuote(int id, {String? query}); + + Future> getRandomImages(); + + Future> getTranslations(); +} + +class KuwotApiRemoteApiImpl implements KuwotApiRemoteDataSource { + final Env env; + final Network network; + + KuwotApiRemoteApiImpl({required this.env, required this.network}); + + @override + Future getQuote({String? query}) async { + final uri = Uri( + scheme: env.quoteApiScheme, + host: env.quoteApiHost, + port: env.quoteApiPort, + path: 'kuwot/v1/quotes/random', + query: query, + ); + final response = await network.get(uri); + final jsonResponse = jsonDecode(response) as Map; + return QuoteModel.fromJson(jsonResponse); + } + + @override + Future getTranslatedQuote(int id, {String? query}) async { + final uri = Uri( + scheme: env.quoteApiScheme, + host: env.quoteApiHost, + port: env.quoteApiPort, + path: 'kuwot/v1/quotes/$id', + query: query, + ); + final response = await network.get(uri); + final jsonResponse = jsonDecode(response) as Map; + return QuoteModel.fromJson(jsonResponse); + } + + @override + Future> getRandomImages() async { + final uri = Uri( + scheme: env.quoteApiScheme, + host: env.quoteApiHost, + port: env.quoteApiPort, + path: 'kuwot/v1/images', + ); + final response = await network.get(uri); + final jsonResponse = jsonDecode(response) as List; + return jsonResponse + .map((e) => ImageModel.fromJson(e as Map)) + .toList(); + } + + @override + Future> getTranslations() async { + final uri = Uri( + scheme: env.quoteApiScheme, + host: env.quoteApiHost, + port: env.quoteApiPort, + path: 'kuwot/v1/translations', + ); + final response = await network.get(uri); + final jsonResponse = jsonDecode(response) as List; + return jsonResponse + .map((e) => TranslationModel.fromJson(e as Map)) + .toList(); + } +} diff --git a/lib/features/quote/data/models/image_model.dart b/lib/features/quote/data/models/image_model.dart new file mode 100644 index 0000000..6183f35 --- /dev/null +++ b/lib/features/quote/data/models/image_model.dart @@ -0,0 +1,27 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'image_model.freezed.dart'; +part 'image_model.g.dart'; + +@freezed +abstract class ImageModel with _$ImageModel { + const factory ImageModel({ + required String id, + required String description, + required String color, + required String blurHash, + required String url, + required String originUrl, + required String authorName, + required String authorBio, + required String authorLocation, + required int authorTotalLikes, + required int authorTotalPhotos, + required bool authorIsForHire, + required String authorProfileImageUrl, + required String authorUrl, + }) = _ImageModel; + + factory ImageModel.fromJson(Map json) => + _$ImageModelFromJson(json); +} diff --git a/lib/features/quote/data/models/image_model.freezed.dart b/lib/features/quote/data/models/image_model.freezed.dart new file mode 100644 index 0000000..ddee136 --- /dev/null +++ b/lib/features/quote/data/models/image_model.freezed.dart @@ -0,0 +1,316 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'image_model.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; + +/// @nodoc +mixin _$ImageModel { + + String get id; String get description; String get color; String get blurHash; String get url; String get originUrl; String get authorName; String get authorBio; String get authorLocation; int get authorTotalLikes; int get authorTotalPhotos; bool get authorIsForHire; String get authorProfileImageUrl; String get authorUrl; +/// Create a copy of ImageModel +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$ImageModelCopyWith get copyWith => _$ImageModelCopyWithImpl(this as ImageModel, _$identity); + + /// Serializes this ImageModel to a JSON map. + Map toJson(); + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is ImageModel&&(identical(other.id, id) || other.id == id)&&(identical(other.description, description) || other.description == description)&&(identical(other.color, color) || other.color == color)&&(identical(other.blurHash, blurHash) || other.blurHash == blurHash)&&(identical(other.url, url) || other.url == url)&&(identical(other.originUrl, originUrl) || other.originUrl == originUrl)&&(identical(other.authorName, authorName) || other.authorName == authorName)&&(identical(other.authorBio, authorBio) || other.authorBio == authorBio)&&(identical(other.authorLocation, authorLocation) || other.authorLocation == authorLocation)&&(identical(other.authorTotalLikes, authorTotalLikes) || other.authorTotalLikes == authorTotalLikes)&&(identical(other.authorTotalPhotos, authorTotalPhotos) || other.authorTotalPhotos == authorTotalPhotos)&&(identical(other.authorIsForHire, authorIsForHire) || other.authorIsForHire == authorIsForHire)&&(identical(other.authorProfileImageUrl, authorProfileImageUrl) || other.authorProfileImageUrl == authorProfileImageUrl)&&(identical(other.authorUrl, authorUrl) || other.authorUrl == authorUrl)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,id,description,color,blurHash,url,originUrl,authorName,authorBio,authorLocation,authorTotalLikes,authorTotalPhotos,authorIsForHire,authorProfileImageUrl,authorUrl); + +@override +String toString() { + return 'ImageModel(id: $id, description: $description, color: $color, blurHash: $blurHash, url: $url, originUrl: $originUrl, authorName: $authorName, authorBio: $authorBio, authorLocation: $authorLocation, authorTotalLikes: $authorTotalLikes, authorTotalPhotos: $authorTotalPhotos, authorIsForHire: $authorIsForHire, authorProfileImageUrl: $authorProfileImageUrl, authorUrl: $authorUrl)'; +} + + +} + +/// @nodoc +abstract mixin class $ImageModelCopyWith<$Res> { + factory $ImageModelCopyWith(ImageModel value, $Res Function(ImageModel) _then) = _$ImageModelCopyWithImpl; +@useResult +$Res call({ + String id, String description, String color, String blurHash, String url, String originUrl, String authorName, String authorBio, String authorLocation, int authorTotalLikes, int authorTotalPhotos, bool authorIsForHire, String authorProfileImageUrl, String authorUrl +}); + + + + +} +/// @nodoc +class _$ImageModelCopyWithImpl<$Res> + implements $ImageModelCopyWith<$Res> { + _$ImageModelCopyWithImpl(this._self, this._then); + + final ImageModel _self; + final $Res Function(ImageModel) _then; + +/// Create a copy of ImageModel +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? description = null,Object? color = null,Object? blurHash = null,Object? url = null,Object? originUrl = null,Object? authorName = null,Object? authorBio = null,Object? authorLocation = null,Object? authorTotalLikes = null,Object? authorTotalPhotos = null,Object? authorIsForHire = null,Object? authorProfileImageUrl = null,Object? authorUrl = null,}) { + return _then(_self.copyWith( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as String,description: null == description ? _self.description : description // ignore: cast_nullable_to_non_nullable +as String,color: null == color ? _self.color : color // ignore: cast_nullable_to_non_nullable +as String,blurHash: null == blurHash ? _self.blurHash : blurHash // ignore: cast_nullable_to_non_nullable +as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable +as String,originUrl: null == originUrl ? _self.originUrl : originUrl // ignore: cast_nullable_to_non_nullable +as String,authorName: null == authorName ? _self.authorName : authorName // ignore: cast_nullable_to_non_nullable +as String,authorBio: null == authorBio ? _self.authorBio : authorBio // ignore: cast_nullable_to_non_nullable +as String,authorLocation: null == authorLocation ? _self.authorLocation : authorLocation // ignore: cast_nullable_to_non_nullable +as String,authorTotalLikes: null == authorTotalLikes ? _self.authorTotalLikes : authorTotalLikes // ignore: cast_nullable_to_non_nullable +as int,authorTotalPhotos: null == authorTotalPhotos ? _self.authorTotalPhotos : authorTotalPhotos // ignore: cast_nullable_to_non_nullable +as int,authorIsForHire: null == authorIsForHire ? _self.authorIsForHire : authorIsForHire // ignore: cast_nullable_to_non_nullable +as bool,authorProfileImageUrl: null == authorProfileImageUrl ? _self.authorProfileImageUrl : authorProfileImageUrl // ignore: cast_nullable_to_non_nullable +as String,authorUrl: null == authorUrl ? _self.authorUrl : authorUrl // ignore: cast_nullable_to_non_nullable +as String, + )); +} + +} + + +/// Adds pattern-matching-related methods to [ImageModel]. +extension ImageModelPatterns on ImageModel { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _ImageModel value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _ImageModel() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _ImageModel value) $default,){ +final _that = this; +switch (_that) { +case _ImageModel(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _ImageModel value)? $default,){ +final _that = this; +switch (_that) { +case _ImageModel() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( String id, String description, String color, String blurHash, String url, String originUrl, String authorName, String authorBio, String authorLocation, int authorTotalLikes, int authorTotalPhotos, bool authorIsForHire, String authorProfileImageUrl, String authorUrl)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _ImageModel() when $default != null: +return $default(_that.id,_that.description,_that.color,_that.blurHash,_that.url,_that.originUrl,_that.authorName,_that.authorBio,_that.authorLocation,_that.authorTotalLikes,_that.authorTotalPhotos,_that.authorIsForHire,_that.authorProfileImageUrl,_that.authorUrl);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( String id, String description, String color, String blurHash, String url, String originUrl, String authorName, String authorBio, String authorLocation, int authorTotalLikes, int authorTotalPhotos, bool authorIsForHire, String authorProfileImageUrl, String authorUrl) $default,) {final _that = this; +switch (_that) { +case _ImageModel(): +return $default(_that.id,_that.description,_that.color,_that.blurHash,_that.url,_that.originUrl,_that.authorName,_that.authorBio,_that.authorLocation,_that.authorTotalLikes,_that.authorTotalPhotos,_that.authorIsForHire,_that.authorProfileImageUrl,_that.authorUrl);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String id, String description, String color, String blurHash, String url, String originUrl, String authorName, String authorBio, String authorLocation, int authorTotalLikes, int authorTotalPhotos, bool authorIsForHire, String authorProfileImageUrl, String authorUrl)? $default,) {final _that = this; +switch (_that) { +case _ImageModel() when $default != null: +return $default(_that.id,_that.description,_that.color,_that.blurHash,_that.url,_that.originUrl,_that.authorName,_that.authorBio,_that.authorLocation,_that.authorTotalLikes,_that.authorTotalPhotos,_that.authorIsForHire,_that.authorProfileImageUrl,_that.authorUrl);case _: + return null; + +} +} + +} + +/// @nodoc +@JsonSerializable() + +class _ImageModel implements ImageModel { + const _ImageModel({required this.id, required this.description, required this.color, required this.blurHash, required this.url, required this.originUrl, required this.authorName, required this.authorBio, required this.authorLocation, required this.authorTotalLikes, required this.authorTotalPhotos, required this.authorIsForHire, required this.authorProfileImageUrl, required this.authorUrl}); + factory _ImageModel.fromJson(Map json) => _$ImageModelFromJson(json); + +@override final String id; +@override final String description; +@override final String color; +@override final String blurHash; +@override final String url; +@override final String originUrl; +@override final String authorName; +@override final String authorBio; +@override final String authorLocation; +@override final int authorTotalLikes; +@override final int authorTotalPhotos; +@override final bool authorIsForHire; +@override final String authorProfileImageUrl; +@override final String authorUrl; + +/// Create a copy of ImageModel +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$ImageModelCopyWith<_ImageModel> get copyWith => __$ImageModelCopyWithImpl<_ImageModel>(this, _$identity); + +@override +Map toJson() { + return _$ImageModelToJson(this, ); +} + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _ImageModel&&(identical(other.id, id) || other.id == id)&&(identical(other.description, description) || other.description == description)&&(identical(other.color, color) || other.color == color)&&(identical(other.blurHash, blurHash) || other.blurHash == blurHash)&&(identical(other.url, url) || other.url == url)&&(identical(other.originUrl, originUrl) || other.originUrl == originUrl)&&(identical(other.authorName, authorName) || other.authorName == authorName)&&(identical(other.authorBio, authorBio) || other.authorBio == authorBio)&&(identical(other.authorLocation, authorLocation) || other.authorLocation == authorLocation)&&(identical(other.authorTotalLikes, authorTotalLikes) || other.authorTotalLikes == authorTotalLikes)&&(identical(other.authorTotalPhotos, authorTotalPhotos) || other.authorTotalPhotos == authorTotalPhotos)&&(identical(other.authorIsForHire, authorIsForHire) || other.authorIsForHire == authorIsForHire)&&(identical(other.authorProfileImageUrl, authorProfileImageUrl) || other.authorProfileImageUrl == authorProfileImageUrl)&&(identical(other.authorUrl, authorUrl) || other.authorUrl == authorUrl)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,id,description,color,blurHash,url,originUrl,authorName,authorBio,authorLocation,authorTotalLikes,authorTotalPhotos,authorIsForHire,authorProfileImageUrl,authorUrl); + +@override +String toString() { + return 'ImageModel(id: $id, description: $description, color: $color, blurHash: $blurHash, url: $url, originUrl: $originUrl, authorName: $authorName, authorBio: $authorBio, authorLocation: $authorLocation, authorTotalLikes: $authorTotalLikes, authorTotalPhotos: $authorTotalPhotos, authorIsForHire: $authorIsForHire, authorProfileImageUrl: $authorProfileImageUrl, authorUrl: $authorUrl)'; +} + + +} + +/// @nodoc +abstract mixin class _$ImageModelCopyWith<$Res> implements $ImageModelCopyWith<$Res> { + factory _$ImageModelCopyWith(_ImageModel value, $Res Function(_ImageModel) _then) = __$ImageModelCopyWithImpl; +@override @useResult +$Res call({ + String id, String description, String color, String blurHash, String url, String originUrl, String authorName, String authorBio, String authorLocation, int authorTotalLikes, int authorTotalPhotos, bool authorIsForHire, String authorProfileImageUrl, String authorUrl +}); + + + + +} +/// @nodoc +class __$ImageModelCopyWithImpl<$Res> + implements _$ImageModelCopyWith<$Res> { + __$ImageModelCopyWithImpl(this._self, this._then); + + final _ImageModel _self; + final $Res Function(_ImageModel) _then; + +/// Create a copy of ImageModel +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? description = null,Object? color = null,Object? blurHash = null,Object? url = null,Object? originUrl = null,Object? authorName = null,Object? authorBio = null,Object? authorLocation = null,Object? authorTotalLikes = null,Object? authorTotalPhotos = null,Object? authorIsForHire = null,Object? authorProfileImageUrl = null,Object? authorUrl = null,}) { + return _then(_ImageModel( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as String,description: null == description ? _self.description : description // ignore: cast_nullable_to_non_nullable +as String,color: null == color ? _self.color : color // ignore: cast_nullable_to_non_nullable +as String,blurHash: null == blurHash ? _self.blurHash : blurHash // ignore: cast_nullable_to_non_nullable +as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable +as String,originUrl: null == originUrl ? _self.originUrl : originUrl // ignore: cast_nullable_to_non_nullable +as String,authorName: null == authorName ? _self.authorName : authorName // ignore: cast_nullable_to_non_nullable +as String,authorBio: null == authorBio ? _self.authorBio : authorBio // ignore: cast_nullable_to_non_nullable +as String,authorLocation: null == authorLocation ? _self.authorLocation : authorLocation // ignore: cast_nullable_to_non_nullable +as String,authorTotalLikes: null == authorTotalLikes ? _self.authorTotalLikes : authorTotalLikes // ignore: cast_nullable_to_non_nullable +as int,authorTotalPhotos: null == authorTotalPhotos ? _self.authorTotalPhotos : authorTotalPhotos // ignore: cast_nullable_to_non_nullable +as int,authorIsForHire: null == authorIsForHire ? _self.authorIsForHire : authorIsForHire // ignore: cast_nullable_to_non_nullable +as bool,authorProfileImageUrl: null == authorProfileImageUrl ? _self.authorProfileImageUrl : authorProfileImageUrl // ignore: cast_nullable_to_non_nullable +as String,authorUrl: null == authorUrl ? _self.authorUrl : authorUrl // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +// dart format on diff --git a/lib/features/quote/data/models/image_model.g.dart b/lib/features/quote/data/models/image_model.g.dart new file mode 100644 index 0000000..1e9996c --- /dev/null +++ b/lib/features/quote/data/models/image_model.g.dart @@ -0,0 +1,42 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'image_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_ImageModel _$ImageModelFromJson(Map json) => _ImageModel( + id: json['id'] as String, + description: json['description'] as String, + color: json['color'] as String, + blurHash: json['blurHash'] as String, + url: json['url'] as String, + originUrl: json['originUrl'] as String, + authorName: json['authorName'] as String, + authorBio: json['authorBio'] as String, + authorLocation: json['authorLocation'] as String, + authorTotalLikes: (json['authorTotalLikes'] as num).toInt(), + authorTotalPhotos: (json['authorTotalPhotos'] as num).toInt(), + authorIsForHire: json['authorIsForHire'] as bool, + authorProfileImageUrl: json['authorProfileImageUrl'] as String, + authorUrl: json['authorUrl'] as String, +); + +Map _$ImageModelToJson(_ImageModel instance) => + { + 'id': instance.id, + 'description': instance.description, + 'color': instance.color, + 'blurHash': instance.blurHash, + 'url': instance.url, + 'originUrl': instance.originUrl, + 'authorName': instance.authorName, + 'authorBio': instance.authorBio, + 'authorLocation': instance.authorLocation, + 'authorTotalLikes': instance.authorTotalLikes, + 'authorTotalPhotos': instance.authorTotalPhotos, + 'authorIsForHire': instance.authorIsForHire, + 'authorProfileImageUrl': instance.authorProfileImageUrl, + 'authorUrl': instance.authorUrl, + }; diff --git a/lib/features/quote/data/models/photo_list_model.dart b/lib/features/quote/data/models/photo_list_model.dart new file mode 100644 index 0000000..7c0ecbf --- /dev/null +++ b/lib/features/quote/data/models/photo_list_model.dart @@ -0,0 +1,58 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'photo_list_model.freezed.dart'; +part 'photo_list_model.g.dart'; + +@freezed +abstract class PhotoListModel with _$PhotoListModel { + @JsonSerializable(fieldRename: FieldRename.snake) + const factory PhotoListModel({ + required int page, + required int perPage, + required List photos, + required int totalResults, + required String nextPage, + }) = _PhotoListModel; + + factory PhotoListModel.fromJson(Map json) => + _$PhotoListModelFromJson(json); +} + +@freezed +abstract class PhotoModel with _$PhotoModel { + @JsonSerializable(fieldRename: FieldRename.snake) + const factory PhotoModel({ + required int id, + required int width, + required int height, + required String url, + required String photographer, + required String photographerUrl, + required int photographerId, + required String avgColor, + required SrcModel src, + required bool liked, + required String alt, + }) = _PhotoModel; + + factory PhotoModel.fromJson(Map json) => + _$PhotoModelFromJson(json); +} + +@freezed +abstract class SrcModel with _$SrcModel { + @JsonSerializable(fieldRename: FieldRename.snake) + const factory SrcModel({ + required String original, + required String large2x, + required String large, + required String medium, + required String small, + required String portrait, + required String landscape, + required String tiny, + }) = _SrcModel; + + factory SrcModel.fromJson(Map json) => + _$SrcModelFromJson(json); +} diff --git a/lib/features/quote/data/models/photo_list_model.freezed.dart b/lib/features/quote/data/models/photo_list_model.freezed.dart new file mode 100644 index 0000000..b951b37 --- /dev/null +++ b/lib/features/quote/data/models/photo_list_model.freezed.dart @@ -0,0 +1,890 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'photo_list_model.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; + +/// @nodoc +mixin _$PhotoListModel { + + int get page; int get perPage; List get photos; int get totalResults; String get nextPage; +/// Create a copy of PhotoListModel +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$PhotoListModelCopyWith get copyWith => _$PhotoListModelCopyWithImpl(this as PhotoListModel, _$identity); + + /// Serializes this PhotoListModel to a JSON map. + Map toJson(); + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is PhotoListModel&&(identical(other.page, page) || other.page == page)&&(identical(other.perPage, perPage) || other.perPage == perPage)&&const DeepCollectionEquality().equals(other.photos, photos)&&(identical(other.totalResults, totalResults) || other.totalResults == totalResults)&&(identical(other.nextPage, nextPage) || other.nextPage == nextPage)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,page,perPage,const DeepCollectionEquality().hash(photos),totalResults,nextPage); + +@override +String toString() { + return 'PhotoListModel(page: $page, perPage: $perPage, photos: $photos, totalResults: $totalResults, nextPage: $nextPage)'; +} + + +} + +/// @nodoc +abstract mixin class $PhotoListModelCopyWith<$Res> { + factory $PhotoListModelCopyWith(PhotoListModel value, $Res Function(PhotoListModel) _then) = _$PhotoListModelCopyWithImpl; +@useResult +$Res call({ + int page, int perPage, List photos, int totalResults, String nextPage +}); + + + + +} +/// @nodoc +class _$PhotoListModelCopyWithImpl<$Res> + implements $PhotoListModelCopyWith<$Res> { + _$PhotoListModelCopyWithImpl(this._self, this._then); + + final PhotoListModel _self; + final $Res Function(PhotoListModel) _then; + +/// Create a copy of PhotoListModel +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? page = null,Object? perPage = null,Object? photos = null,Object? totalResults = null,Object? nextPage = null,}) { + return _then(_self.copyWith( +page: null == page ? _self.page : page // ignore: cast_nullable_to_non_nullable +as int,perPage: null == perPage ? _self.perPage : perPage // ignore: cast_nullable_to_non_nullable +as int,photos: null == photos ? _self.photos : photos // ignore: cast_nullable_to_non_nullable +as List,totalResults: null == totalResults ? _self.totalResults : totalResults // ignore: cast_nullable_to_non_nullable +as int,nextPage: null == nextPage ? _self.nextPage : nextPage // ignore: cast_nullable_to_non_nullable +as String, + )); +} + +} + + +/// Adds pattern-matching-related methods to [PhotoListModel]. +extension PhotoListModelPatterns on PhotoListModel { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _PhotoListModel value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _PhotoListModel() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _PhotoListModel value) $default,){ +final _that = this; +switch (_that) { +case _PhotoListModel(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _PhotoListModel value)? $default,){ +final _that = this; +switch (_that) { +case _PhotoListModel() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( int page, int perPage, List photos, int totalResults, String nextPage)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _PhotoListModel() when $default != null: +return $default(_that.page,_that.perPage,_that.photos,_that.totalResults,_that.nextPage);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( int page, int perPage, List photos, int totalResults, String nextPage) $default,) {final _that = this; +switch (_that) { +case _PhotoListModel(): +return $default(_that.page,_that.perPage,_that.photos,_that.totalResults,_that.nextPage);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( int page, int perPage, List photos, int totalResults, String nextPage)? $default,) {final _that = this; +switch (_that) { +case _PhotoListModel() when $default != null: +return $default(_that.page,_that.perPage,_that.photos,_that.totalResults,_that.nextPage);case _: + return null; + +} +} + +} + +/// @nodoc + +@JsonSerializable(fieldRename: FieldRename.snake) +class _PhotoListModel implements PhotoListModel { + const _PhotoListModel({required this.page, required this.perPage, required final List photos, required this.totalResults, required this.nextPage}): _photos = photos; + factory _PhotoListModel.fromJson(Map json) => _$PhotoListModelFromJson(json); + +@override final int page; +@override final int perPage; + final List _photos; +@override List get photos { + if (_photos is EqualUnmodifiableListView) return _photos; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_photos); +} + +@override final int totalResults; +@override final String nextPage; + +/// Create a copy of PhotoListModel +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$PhotoListModelCopyWith<_PhotoListModel> get copyWith => __$PhotoListModelCopyWithImpl<_PhotoListModel>(this, _$identity); + +@override +Map toJson() { + return _$PhotoListModelToJson(this, ); +} + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _PhotoListModel&&(identical(other.page, page) || other.page == page)&&(identical(other.perPage, perPage) || other.perPage == perPage)&&const DeepCollectionEquality().equals(other._photos, _photos)&&(identical(other.totalResults, totalResults) || other.totalResults == totalResults)&&(identical(other.nextPage, nextPage) || other.nextPage == nextPage)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,page,perPage,const DeepCollectionEquality().hash(_photos),totalResults,nextPage); + +@override +String toString() { + return 'PhotoListModel(page: $page, perPage: $perPage, photos: $photos, totalResults: $totalResults, nextPage: $nextPage)'; +} + + +} + +/// @nodoc +abstract mixin class _$PhotoListModelCopyWith<$Res> implements $PhotoListModelCopyWith<$Res> { + factory _$PhotoListModelCopyWith(_PhotoListModel value, $Res Function(_PhotoListModel) _then) = __$PhotoListModelCopyWithImpl; +@override @useResult +$Res call({ + int page, int perPage, List photos, int totalResults, String nextPage +}); + + + + +} +/// @nodoc +class __$PhotoListModelCopyWithImpl<$Res> + implements _$PhotoListModelCopyWith<$Res> { + __$PhotoListModelCopyWithImpl(this._self, this._then); + + final _PhotoListModel _self; + final $Res Function(_PhotoListModel) _then; + +/// Create a copy of PhotoListModel +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? page = null,Object? perPage = null,Object? photos = null,Object? totalResults = null,Object? nextPage = null,}) { + return _then(_PhotoListModel( +page: null == page ? _self.page : page // ignore: cast_nullable_to_non_nullable +as int,perPage: null == perPage ? _self.perPage : perPage // ignore: cast_nullable_to_non_nullable +as int,photos: null == photos ? _self._photos : photos // ignore: cast_nullable_to_non_nullable +as List,totalResults: null == totalResults ? _self.totalResults : totalResults // ignore: cast_nullable_to_non_nullable +as int,nextPage: null == nextPage ? _self.nextPage : nextPage // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + + +/// @nodoc +mixin _$PhotoModel { + + int get id; int get width; int get height; String get url; String get photographer; String get photographerUrl; int get photographerId; String get avgColor; SrcModel get src; bool get liked; String get alt; +/// Create a copy of PhotoModel +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$PhotoModelCopyWith get copyWith => _$PhotoModelCopyWithImpl(this as PhotoModel, _$identity); + + /// Serializes this PhotoModel to a JSON map. + Map toJson(); + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is PhotoModel&&(identical(other.id, id) || other.id == id)&&(identical(other.width, width) || other.width == width)&&(identical(other.height, height) || other.height == height)&&(identical(other.url, url) || other.url == url)&&(identical(other.photographer, photographer) || other.photographer == photographer)&&(identical(other.photographerUrl, photographerUrl) || other.photographerUrl == photographerUrl)&&(identical(other.photographerId, photographerId) || other.photographerId == photographerId)&&(identical(other.avgColor, avgColor) || other.avgColor == avgColor)&&(identical(other.src, src) || other.src == src)&&(identical(other.liked, liked) || other.liked == liked)&&(identical(other.alt, alt) || other.alt == alt)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,id,width,height,url,photographer,photographerUrl,photographerId,avgColor,src,liked,alt); + +@override +String toString() { + return 'PhotoModel(id: $id, width: $width, height: $height, url: $url, photographer: $photographer, photographerUrl: $photographerUrl, photographerId: $photographerId, avgColor: $avgColor, src: $src, liked: $liked, alt: $alt)'; +} + + +} + +/// @nodoc +abstract mixin class $PhotoModelCopyWith<$Res> { + factory $PhotoModelCopyWith(PhotoModel value, $Res Function(PhotoModel) _then) = _$PhotoModelCopyWithImpl; +@useResult +$Res call({ + int id, int width, int height, String url, String photographer, String photographerUrl, int photographerId, String avgColor, SrcModel src, bool liked, String alt +}); + + +$SrcModelCopyWith<$Res> get src; + +} +/// @nodoc +class _$PhotoModelCopyWithImpl<$Res> + implements $PhotoModelCopyWith<$Res> { + _$PhotoModelCopyWithImpl(this._self, this._then); + + final PhotoModel _self; + final $Res Function(PhotoModel) _then; + +/// Create a copy of PhotoModel +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? width = null,Object? height = null,Object? url = null,Object? photographer = null,Object? photographerUrl = null,Object? photographerId = null,Object? avgColor = null,Object? src = null,Object? liked = null,Object? alt = null,}) { + return _then(_self.copyWith( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as int,width: null == width ? _self.width : width // ignore: cast_nullable_to_non_nullable +as int,height: null == height ? _self.height : height // ignore: cast_nullable_to_non_nullable +as int,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable +as String,photographer: null == photographer ? _self.photographer : photographer // ignore: cast_nullable_to_non_nullable +as String,photographerUrl: null == photographerUrl ? _self.photographerUrl : photographerUrl // ignore: cast_nullable_to_non_nullable +as String,photographerId: null == photographerId ? _self.photographerId : photographerId // ignore: cast_nullable_to_non_nullable +as int,avgColor: null == avgColor ? _self.avgColor : avgColor // ignore: cast_nullable_to_non_nullable +as String,src: null == src ? _self.src : src // ignore: cast_nullable_to_non_nullable +as SrcModel,liked: null == liked ? _self.liked : liked // ignore: cast_nullable_to_non_nullable +as bool,alt: null == alt ? _self.alt : alt // ignore: cast_nullable_to_non_nullable +as String, + )); +} +/// Create a copy of PhotoModel +/// with the given fields replaced by the non-null parameter values. +@override +@pragma('vm:prefer-inline') +$SrcModelCopyWith<$Res> get src { + + return $SrcModelCopyWith<$Res>(_self.src, (value) { + return _then(_self.copyWith(src: value)); + }); +} +} + + +/// Adds pattern-matching-related methods to [PhotoModel]. +extension PhotoModelPatterns on PhotoModel { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _PhotoModel value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _PhotoModel() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _PhotoModel value) $default,){ +final _that = this; +switch (_that) { +case _PhotoModel(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _PhotoModel value)? $default,){ +final _that = this; +switch (_that) { +case _PhotoModel() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( int id, int width, int height, String url, String photographer, String photographerUrl, int photographerId, String avgColor, SrcModel src, bool liked, String alt)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _PhotoModel() when $default != null: +return $default(_that.id,_that.width,_that.height,_that.url,_that.photographer,_that.photographerUrl,_that.photographerId,_that.avgColor,_that.src,_that.liked,_that.alt);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( int id, int width, int height, String url, String photographer, String photographerUrl, int photographerId, String avgColor, SrcModel src, bool liked, String alt) $default,) {final _that = this; +switch (_that) { +case _PhotoModel(): +return $default(_that.id,_that.width,_that.height,_that.url,_that.photographer,_that.photographerUrl,_that.photographerId,_that.avgColor,_that.src,_that.liked,_that.alt);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( int id, int width, int height, String url, String photographer, String photographerUrl, int photographerId, String avgColor, SrcModel src, bool liked, String alt)? $default,) {final _that = this; +switch (_that) { +case _PhotoModel() when $default != null: +return $default(_that.id,_that.width,_that.height,_that.url,_that.photographer,_that.photographerUrl,_that.photographerId,_that.avgColor,_that.src,_that.liked,_that.alt);case _: + return null; + +} +} + +} + +/// @nodoc + +@JsonSerializable(fieldRename: FieldRename.snake) +class _PhotoModel implements PhotoModel { + const _PhotoModel({required this.id, required this.width, required this.height, required this.url, required this.photographer, required this.photographerUrl, required this.photographerId, required this.avgColor, required this.src, required this.liked, required this.alt}); + factory _PhotoModel.fromJson(Map json) => _$PhotoModelFromJson(json); + +@override final int id; +@override final int width; +@override final int height; +@override final String url; +@override final String photographer; +@override final String photographerUrl; +@override final int photographerId; +@override final String avgColor; +@override final SrcModel src; +@override final bool liked; +@override final String alt; + +/// Create a copy of PhotoModel +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$PhotoModelCopyWith<_PhotoModel> get copyWith => __$PhotoModelCopyWithImpl<_PhotoModel>(this, _$identity); + +@override +Map toJson() { + return _$PhotoModelToJson(this, ); +} + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _PhotoModel&&(identical(other.id, id) || other.id == id)&&(identical(other.width, width) || other.width == width)&&(identical(other.height, height) || other.height == height)&&(identical(other.url, url) || other.url == url)&&(identical(other.photographer, photographer) || other.photographer == photographer)&&(identical(other.photographerUrl, photographerUrl) || other.photographerUrl == photographerUrl)&&(identical(other.photographerId, photographerId) || other.photographerId == photographerId)&&(identical(other.avgColor, avgColor) || other.avgColor == avgColor)&&(identical(other.src, src) || other.src == src)&&(identical(other.liked, liked) || other.liked == liked)&&(identical(other.alt, alt) || other.alt == alt)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,id,width,height,url,photographer,photographerUrl,photographerId,avgColor,src,liked,alt); + +@override +String toString() { + return 'PhotoModel(id: $id, width: $width, height: $height, url: $url, photographer: $photographer, photographerUrl: $photographerUrl, photographerId: $photographerId, avgColor: $avgColor, src: $src, liked: $liked, alt: $alt)'; +} + + +} + +/// @nodoc +abstract mixin class _$PhotoModelCopyWith<$Res> implements $PhotoModelCopyWith<$Res> { + factory _$PhotoModelCopyWith(_PhotoModel value, $Res Function(_PhotoModel) _then) = __$PhotoModelCopyWithImpl; +@override @useResult +$Res call({ + int id, int width, int height, String url, String photographer, String photographerUrl, int photographerId, String avgColor, SrcModel src, bool liked, String alt +}); + + +@override $SrcModelCopyWith<$Res> get src; + +} +/// @nodoc +class __$PhotoModelCopyWithImpl<$Res> + implements _$PhotoModelCopyWith<$Res> { + __$PhotoModelCopyWithImpl(this._self, this._then); + + final _PhotoModel _self; + final $Res Function(_PhotoModel) _then; + +/// Create a copy of PhotoModel +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? width = null,Object? height = null,Object? url = null,Object? photographer = null,Object? photographerUrl = null,Object? photographerId = null,Object? avgColor = null,Object? src = null,Object? liked = null,Object? alt = null,}) { + return _then(_PhotoModel( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as int,width: null == width ? _self.width : width // ignore: cast_nullable_to_non_nullable +as int,height: null == height ? _self.height : height // ignore: cast_nullable_to_non_nullable +as int,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable +as String,photographer: null == photographer ? _self.photographer : photographer // ignore: cast_nullable_to_non_nullable +as String,photographerUrl: null == photographerUrl ? _self.photographerUrl : photographerUrl // ignore: cast_nullable_to_non_nullable +as String,photographerId: null == photographerId ? _self.photographerId : photographerId // ignore: cast_nullable_to_non_nullable +as int,avgColor: null == avgColor ? _self.avgColor : avgColor // ignore: cast_nullable_to_non_nullable +as String,src: null == src ? _self.src : src // ignore: cast_nullable_to_non_nullable +as SrcModel,liked: null == liked ? _self.liked : liked // ignore: cast_nullable_to_non_nullable +as bool,alt: null == alt ? _self.alt : alt // ignore: cast_nullable_to_non_nullable +as String, + )); +} + +/// Create a copy of PhotoModel +/// with the given fields replaced by the non-null parameter values. +@override +@pragma('vm:prefer-inline') +$SrcModelCopyWith<$Res> get src { + + return $SrcModelCopyWith<$Res>(_self.src, (value) { + return _then(_self.copyWith(src: value)); + }); +} +} + + +/// @nodoc +mixin _$SrcModel { + + String get original; String get large2x; String get large; String get medium; String get small; String get portrait; String get landscape; String get tiny; +/// Create a copy of SrcModel +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$SrcModelCopyWith get copyWith => _$SrcModelCopyWithImpl(this as SrcModel, _$identity); + + /// Serializes this SrcModel to a JSON map. + Map toJson(); + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is SrcModel&&(identical(other.original, original) || other.original == original)&&(identical(other.large2x, large2x) || other.large2x == large2x)&&(identical(other.large, large) || other.large == large)&&(identical(other.medium, medium) || other.medium == medium)&&(identical(other.small, small) || other.small == small)&&(identical(other.portrait, portrait) || other.portrait == portrait)&&(identical(other.landscape, landscape) || other.landscape == landscape)&&(identical(other.tiny, tiny) || other.tiny == tiny)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,original,large2x,large,medium,small,portrait,landscape,tiny); + +@override +String toString() { + return 'SrcModel(original: $original, large2x: $large2x, large: $large, medium: $medium, small: $small, portrait: $portrait, landscape: $landscape, tiny: $tiny)'; +} + + +} + +/// @nodoc +abstract mixin class $SrcModelCopyWith<$Res> { + factory $SrcModelCopyWith(SrcModel value, $Res Function(SrcModel) _then) = _$SrcModelCopyWithImpl; +@useResult +$Res call({ + String original, String large2x, String large, String medium, String small, String portrait, String landscape, String tiny +}); + + + + +} +/// @nodoc +class _$SrcModelCopyWithImpl<$Res> + implements $SrcModelCopyWith<$Res> { + _$SrcModelCopyWithImpl(this._self, this._then); + + final SrcModel _self; + final $Res Function(SrcModel) _then; + +/// Create a copy of SrcModel +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? original = null,Object? large2x = null,Object? large = null,Object? medium = null,Object? small = null,Object? portrait = null,Object? landscape = null,Object? tiny = null,}) { + return _then(_self.copyWith( +original: null == original ? _self.original : original // ignore: cast_nullable_to_non_nullable +as String,large2x: null == large2x ? _self.large2x : large2x // ignore: cast_nullable_to_non_nullable +as String,large: null == large ? _self.large : large // ignore: cast_nullable_to_non_nullable +as String,medium: null == medium ? _self.medium : medium // ignore: cast_nullable_to_non_nullable +as String,small: null == small ? _self.small : small // ignore: cast_nullable_to_non_nullable +as String,portrait: null == portrait ? _self.portrait : portrait // ignore: cast_nullable_to_non_nullable +as String,landscape: null == landscape ? _self.landscape : landscape // ignore: cast_nullable_to_non_nullable +as String,tiny: null == tiny ? _self.tiny : tiny // ignore: cast_nullable_to_non_nullable +as String, + )); +} + +} + + +/// Adds pattern-matching-related methods to [SrcModel]. +extension SrcModelPatterns on SrcModel { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _SrcModel value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _SrcModel() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _SrcModel value) $default,){ +final _that = this; +switch (_that) { +case _SrcModel(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _SrcModel value)? $default,){ +final _that = this; +switch (_that) { +case _SrcModel() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( String original, String large2x, String large, String medium, String small, String portrait, String landscape, String tiny)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _SrcModel() when $default != null: +return $default(_that.original,_that.large2x,_that.large,_that.medium,_that.small,_that.portrait,_that.landscape,_that.tiny);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( String original, String large2x, String large, String medium, String small, String portrait, String landscape, String tiny) $default,) {final _that = this; +switch (_that) { +case _SrcModel(): +return $default(_that.original,_that.large2x,_that.large,_that.medium,_that.small,_that.portrait,_that.landscape,_that.tiny);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String original, String large2x, String large, String medium, String small, String portrait, String landscape, String tiny)? $default,) {final _that = this; +switch (_that) { +case _SrcModel() when $default != null: +return $default(_that.original,_that.large2x,_that.large,_that.medium,_that.small,_that.portrait,_that.landscape,_that.tiny);case _: + return null; + +} +} + +} + +/// @nodoc + +@JsonSerializable(fieldRename: FieldRename.snake) +class _SrcModel implements SrcModel { + const _SrcModel({required this.original, required this.large2x, required this.large, required this.medium, required this.small, required this.portrait, required this.landscape, required this.tiny}); + factory _SrcModel.fromJson(Map json) => _$SrcModelFromJson(json); + +@override final String original; +@override final String large2x; +@override final String large; +@override final String medium; +@override final String small; +@override final String portrait; +@override final String landscape; +@override final String tiny; + +/// Create a copy of SrcModel +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$SrcModelCopyWith<_SrcModel> get copyWith => __$SrcModelCopyWithImpl<_SrcModel>(this, _$identity); + +@override +Map toJson() { + return _$SrcModelToJson(this, ); +} + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _SrcModel&&(identical(other.original, original) || other.original == original)&&(identical(other.large2x, large2x) || other.large2x == large2x)&&(identical(other.large, large) || other.large == large)&&(identical(other.medium, medium) || other.medium == medium)&&(identical(other.small, small) || other.small == small)&&(identical(other.portrait, portrait) || other.portrait == portrait)&&(identical(other.landscape, landscape) || other.landscape == landscape)&&(identical(other.tiny, tiny) || other.tiny == tiny)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,original,large2x,large,medium,small,portrait,landscape,tiny); + +@override +String toString() { + return 'SrcModel(original: $original, large2x: $large2x, large: $large, medium: $medium, small: $small, portrait: $portrait, landscape: $landscape, tiny: $tiny)'; +} + + +} + +/// @nodoc +abstract mixin class _$SrcModelCopyWith<$Res> implements $SrcModelCopyWith<$Res> { + factory _$SrcModelCopyWith(_SrcModel value, $Res Function(_SrcModel) _then) = __$SrcModelCopyWithImpl; +@override @useResult +$Res call({ + String original, String large2x, String large, String medium, String small, String portrait, String landscape, String tiny +}); + + + + +} +/// @nodoc +class __$SrcModelCopyWithImpl<$Res> + implements _$SrcModelCopyWith<$Res> { + __$SrcModelCopyWithImpl(this._self, this._then); + + final _SrcModel _self; + final $Res Function(_SrcModel) _then; + +/// Create a copy of SrcModel +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? original = null,Object? large2x = null,Object? large = null,Object? medium = null,Object? small = null,Object? portrait = null,Object? landscape = null,Object? tiny = null,}) { + return _then(_SrcModel( +original: null == original ? _self.original : original // ignore: cast_nullable_to_non_nullable +as String,large2x: null == large2x ? _self.large2x : large2x // ignore: cast_nullable_to_non_nullable +as String,large: null == large ? _self.large : large // ignore: cast_nullable_to_non_nullable +as String,medium: null == medium ? _self.medium : medium // ignore: cast_nullable_to_non_nullable +as String,small: null == small ? _self.small : small // ignore: cast_nullable_to_non_nullable +as String,portrait: null == portrait ? _self.portrait : portrait // ignore: cast_nullable_to_non_nullable +as String,landscape: null == landscape ? _self.landscape : landscape // ignore: cast_nullable_to_non_nullable +as String,tiny: null == tiny ? _self.tiny : tiny // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +// dart format on diff --git a/lib/features/quote/data/models/photo_list_model.g.dart b/lib/features/quote/data/models/photo_list_model.g.dart new file mode 100644 index 0000000..bc1ccbd --- /dev/null +++ b/lib/features/quote/data/models/photo_list_model.g.dart @@ -0,0 +1,78 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'photo_list_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_PhotoListModel _$PhotoListModelFromJson(Map json) => + _PhotoListModel( + page: (json['page'] as num).toInt(), + perPage: (json['per_page'] as num).toInt(), + photos: (json['photos'] as List) + .map((e) => PhotoModel.fromJson(e as Map)) + .toList(), + totalResults: (json['total_results'] as num).toInt(), + nextPage: json['next_page'] as String, + ); + +Map _$PhotoListModelToJson(_PhotoListModel instance) => + { + 'page': instance.page, + 'per_page': instance.perPage, + 'photos': instance.photos, + 'total_results': instance.totalResults, + 'next_page': instance.nextPage, + }; + +_PhotoModel _$PhotoModelFromJson(Map json) => _PhotoModel( + id: (json['id'] as num).toInt(), + width: (json['width'] as num).toInt(), + height: (json['height'] as num).toInt(), + url: json['url'] as String, + photographer: json['photographer'] as String, + photographerUrl: json['photographer_url'] as String, + photographerId: (json['photographer_id'] as num).toInt(), + avgColor: json['avg_color'] as String, + src: SrcModel.fromJson(json['src'] as Map), + liked: json['liked'] as bool, + alt: json['alt'] as String, +); + +Map _$PhotoModelToJson(_PhotoModel instance) => + { + 'id': instance.id, + 'width': instance.width, + 'height': instance.height, + 'url': instance.url, + 'photographer': instance.photographer, + 'photographer_url': instance.photographerUrl, + 'photographer_id': instance.photographerId, + 'avg_color': instance.avgColor, + 'src': instance.src, + 'liked': instance.liked, + 'alt': instance.alt, + }; + +_SrcModel _$SrcModelFromJson(Map json) => _SrcModel( + original: json['original'] as String, + large2x: json['large2x'] as String, + large: json['large'] as String, + medium: json['medium'] as String, + small: json['small'] as String, + portrait: json['portrait'] as String, + landscape: json['landscape'] as String, + tiny: json['tiny'] as String, +); + +Map _$SrcModelToJson(_SrcModel instance) => { + 'original': instance.original, + 'large2x': instance.large2x, + 'large': instance.large, + 'medium': instance.medium, + 'small': instance.small, + 'portrait': instance.portrait, + 'landscape': instance.landscape, + 'tiny': instance.tiny, +}; diff --git a/lib/features/quote/data/models/quote_model.dart b/lib/features/quote/data/models/quote_model.dart new file mode 100644 index 0000000..355c1da --- /dev/null +++ b/lib/features/quote/data/models/quote_model.dart @@ -0,0 +1,17 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'quote_model.freezed.dart'; +part 'quote_model.g.dart'; + +@freezed +abstract class QuoteModel with _$QuoteModel { + @JsonSerializable(fieldRename: FieldRename.snake) + const factory QuoteModel({ + required int id, + required String text, + required String author, + }) = _QuoteModel; + + factory QuoteModel.fromJson(Map json) => + _$QuoteModelFromJson(json); +} diff --git a/lib/features/quote/data/models/quote_model.freezed.dart b/lib/features/quote/data/models/quote_model.freezed.dart new file mode 100644 index 0000000..84da644 --- /dev/null +++ b/lib/features/quote/data/models/quote_model.freezed.dart @@ -0,0 +1,283 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'quote_model.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; + +/// @nodoc +mixin _$QuoteModel { + + int get id; String get text; String get author; +/// Create a copy of QuoteModel +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$QuoteModelCopyWith get copyWith => _$QuoteModelCopyWithImpl(this as QuoteModel, _$identity); + + /// Serializes this QuoteModel to a JSON map. + Map toJson(); + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is QuoteModel&&(identical(other.id, id) || other.id == id)&&(identical(other.text, text) || other.text == text)&&(identical(other.author, author) || other.author == author)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,id,text,author); + +@override +String toString() { + return 'QuoteModel(id: $id, text: $text, author: $author)'; +} + + +} + +/// @nodoc +abstract mixin class $QuoteModelCopyWith<$Res> { + factory $QuoteModelCopyWith(QuoteModel value, $Res Function(QuoteModel) _then) = _$QuoteModelCopyWithImpl; +@useResult +$Res call({ + int id, String text, String author +}); + + + + +} +/// @nodoc +class _$QuoteModelCopyWithImpl<$Res> + implements $QuoteModelCopyWith<$Res> { + _$QuoteModelCopyWithImpl(this._self, this._then); + + final QuoteModel _self; + final $Res Function(QuoteModel) _then; + +/// Create a copy of QuoteModel +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? text = null,Object? author = null,}) { + return _then(_self.copyWith( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as int,text: null == text ? _self.text : text // ignore: cast_nullable_to_non_nullable +as String,author: null == author ? _self.author : author // ignore: cast_nullable_to_non_nullable +as String, + )); +} + +} + + +/// Adds pattern-matching-related methods to [QuoteModel]. +extension QuoteModelPatterns on QuoteModel { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _QuoteModel value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _QuoteModel() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _QuoteModel value) $default,){ +final _that = this; +switch (_that) { +case _QuoteModel(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _QuoteModel value)? $default,){ +final _that = this; +switch (_that) { +case _QuoteModel() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( int id, String text, String author)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _QuoteModel() when $default != null: +return $default(_that.id,_that.text,_that.author);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( int id, String text, String author) $default,) {final _that = this; +switch (_that) { +case _QuoteModel(): +return $default(_that.id,_that.text,_that.author);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( int id, String text, String author)? $default,) {final _that = this; +switch (_that) { +case _QuoteModel() when $default != null: +return $default(_that.id,_that.text,_that.author);case _: + return null; + +} +} + +} + +/// @nodoc + +@JsonSerializable(fieldRename: FieldRename.snake) +class _QuoteModel implements QuoteModel { + const _QuoteModel({required this.id, required this.text, required this.author}); + factory _QuoteModel.fromJson(Map json) => _$QuoteModelFromJson(json); + +@override final int id; +@override final String text; +@override final String author; + +/// Create a copy of QuoteModel +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$QuoteModelCopyWith<_QuoteModel> get copyWith => __$QuoteModelCopyWithImpl<_QuoteModel>(this, _$identity); + +@override +Map toJson() { + return _$QuoteModelToJson(this, ); +} + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _QuoteModel&&(identical(other.id, id) || other.id == id)&&(identical(other.text, text) || other.text == text)&&(identical(other.author, author) || other.author == author)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,id,text,author); + +@override +String toString() { + return 'QuoteModel(id: $id, text: $text, author: $author)'; +} + + +} + +/// @nodoc +abstract mixin class _$QuoteModelCopyWith<$Res> implements $QuoteModelCopyWith<$Res> { + factory _$QuoteModelCopyWith(_QuoteModel value, $Res Function(_QuoteModel) _then) = __$QuoteModelCopyWithImpl; +@override @useResult +$Res call({ + int id, String text, String author +}); + + + + +} +/// @nodoc +class __$QuoteModelCopyWithImpl<$Res> + implements _$QuoteModelCopyWith<$Res> { + __$QuoteModelCopyWithImpl(this._self, this._then); + + final _QuoteModel _self; + final $Res Function(_QuoteModel) _then; + +/// Create a copy of QuoteModel +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? text = null,Object? author = null,}) { + return _then(_QuoteModel( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as int,text: null == text ? _self.text : text // ignore: cast_nullable_to_non_nullable +as String,author: null == author ? _self.author : author // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +// dart format on diff --git a/lib/features/quote/data/models/quote_model.g.dart b/lib/features/quote/data/models/quote_model.g.dart new file mode 100644 index 0000000..252cb4e --- /dev/null +++ b/lib/features/quote/data/models/quote_model.g.dart @@ -0,0 +1,20 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'quote_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_QuoteModel _$QuoteModelFromJson(Map json) => _QuoteModel( + id: (json['id'] as num).toInt(), + text: json['text'] as String, + author: json['author'] as String, +); + +Map _$QuoteModelToJson(_QuoteModel instance) => + { + 'id': instance.id, + 'text': instance.text, + 'author': instance.author, + }; diff --git a/lib/features/quote/data/models/translation_model.dart b/lib/features/quote/data/models/translation_model.dart new file mode 100644 index 0000000..290bc02 --- /dev/null +++ b/lib/features/quote/data/models/translation_model.dart @@ -0,0 +1,13 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'translation_model.freezed.dart'; +part 'translation_model.g.dart'; + +@freezed +abstract class TranslationModel with _$TranslationModel { + const factory TranslationModel({required String id, required String lang}) = + _TranslationModel; + + factory TranslationModel.fromJson(Map json) => + _$TranslationModelFromJson(json); +} diff --git a/lib/features/quote/data/models/translation_model.freezed.dart b/lib/features/quote/data/models/translation_model.freezed.dart new file mode 100644 index 0000000..65577d1 --- /dev/null +++ b/lib/features/quote/data/models/translation_model.freezed.dart @@ -0,0 +1,280 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'translation_model.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; + +/// @nodoc +mixin _$TranslationModel { + + String get id; String get lang; +/// Create a copy of TranslationModel +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$TranslationModelCopyWith get copyWith => _$TranslationModelCopyWithImpl(this as TranslationModel, _$identity); + + /// Serializes this TranslationModel to a JSON map. + Map toJson(); + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is TranslationModel&&(identical(other.id, id) || other.id == id)&&(identical(other.lang, lang) || other.lang == lang)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,id,lang); + +@override +String toString() { + return 'TranslationModel(id: $id, lang: $lang)'; +} + + +} + +/// @nodoc +abstract mixin class $TranslationModelCopyWith<$Res> { + factory $TranslationModelCopyWith(TranslationModel value, $Res Function(TranslationModel) _then) = _$TranslationModelCopyWithImpl; +@useResult +$Res call({ + String id, String lang +}); + + + + +} +/// @nodoc +class _$TranslationModelCopyWithImpl<$Res> + implements $TranslationModelCopyWith<$Res> { + _$TranslationModelCopyWithImpl(this._self, this._then); + + final TranslationModel _self; + final $Res Function(TranslationModel) _then; + +/// Create a copy of TranslationModel +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? lang = null,}) { + return _then(_self.copyWith( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as String,lang: null == lang ? _self.lang : lang // ignore: cast_nullable_to_non_nullable +as String, + )); +} + +} + + +/// Adds pattern-matching-related methods to [TranslationModel]. +extension TranslationModelPatterns on TranslationModel { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _TranslationModel value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _TranslationModel() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _TranslationModel value) $default,){ +final _that = this; +switch (_that) { +case _TranslationModel(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _TranslationModel value)? $default,){ +final _that = this; +switch (_that) { +case _TranslationModel() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( String id, String lang)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _TranslationModel() when $default != null: +return $default(_that.id,_that.lang);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( String id, String lang) $default,) {final _that = this; +switch (_that) { +case _TranslationModel(): +return $default(_that.id,_that.lang);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String id, String lang)? $default,) {final _that = this; +switch (_that) { +case _TranslationModel() when $default != null: +return $default(_that.id,_that.lang);case _: + return null; + +} +} + +} + +/// @nodoc +@JsonSerializable() + +class _TranslationModel implements TranslationModel { + const _TranslationModel({required this.id, required this.lang}); + factory _TranslationModel.fromJson(Map json) => _$TranslationModelFromJson(json); + +@override final String id; +@override final String lang; + +/// Create a copy of TranslationModel +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$TranslationModelCopyWith<_TranslationModel> get copyWith => __$TranslationModelCopyWithImpl<_TranslationModel>(this, _$identity); + +@override +Map toJson() { + return _$TranslationModelToJson(this, ); +} + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _TranslationModel&&(identical(other.id, id) || other.id == id)&&(identical(other.lang, lang) || other.lang == lang)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode => Object.hash(runtimeType,id,lang); + +@override +String toString() { + return 'TranslationModel(id: $id, lang: $lang)'; +} + + +} + +/// @nodoc +abstract mixin class _$TranslationModelCopyWith<$Res> implements $TranslationModelCopyWith<$Res> { + factory _$TranslationModelCopyWith(_TranslationModel value, $Res Function(_TranslationModel) _then) = __$TranslationModelCopyWithImpl; +@override @useResult +$Res call({ + String id, String lang +}); + + + + +} +/// @nodoc +class __$TranslationModelCopyWithImpl<$Res> + implements _$TranslationModelCopyWith<$Res> { + __$TranslationModelCopyWithImpl(this._self, this._then); + + final _TranslationModel _self; + final $Res Function(_TranslationModel) _then; + +/// Create a copy of TranslationModel +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? lang = null,}) { + return _then(_TranslationModel( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as String,lang: null == lang ? _self.lang : lang // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +// dart format on diff --git a/lib/features/quote/data/models/translation_model.g.dart b/lib/features/quote/data/models/translation_model.g.dart new file mode 100644 index 0000000..06564b1 --- /dev/null +++ b/lib/features/quote/data/models/translation_model.g.dart @@ -0,0 +1,13 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'translation_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_TranslationModel _$TranslationModelFromJson(Map json) => + _TranslationModel(id: json['id'] as String, lang: json['lang'] as String); + +Map _$TranslationModelToJson(_TranslationModel instance) => + {'id': instance.id, 'lang': instance.lang}; diff --git a/lib/features/quote/data/repositories/quote_repository_impl.dart b/lib/features/quote/data/repositories/quote_repository_impl.dart new file mode 100644 index 0000000..4786eb1 --- /dev/null +++ b/lib/features/quote/data/repositories/quote_repository_impl.dart @@ -0,0 +1,89 @@ +import 'dart:convert'; + +import 'package:fpdart/fpdart.dart'; +import 'package:http/http.dart'; +import 'package:kuwot/core/data/local/translation_target_config.dart'; +import 'package:kuwot/core/error/exception.dart'; +import 'package:kuwot/core/error/failure.dart'; +import 'package:kuwot/core/error/server_error_model.dart'; +import 'package:kuwot/features/quote/data/data_sources/remote/kuwot_api_remote_data_source.dart'; +import 'package:kuwot/features/quote/domain/entities/background_image.dart'; +import 'package:kuwot/features/quote/domain/entities/quote.dart'; +import 'package:kuwot/features/quote/domain/entities/translation.dart'; +import 'package:kuwot/features/quote/domain/repositories/quote_repository.dart'; + +class QuoteRepositoryImpl implements QuoteRepository { + final KuwotApiRemoteDataSource quoteDataSource; + + QuoteRepositoryImpl({required this.quoteDataSource}); + + @override + Future>> getBackgroundImages() async { + try { + final images = await quoteDataSource.getRandomImages(); + return right(BackgroundImage.fromModels(images)); + } on ClientException catch (e) { + return left( + ClientFailure(message: "Failed to connect to the server", cause: e), + ); + } on Exception catch (e) { + return left(UnknownFailure(message: e.toString(), cause: e)); + } + } + + @override + Future> getQuote( + TranslationTarget? translationTarget, + ) async { + try { + final query = translationTarget != null + ? "lang=${translationTarget.id}" + : null; + final quote = await quoteDataSource.getQuote(query: query); + return right(Quote.fromModel(quote)); + } on ClientException catch (e) { + return left( + ClientFailure(message: "Failed to connect to the server", cause: e), + ); + } on ServerException catch (e) { + final error = ServerErrorModel.fromJson(jsonDecode(e.message)); + return left( + ServerFailure(message: '${error.message} (${error.code})', cause: e), + ); + } on Exception catch (e) { + return left(UnknownFailure(message: e.toString(), cause: e)); + } + } + + @override + Future> getTranslatedQuote( + int id, + TranslationTarget translationTarget, + ) async { + try { + final query = "lang=${translationTarget.id}"; + final quote = await quoteDataSource.getTranslatedQuote(id, query: query); + return right(Quote.fromModel(quote)); + } on ClientException catch (e) { + return left( + ClientFailure(message: "Failed to connect to the server", cause: e), + ); + } on Exception catch (e) { + return left(UnknownFailure(message: e.toString(), cause: e)); + } + } + + @override + Future>> getTranslations() async { + try { + final translations = await quoteDataSource.getTranslations(); + return right(translations.map((e) => Translation.fromModel(e)).toList()); + } on ClientException catch (e) { + return left( + ClientFailure(message: "Failed to connect to the server", cause: e), + ); + } on Exception catch (e) { + return left(UnknownFailure(message: e.toString(), cause: e)); + } + } +} diff --git a/lib/features/quote/domain/entities/background_image.dart b/lib/features/quote/domain/entities/background_image.dart new file mode 100644 index 0000000..66761ae --- /dev/null +++ b/lib/features/quote/domain/entities/background_image.dart @@ -0,0 +1,49 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:kuwot/features/quote/data/models/image_model.dart'; + +part 'background_image.freezed.dart'; + +@freezed +abstract class BackgroundImage with _$BackgroundImage { + const BackgroundImage._(); + + const factory BackgroundImage({ + required String id, + required String description, + required String color, + required String blurHash, + required String url, + required String originUrl, + required String authorName, + required String authorProfileImageUrl, + required String authorUrl, + required String authorBio, + required String authorLocation, + required int authorTotalLikes, + required int authorTotalPhotos, + required bool authorIsForHire, + }) = _BackgroundImage; + + static List fromModels(List images) { + return images + .map( + (e) => BackgroundImage( + id: e.id, + description: e.description, + color: e.color, + blurHash: e.blurHash, + url: e.url, + originUrl: e.originUrl, + authorUrl: e.authorUrl, + authorName: e.authorName, + authorProfileImageUrl: e.authorProfileImageUrl, + authorBio: e.authorBio, + authorLocation: e.authorLocation, + authorTotalLikes: e.authorTotalLikes, + authorTotalPhotos: e.authorTotalPhotos, + authorIsForHire: e.authorIsForHire, + ), + ) + .toList(); + } +} diff --git a/lib/features/quote/domain/entities/background_image.freezed.dart b/lib/features/quote/domain/entities/background_image.freezed.dart new file mode 100644 index 0000000..f3c1b16 --- /dev/null +++ b/lib/features/quote/domain/entities/background_image.freezed.dart @@ -0,0 +1,310 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'background_image.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$BackgroundImage { + + String get id; String get description; String get color; String get blurHash; String get url; String get originUrl; String get authorName; String get authorProfileImageUrl; String get authorUrl; String get authorBio; String get authorLocation; int get authorTotalLikes; int get authorTotalPhotos; bool get authorIsForHire; +/// Create a copy of BackgroundImage +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$BackgroundImageCopyWith get copyWith => _$BackgroundImageCopyWithImpl(this as BackgroundImage, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is BackgroundImage&&(identical(other.id, id) || other.id == id)&&(identical(other.description, description) || other.description == description)&&(identical(other.color, color) || other.color == color)&&(identical(other.blurHash, blurHash) || other.blurHash == blurHash)&&(identical(other.url, url) || other.url == url)&&(identical(other.originUrl, originUrl) || other.originUrl == originUrl)&&(identical(other.authorName, authorName) || other.authorName == authorName)&&(identical(other.authorProfileImageUrl, authorProfileImageUrl) || other.authorProfileImageUrl == authorProfileImageUrl)&&(identical(other.authorUrl, authorUrl) || other.authorUrl == authorUrl)&&(identical(other.authorBio, authorBio) || other.authorBio == authorBio)&&(identical(other.authorLocation, authorLocation) || other.authorLocation == authorLocation)&&(identical(other.authorTotalLikes, authorTotalLikes) || other.authorTotalLikes == authorTotalLikes)&&(identical(other.authorTotalPhotos, authorTotalPhotos) || other.authorTotalPhotos == authorTotalPhotos)&&(identical(other.authorIsForHire, authorIsForHire) || other.authorIsForHire == authorIsForHire)); +} + + +@override +int get hashCode => Object.hash(runtimeType,id,description,color,blurHash,url,originUrl,authorName,authorProfileImageUrl,authorUrl,authorBio,authorLocation,authorTotalLikes,authorTotalPhotos,authorIsForHire); + +@override +String toString() { + return 'BackgroundImage(id: $id, description: $description, color: $color, blurHash: $blurHash, url: $url, originUrl: $originUrl, authorName: $authorName, authorProfileImageUrl: $authorProfileImageUrl, authorUrl: $authorUrl, authorBio: $authorBio, authorLocation: $authorLocation, authorTotalLikes: $authorTotalLikes, authorTotalPhotos: $authorTotalPhotos, authorIsForHire: $authorIsForHire)'; +} + + +} + +/// @nodoc +abstract mixin class $BackgroundImageCopyWith<$Res> { + factory $BackgroundImageCopyWith(BackgroundImage value, $Res Function(BackgroundImage) _then) = _$BackgroundImageCopyWithImpl; +@useResult +$Res call({ + String id, String description, String color, String blurHash, String url, String originUrl, String authorName, String authorProfileImageUrl, String authorUrl, String authorBio, String authorLocation, int authorTotalLikes, int authorTotalPhotos, bool authorIsForHire +}); + + + + +} +/// @nodoc +class _$BackgroundImageCopyWithImpl<$Res> + implements $BackgroundImageCopyWith<$Res> { + _$BackgroundImageCopyWithImpl(this._self, this._then); + + final BackgroundImage _self; + final $Res Function(BackgroundImage) _then; + +/// Create a copy of BackgroundImage +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? description = null,Object? color = null,Object? blurHash = null,Object? url = null,Object? originUrl = null,Object? authorName = null,Object? authorProfileImageUrl = null,Object? authorUrl = null,Object? authorBio = null,Object? authorLocation = null,Object? authorTotalLikes = null,Object? authorTotalPhotos = null,Object? authorIsForHire = null,}) { + return _then(_self.copyWith( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as String,description: null == description ? _self.description : description // ignore: cast_nullable_to_non_nullable +as String,color: null == color ? _self.color : color // ignore: cast_nullable_to_non_nullable +as String,blurHash: null == blurHash ? _self.blurHash : blurHash // ignore: cast_nullable_to_non_nullable +as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable +as String,originUrl: null == originUrl ? _self.originUrl : originUrl // ignore: cast_nullable_to_non_nullable +as String,authorName: null == authorName ? _self.authorName : authorName // ignore: cast_nullable_to_non_nullable +as String,authorProfileImageUrl: null == authorProfileImageUrl ? _self.authorProfileImageUrl : authorProfileImageUrl // ignore: cast_nullable_to_non_nullable +as String,authorUrl: null == authorUrl ? _self.authorUrl : authorUrl // ignore: cast_nullable_to_non_nullable +as String,authorBio: null == authorBio ? _self.authorBio : authorBio // ignore: cast_nullable_to_non_nullable +as String,authorLocation: null == authorLocation ? _self.authorLocation : authorLocation // ignore: cast_nullable_to_non_nullable +as String,authorTotalLikes: null == authorTotalLikes ? _self.authorTotalLikes : authorTotalLikes // ignore: cast_nullable_to_non_nullable +as int,authorTotalPhotos: null == authorTotalPhotos ? _self.authorTotalPhotos : authorTotalPhotos // ignore: cast_nullable_to_non_nullable +as int,authorIsForHire: null == authorIsForHire ? _self.authorIsForHire : authorIsForHire // ignore: cast_nullable_to_non_nullable +as bool, + )); +} + +} + + +/// Adds pattern-matching-related methods to [BackgroundImage]. +extension BackgroundImagePatterns on BackgroundImage { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _BackgroundImage value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _BackgroundImage() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _BackgroundImage value) $default,){ +final _that = this; +switch (_that) { +case _BackgroundImage(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _BackgroundImage value)? $default,){ +final _that = this; +switch (_that) { +case _BackgroundImage() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( String id, String description, String color, String blurHash, String url, String originUrl, String authorName, String authorProfileImageUrl, String authorUrl, String authorBio, String authorLocation, int authorTotalLikes, int authorTotalPhotos, bool authorIsForHire)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _BackgroundImage() when $default != null: +return $default(_that.id,_that.description,_that.color,_that.blurHash,_that.url,_that.originUrl,_that.authorName,_that.authorProfileImageUrl,_that.authorUrl,_that.authorBio,_that.authorLocation,_that.authorTotalLikes,_that.authorTotalPhotos,_that.authorIsForHire);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( String id, String description, String color, String blurHash, String url, String originUrl, String authorName, String authorProfileImageUrl, String authorUrl, String authorBio, String authorLocation, int authorTotalLikes, int authorTotalPhotos, bool authorIsForHire) $default,) {final _that = this; +switch (_that) { +case _BackgroundImage(): +return $default(_that.id,_that.description,_that.color,_that.blurHash,_that.url,_that.originUrl,_that.authorName,_that.authorProfileImageUrl,_that.authorUrl,_that.authorBio,_that.authorLocation,_that.authorTotalLikes,_that.authorTotalPhotos,_that.authorIsForHire);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String id, String description, String color, String blurHash, String url, String originUrl, String authorName, String authorProfileImageUrl, String authorUrl, String authorBio, String authorLocation, int authorTotalLikes, int authorTotalPhotos, bool authorIsForHire)? $default,) {final _that = this; +switch (_that) { +case _BackgroundImage() when $default != null: +return $default(_that.id,_that.description,_that.color,_that.blurHash,_that.url,_that.originUrl,_that.authorName,_that.authorProfileImageUrl,_that.authorUrl,_that.authorBio,_that.authorLocation,_that.authorTotalLikes,_that.authorTotalPhotos,_that.authorIsForHire);case _: + return null; + +} +} + +} + +/// @nodoc + + +class _BackgroundImage extends BackgroundImage { + const _BackgroundImage({required this.id, required this.description, required this.color, required this.blurHash, required this.url, required this.originUrl, required this.authorName, required this.authorProfileImageUrl, required this.authorUrl, required this.authorBio, required this.authorLocation, required this.authorTotalLikes, required this.authorTotalPhotos, required this.authorIsForHire}): super._(); + + +@override final String id; +@override final String description; +@override final String color; +@override final String blurHash; +@override final String url; +@override final String originUrl; +@override final String authorName; +@override final String authorProfileImageUrl; +@override final String authorUrl; +@override final String authorBio; +@override final String authorLocation; +@override final int authorTotalLikes; +@override final int authorTotalPhotos; +@override final bool authorIsForHire; + +/// Create a copy of BackgroundImage +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$BackgroundImageCopyWith<_BackgroundImage> get copyWith => __$BackgroundImageCopyWithImpl<_BackgroundImage>(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _BackgroundImage&&(identical(other.id, id) || other.id == id)&&(identical(other.description, description) || other.description == description)&&(identical(other.color, color) || other.color == color)&&(identical(other.blurHash, blurHash) || other.blurHash == blurHash)&&(identical(other.url, url) || other.url == url)&&(identical(other.originUrl, originUrl) || other.originUrl == originUrl)&&(identical(other.authorName, authorName) || other.authorName == authorName)&&(identical(other.authorProfileImageUrl, authorProfileImageUrl) || other.authorProfileImageUrl == authorProfileImageUrl)&&(identical(other.authorUrl, authorUrl) || other.authorUrl == authorUrl)&&(identical(other.authorBio, authorBio) || other.authorBio == authorBio)&&(identical(other.authorLocation, authorLocation) || other.authorLocation == authorLocation)&&(identical(other.authorTotalLikes, authorTotalLikes) || other.authorTotalLikes == authorTotalLikes)&&(identical(other.authorTotalPhotos, authorTotalPhotos) || other.authorTotalPhotos == authorTotalPhotos)&&(identical(other.authorIsForHire, authorIsForHire) || other.authorIsForHire == authorIsForHire)); +} + + +@override +int get hashCode => Object.hash(runtimeType,id,description,color,blurHash,url,originUrl,authorName,authorProfileImageUrl,authorUrl,authorBio,authorLocation,authorTotalLikes,authorTotalPhotos,authorIsForHire); + +@override +String toString() { + return 'BackgroundImage(id: $id, description: $description, color: $color, blurHash: $blurHash, url: $url, originUrl: $originUrl, authorName: $authorName, authorProfileImageUrl: $authorProfileImageUrl, authorUrl: $authorUrl, authorBio: $authorBio, authorLocation: $authorLocation, authorTotalLikes: $authorTotalLikes, authorTotalPhotos: $authorTotalPhotos, authorIsForHire: $authorIsForHire)'; +} + + +} + +/// @nodoc +abstract mixin class _$BackgroundImageCopyWith<$Res> implements $BackgroundImageCopyWith<$Res> { + factory _$BackgroundImageCopyWith(_BackgroundImage value, $Res Function(_BackgroundImage) _then) = __$BackgroundImageCopyWithImpl; +@override @useResult +$Res call({ + String id, String description, String color, String blurHash, String url, String originUrl, String authorName, String authorProfileImageUrl, String authorUrl, String authorBio, String authorLocation, int authorTotalLikes, int authorTotalPhotos, bool authorIsForHire +}); + + + + +} +/// @nodoc +class __$BackgroundImageCopyWithImpl<$Res> + implements _$BackgroundImageCopyWith<$Res> { + __$BackgroundImageCopyWithImpl(this._self, this._then); + + final _BackgroundImage _self; + final $Res Function(_BackgroundImage) _then; + +/// Create a copy of BackgroundImage +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? description = null,Object? color = null,Object? blurHash = null,Object? url = null,Object? originUrl = null,Object? authorName = null,Object? authorProfileImageUrl = null,Object? authorUrl = null,Object? authorBio = null,Object? authorLocation = null,Object? authorTotalLikes = null,Object? authorTotalPhotos = null,Object? authorIsForHire = null,}) { + return _then(_BackgroundImage( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as String,description: null == description ? _self.description : description // ignore: cast_nullable_to_non_nullable +as String,color: null == color ? _self.color : color // ignore: cast_nullable_to_non_nullable +as String,blurHash: null == blurHash ? _self.blurHash : blurHash // ignore: cast_nullable_to_non_nullable +as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable +as String,originUrl: null == originUrl ? _self.originUrl : originUrl // ignore: cast_nullable_to_non_nullable +as String,authorName: null == authorName ? _self.authorName : authorName // ignore: cast_nullable_to_non_nullable +as String,authorProfileImageUrl: null == authorProfileImageUrl ? _self.authorProfileImageUrl : authorProfileImageUrl // ignore: cast_nullable_to_non_nullable +as String,authorUrl: null == authorUrl ? _self.authorUrl : authorUrl // ignore: cast_nullable_to_non_nullable +as String,authorBio: null == authorBio ? _self.authorBio : authorBio // ignore: cast_nullable_to_non_nullable +as String,authorLocation: null == authorLocation ? _self.authorLocation : authorLocation // ignore: cast_nullable_to_non_nullable +as String,authorTotalLikes: null == authorTotalLikes ? _self.authorTotalLikes : authorTotalLikes // ignore: cast_nullable_to_non_nullable +as int,authorTotalPhotos: null == authorTotalPhotos ? _self.authorTotalPhotos : authorTotalPhotos // ignore: cast_nullable_to_non_nullable +as int,authorIsForHire: null == authorIsForHire ? _self.authorIsForHire : authorIsForHire // ignore: cast_nullable_to_non_nullable +as bool, + )); +} + + +} + +// dart format on diff --git a/lib/features/quote/domain/entities/background_photos.dart b/lib/features/quote/domain/entities/background_photos.dart new file mode 100644 index 0000000..cea4a52 --- /dev/null +++ b/lib/features/quote/domain/entities/background_photos.dart @@ -0,0 +1,28 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:kuwot/features/quote/data/models/photo_list_model.dart'; + +part 'background_photos.freezed.dart'; + +@freezed +abstract class BackgroundPhotos with _$BackgroundPhotos { + const factory BackgroundPhotos({required List photos}) = + _BackgroundPhotos; + + static BackgroundPhotos fromModel(PhotoListModel model) => BackgroundPhotos( + photos: model.photos.map((e) { + return Photo( + url: buildPortraitImageUrl(e.src.original), + avgColor: e.avgColor, + ); + }).toList(), + ); + + static String buildPortraitImageUrl(String originalUrl) => + '$originalUrl?auto=compress&cs=tinysrgb&fit=crop&h=2400&w=1200'; +} + +@freezed +abstract class Photo with _$Photo { + const factory Photo({required String url, required String avgColor}) = + _BackgroundImage; +} diff --git a/lib/features/quote/domain/entities/background_photos.freezed.dart b/lib/features/quote/domain/entities/background_photos.freezed.dart new file mode 100644 index 0000000..c9b5290 --- /dev/null +++ b/lib/features/quote/domain/entities/background_photos.freezed.dart @@ -0,0 +1,537 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'background_photos.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$BackgroundPhotos { + + List get photos; +/// Create a copy of BackgroundPhotos +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$BackgroundPhotosCopyWith get copyWith => _$BackgroundPhotosCopyWithImpl(this as BackgroundPhotos, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is BackgroundPhotos&&const DeepCollectionEquality().equals(other.photos, photos)); +} + + +@override +int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(photos)); + +@override +String toString() { + return 'BackgroundPhotos(photos: $photos)'; +} + + +} + +/// @nodoc +abstract mixin class $BackgroundPhotosCopyWith<$Res> { + factory $BackgroundPhotosCopyWith(BackgroundPhotos value, $Res Function(BackgroundPhotos) _then) = _$BackgroundPhotosCopyWithImpl; +@useResult +$Res call({ + List photos +}); + + + + +} +/// @nodoc +class _$BackgroundPhotosCopyWithImpl<$Res> + implements $BackgroundPhotosCopyWith<$Res> { + _$BackgroundPhotosCopyWithImpl(this._self, this._then); + + final BackgroundPhotos _self; + final $Res Function(BackgroundPhotos) _then; + +/// Create a copy of BackgroundPhotos +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? photos = null,}) { + return _then(_self.copyWith( +photos: null == photos ? _self.photos : photos // ignore: cast_nullable_to_non_nullable +as List, + )); +} + +} + + +/// Adds pattern-matching-related methods to [BackgroundPhotos]. +extension BackgroundPhotosPatterns on BackgroundPhotos { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _BackgroundPhotos value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _BackgroundPhotos() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _BackgroundPhotos value) $default,){ +final _that = this; +switch (_that) { +case _BackgroundPhotos(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _BackgroundPhotos value)? $default,){ +final _that = this; +switch (_that) { +case _BackgroundPhotos() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( List photos)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _BackgroundPhotos() when $default != null: +return $default(_that.photos);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( List photos) $default,) {final _that = this; +switch (_that) { +case _BackgroundPhotos(): +return $default(_that.photos);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( List photos)? $default,) {final _that = this; +switch (_that) { +case _BackgroundPhotos() when $default != null: +return $default(_that.photos);case _: + return null; + +} +} + +} + +/// @nodoc + + +class _BackgroundPhotos implements BackgroundPhotos { + const _BackgroundPhotos({required final List photos}): _photos = photos; + + + final List _photos; +@override List get photos { + if (_photos is EqualUnmodifiableListView) return _photos; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_photos); +} + + +/// Create a copy of BackgroundPhotos +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$BackgroundPhotosCopyWith<_BackgroundPhotos> get copyWith => __$BackgroundPhotosCopyWithImpl<_BackgroundPhotos>(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _BackgroundPhotos&&const DeepCollectionEquality().equals(other._photos, _photos)); +} + + +@override +int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(_photos)); + +@override +String toString() { + return 'BackgroundPhotos(photos: $photos)'; +} + + +} + +/// @nodoc +abstract mixin class _$BackgroundPhotosCopyWith<$Res> implements $BackgroundPhotosCopyWith<$Res> { + factory _$BackgroundPhotosCopyWith(_BackgroundPhotos value, $Res Function(_BackgroundPhotos) _then) = __$BackgroundPhotosCopyWithImpl; +@override @useResult +$Res call({ + List photos +}); + + + + +} +/// @nodoc +class __$BackgroundPhotosCopyWithImpl<$Res> + implements _$BackgroundPhotosCopyWith<$Res> { + __$BackgroundPhotosCopyWithImpl(this._self, this._then); + + final _BackgroundPhotos _self; + final $Res Function(_BackgroundPhotos) _then; + +/// Create a copy of BackgroundPhotos +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? photos = null,}) { + return _then(_BackgroundPhotos( +photos: null == photos ? _self._photos : photos // ignore: cast_nullable_to_non_nullable +as List, + )); +} + + +} + +/// @nodoc +mixin _$Photo { + + String get url; String get avgColor; +/// Create a copy of Photo +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$PhotoCopyWith get copyWith => _$PhotoCopyWithImpl(this as Photo, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is Photo&&(identical(other.url, url) || other.url == url)&&(identical(other.avgColor, avgColor) || other.avgColor == avgColor)); +} + + +@override +int get hashCode => Object.hash(runtimeType,url,avgColor); + +@override +String toString() { + return 'Photo(url: $url, avgColor: $avgColor)'; +} + + +} + +/// @nodoc +abstract mixin class $PhotoCopyWith<$Res> { + factory $PhotoCopyWith(Photo value, $Res Function(Photo) _then) = _$PhotoCopyWithImpl; +@useResult +$Res call({ + String url, String avgColor +}); + + + + +} +/// @nodoc +class _$PhotoCopyWithImpl<$Res> + implements $PhotoCopyWith<$Res> { + _$PhotoCopyWithImpl(this._self, this._then); + + final Photo _self; + final $Res Function(Photo) _then; + +/// Create a copy of Photo +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? url = null,Object? avgColor = null,}) { + return _then(_self.copyWith( +url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable +as String,avgColor: null == avgColor ? _self.avgColor : avgColor // ignore: cast_nullable_to_non_nullable +as String, + )); +} + +} + + +/// Adds pattern-matching-related methods to [Photo]. +extension PhotoPatterns on Photo { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _BackgroundImage value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _BackgroundImage() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _BackgroundImage value) $default,){ +final _that = this; +switch (_that) { +case _BackgroundImage(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _BackgroundImage value)? $default,){ +final _that = this; +switch (_that) { +case _BackgroundImage() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( String url, String avgColor)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _BackgroundImage() when $default != null: +return $default(_that.url,_that.avgColor);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( String url, String avgColor) $default,) {final _that = this; +switch (_that) { +case _BackgroundImage(): +return $default(_that.url,_that.avgColor);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String url, String avgColor)? $default,) {final _that = this; +switch (_that) { +case _BackgroundImage() when $default != null: +return $default(_that.url,_that.avgColor);case _: + return null; + +} +} + +} + +/// @nodoc + + +class _BackgroundImage implements Photo { + const _BackgroundImage({required this.url, required this.avgColor}); + + +@override final String url; +@override final String avgColor; + +/// Create a copy of Photo +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$BackgroundImageCopyWith<_BackgroundImage> get copyWith => __$BackgroundImageCopyWithImpl<_BackgroundImage>(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _BackgroundImage&&(identical(other.url, url) || other.url == url)&&(identical(other.avgColor, avgColor) || other.avgColor == avgColor)); +} + + +@override +int get hashCode => Object.hash(runtimeType,url,avgColor); + +@override +String toString() { + return 'Photo(url: $url, avgColor: $avgColor)'; +} + + +} + +/// @nodoc +abstract mixin class _$BackgroundImageCopyWith<$Res> implements $PhotoCopyWith<$Res> { + factory _$BackgroundImageCopyWith(_BackgroundImage value, $Res Function(_BackgroundImage) _then) = __$BackgroundImageCopyWithImpl; +@override @useResult +$Res call({ + String url, String avgColor +}); + + + + +} +/// @nodoc +class __$BackgroundImageCopyWithImpl<$Res> + implements _$BackgroundImageCopyWith<$Res> { + __$BackgroundImageCopyWithImpl(this._self, this._then); + + final _BackgroundImage _self; + final $Res Function(_BackgroundImage) _then; + +/// Create a copy of Photo +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? url = null,Object? avgColor = null,}) { + return _then(_BackgroundImage( +url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable +as String,avgColor: null == avgColor ? _self.avgColor : avgColor // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +// dart format on diff --git a/lib/features/quote/domain/entities/quote.dart b/lib/features/quote/domain/entities/quote.dart new file mode 100644 index 0000000..042c13c --- /dev/null +++ b/lib/features/quote/domain/entities/quote.dart @@ -0,0 +1,16 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:kuwot/features/quote/data/models/quote_model.dart'; + +part 'quote.freezed.dart'; + +@freezed +abstract class Quote with _$Quote { + const factory Quote({ + required int id, + required String author, + required String body, + }) = _Quote; + + static Quote fromModel(QuoteModel model) => + Quote(id: model.id, author: model.author, body: model.text); +} diff --git a/lib/features/quote/domain/entities/quote.freezed.dart b/lib/features/quote/domain/entities/quote.freezed.dart new file mode 100644 index 0000000..4738413 --- /dev/null +++ b/lib/features/quote/domain/entities/quote.freezed.dart @@ -0,0 +1,277 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'quote.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$Quote { + + int get id; String get author; String get body; +/// Create a copy of Quote +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$QuoteCopyWith get copyWith => _$QuoteCopyWithImpl(this as Quote, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is Quote&&(identical(other.id, id) || other.id == id)&&(identical(other.author, author) || other.author == author)&&(identical(other.body, body) || other.body == body)); +} + + +@override +int get hashCode => Object.hash(runtimeType,id,author,body); + +@override +String toString() { + return 'Quote(id: $id, author: $author, body: $body)'; +} + + +} + +/// @nodoc +abstract mixin class $QuoteCopyWith<$Res> { + factory $QuoteCopyWith(Quote value, $Res Function(Quote) _then) = _$QuoteCopyWithImpl; +@useResult +$Res call({ + int id, String author, String body +}); + + + + +} +/// @nodoc +class _$QuoteCopyWithImpl<$Res> + implements $QuoteCopyWith<$Res> { + _$QuoteCopyWithImpl(this._self, this._then); + + final Quote _self; + final $Res Function(Quote) _then; + +/// Create a copy of Quote +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? author = null,Object? body = null,}) { + return _then(_self.copyWith( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as int,author: null == author ? _self.author : author // ignore: cast_nullable_to_non_nullable +as String,body: null == body ? _self.body : body // ignore: cast_nullable_to_non_nullable +as String, + )); +} + +} + + +/// Adds pattern-matching-related methods to [Quote]. +extension QuotePatterns on Quote { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _Quote value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _Quote() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _Quote value) $default,){ +final _that = this; +switch (_that) { +case _Quote(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _Quote value)? $default,){ +final _that = this; +switch (_that) { +case _Quote() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( int id, String author, String body)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _Quote() when $default != null: +return $default(_that.id,_that.author,_that.body);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( int id, String author, String body) $default,) {final _that = this; +switch (_that) { +case _Quote(): +return $default(_that.id,_that.author,_that.body);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( int id, String author, String body)? $default,) {final _that = this; +switch (_that) { +case _Quote() when $default != null: +return $default(_that.id,_that.author,_that.body);case _: + return null; + +} +} + +} + +/// @nodoc + + +class _Quote implements Quote { + const _Quote({required this.id, required this.author, required this.body}); + + +@override final int id; +@override final String author; +@override final String body; + +/// Create a copy of Quote +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$QuoteCopyWith<_Quote> get copyWith => __$QuoteCopyWithImpl<_Quote>(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _Quote&&(identical(other.id, id) || other.id == id)&&(identical(other.author, author) || other.author == author)&&(identical(other.body, body) || other.body == body)); +} + + +@override +int get hashCode => Object.hash(runtimeType,id,author,body); + +@override +String toString() { + return 'Quote(id: $id, author: $author, body: $body)'; +} + + +} + +/// @nodoc +abstract mixin class _$QuoteCopyWith<$Res> implements $QuoteCopyWith<$Res> { + factory _$QuoteCopyWith(_Quote value, $Res Function(_Quote) _then) = __$QuoteCopyWithImpl; +@override @useResult +$Res call({ + int id, String author, String body +}); + + + + +} +/// @nodoc +class __$QuoteCopyWithImpl<$Res> + implements _$QuoteCopyWith<$Res> { + __$QuoteCopyWithImpl(this._self, this._then); + + final _Quote _self; + final $Res Function(_Quote) _then; + +/// Create a copy of Quote +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? author = null,Object? body = null,}) { + return _then(_Quote( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as int,author: null == author ? _self.author : author // ignore: cast_nullable_to_non_nullable +as String,body: null == body ? _self.body : body // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +// dart format on diff --git a/lib/features/quote/domain/entities/translation.dart b/lib/features/quote/domain/entities/translation.dart new file mode 100644 index 0000000..8761a1a --- /dev/null +++ b/lib/features/quote/domain/entities/translation.dart @@ -0,0 +1,14 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:kuwot/features/quote/data/models/translation_model.dart'; + +part 'translation.freezed.dart'; + +@freezed +abstract class Translation with _$Translation { + const factory Translation({required String id, required String language}) = + _Translation; + + static Translation fromModel(TranslationModel model) { + return Translation(id: model.id, language: model.lang); + } +} diff --git a/lib/features/quote/domain/entities/translation.freezed.dart b/lib/features/quote/domain/entities/translation.freezed.dart new file mode 100644 index 0000000..28a7ad3 --- /dev/null +++ b/lib/features/quote/domain/entities/translation.freezed.dart @@ -0,0 +1,274 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'translation.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$Translation { + + String get id; String get language; +/// Create a copy of Translation +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$TranslationCopyWith get copyWith => _$TranslationCopyWithImpl(this as Translation, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is Translation&&(identical(other.id, id) || other.id == id)&&(identical(other.language, language) || other.language == language)); +} + + +@override +int get hashCode => Object.hash(runtimeType,id,language); + +@override +String toString() { + return 'Translation(id: $id, language: $language)'; +} + + +} + +/// @nodoc +abstract mixin class $TranslationCopyWith<$Res> { + factory $TranslationCopyWith(Translation value, $Res Function(Translation) _then) = _$TranslationCopyWithImpl; +@useResult +$Res call({ + String id, String language +}); + + + + +} +/// @nodoc +class _$TranslationCopyWithImpl<$Res> + implements $TranslationCopyWith<$Res> { + _$TranslationCopyWithImpl(this._self, this._then); + + final Translation _self; + final $Res Function(Translation) _then; + +/// Create a copy of Translation +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? language = null,}) { + return _then(_self.copyWith( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as String,language: null == language ? _self.language : language // ignore: cast_nullable_to_non_nullable +as String, + )); +} + +} + + +/// Adds pattern-matching-related methods to [Translation]. +extension TranslationPatterns on Translation { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _Translation value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _Translation() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _Translation value) $default,){ +final _that = this; +switch (_that) { +case _Translation(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _Translation value)? $default,){ +final _that = this; +switch (_that) { +case _Translation() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( String id, String language)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _Translation() when $default != null: +return $default(_that.id,_that.language);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( String id, String language) $default,) {final _that = this; +switch (_that) { +case _Translation(): +return $default(_that.id,_that.language);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String id, String language)? $default,) {final _that = this; +switch (_that) { +case _Translation() when $default != null: +return $default(_that.id,_that.language);case _: + return null; + +} +} + +} + +/// @nodoc + + +class _Translation implements Translation { + const _Translation({required this.id, required this.language}); + + +@override final String id; +@override final String language; + +/// Create a copy of Translation +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$TranslationCopyWith<_Translation> get copyWith => __$TranslationCopyWithImpl<_Translation>(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _Translation&&(identical(other.id, id) || other.id == id)&&(identical(other.language, language) || other.language == language)); +} + + +@override +int get hashCode => Object.hash(runtimeType,id,language); + +@override +String toString() { + return 'Translation(id: $id, language: $language)'; +} + + +} + +/// @nodoc +abstract mixin class _$TranslationCopyWith<$Res> implements $TranslationCopyWith<$Res> { + factory _$TranslationCopyWith(_Translation value, $Res Function(_Translation) _then) = __$TranslationCopyWithImpl; +@override @useResult +$Res call({ + String id, String language +}); + + + + +} +/// @nodoc +class __$TranslationCopyWithImpl<$Res> + implements _$TranslationCopyWith<$Res> { + __$TranslationCopyWithImpl(this._self, this._then); + + final _Translation _self; + final $Res Function(_Translation) _then; + +/// Create a copy of Translation +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? language = null,}) { + return _then(_Translation( +id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable +as String,language: null == language ? _self.language : language // ignore: cast_nullable_to_non_nullable +as String, + )); +} + + +} + +// dart format on diff --git a/lib/features/quote/domain/repositories/quote_repository.dart b/lib/features/quote/domain/repositories/quote_repository.dart new file mode 100644 index 0000000..1810714 --- /dev/null +++ b/lib/features/quote/domain/repositories/quote_repository.dart @@ -0,0 +1,19 @@ +import 'package:fpdart/fpdart.dart'; +import 'package:kuwot/core/data/local/translation_target_config.dart'; +import 'package:kuwot/core/error/failure.dart'; +import 'package:kuwot/features/quote/domain/entities/background_image.dart'; +import 'package:kuwot/features/quote/domain/entities/quote.dart'; +import 'package:kuwot/features/quote/domain/entities/translation.dart'; + +abstract class QuoteRepository { + Future>> getBackgroundImages(); + + Future> getQuote(TranslationTarget? translationTarget); + + Future> getTranslatedQuote( + int id, + TranslationTarget translationTarget, + ); + + Future>> getTranslations(); +} diff --git a/lib/features/quote/domain/use_cases/get_background_images.dart b/lib/features/quote/domain/use_cases/get_background_images.dart new file mode 100644 index 0000000..4ae111f --- /dev/null +++ b/lib/features/quote/domain/use_cases/get_background_images.dart @@ -0,0 +1,17 @@ +import 'package:fpdart/fpdart.dart'; +import 'package:kuwot/core/domain/no_params.dart'; +import 'package:kuwot/core/domain/use_case.dart'; +import 'package:kuwot/core/error/failure.dart'; +import 'package:kuwot/features/quote/domain/entities/background_image.dart'; +import 'package:kuwot/features/quote/domain/repositories/quote_repository.dart'; + +class GetBackgroundImages extends UseCase, NoParams> { + final QuoteRepository _repository; + + GetBackgroundImages(QuoteRepository repository) : _repository = repository; + + @override + Future>> call(NoParams params) async { + return await _repository.getBackgroundImages(); + } +} diff --git a/lib/features/quote/domain/use_cases/get_quote.dart b/lib/features/quote/domain/use_cases/get_quote.dart new file mode 100644 index 0000000..a3689fd --- /dev/null +++ b/lib/features/quote/domain/use_cases/get_quote.dart @@ -0,0 +1,27 @@ +import 'package:equatable/equatable.dart'; +import 'package:fpdart/fpdart.dart'; +import 'package:kuwot/core/data/local/translation_target_config.dart'; +import 'package:kuwot/core/domain/use_case.dart'; +import 'package:kuwot/core/error/failure.dart'; +import 'package:kuwot/features/quote/domain/entities/quote.dart'; +import 'package:kuwot/features/quote/domain/repositories/quote_repository.dart'; + +class GetQuote extends UseCase { + final QuoteRepository _repository; + + GetQuote(QuoteRepository repository) : _repository = repository; + + @override + Future> call(GetQuoteParams params) { + return _repository.getQuote(params.translationTarget); + } +} + +class GetQuoteParams extends Equatable { + final TranslationTarget? translationTarget; + + const GetQuoteParams(this.translationTarget); + + @override + List get props => [translationTarget]; +} diff --git a/lib/features/quote/domain/use_cases/get_translated_quote.dart b/lib/features/quote/domain/use_cases/get_translated_quote.dart new file mode 100644 index 0000000..a8f7a49 --- /dev/null +++ b/lib/features/quote/domain/use_cases/get_translated_quote.dart @@ -0,0 +1,34 @@ +import 'package:equatable/equatable.dart'; +import 'package:fpdart/fpdart.dart'; +import 'package:kuwot/core/data/local/translation_target_config.dart'; +import 'package:kuwot/core/domain/use_case.dart'; +import 'package:kuwot/core/error/failure.dart'; +import 'package:kuwot/features/quote/domain/entities/quote.dart'; +import 'package:kuwot/features/quote/domain/repositories/quote_repository.dart'; + +class GetTranslatedQuote extends UseCase { + final QuoteRepository _repository; + + GetTranslatedQuote(QuoteRepository repository) : _repository = repository; + + @override + Future> call(GetTranslatedQuoteParams params) async { + return await _repository.getTranslatedQuote( + params.id, + params.translationTarget, + ); + } +} + +class GetTranslatedQuoteParams extends Equatable { + final int id; + final TranslationTarget translationTarget; + + const GetTranslatedQuoteParams({ + required this.id, + required this.translationTarget, + }); + + @override + List get props => [id, translationTarget]; +} diff --git a/lib/features/quote/domain/use_cases/get_translations.dart b/lib/features/quote/domain/use_cases/get_translations.dart new file mode 100644 index 0000000..8cd0eb6 --- /dev/null +++ b/lib/features/quote/domain/use_cases/get_translations.dart @@ -0,0 +1,17 @@ +import 'package:fpdart/fpdart.dart'; +import 'package:kuwot/core/domain/no_params.dart'; +import 'package:kuwot/core/domain/use_case.dart'; +import 'package:kuwot/core/error/failure.dart'; +import 'package:kuwot/features/quote/domain/entities/translation.dart'; +import 'package:kuwot/features/quote/domain/repositories/quote_repository.dart'; + +class GetTranslations extends UseCase, NoParams> { + final QuoteRepository _repository; + + GetTranslations(QuoteRepository repository) : _repository = repository; + + @override + Future>> call(NoParams params) { + return _repository.getTranslations(); + } +} diff --git a/lib/features/quote/presentation/bloc/background_images_bloc.dart b/lib/features/quote/presentation/bloc/background_images_bloc.dart new file mode 100644 index 0000000..4a58af9 --- /dev/null +++ b/lib/features/quote/presentation/bloc/background_images_bloc.dart @@ -0,0 +1,37 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:kuwot/core/domain/no_params.dart'; +import 'package:kuwot/core/presentation/bloc/error_state.dart'; +import 'package:kuwot/features/quote/domain/entities/background_image.dart'; +import 'package:kuwot/features/quote/domain/use_cases/get_background_images.dart'; + +part 'background_images_events.dart'; +part 'background_images_states.dart'; + +class BackgroundImagesBloc + extends Bloc { + final GetBackgroundImages getBackgroundImages; + + BackgroundImagesBloc({required this.getBackgroundImages}) + : super(const BackgroundImagesInitialState()) { + on(_onGetBackgroundImages); + } + + Future _onGetBackgroundImages( + GetBackgroundImagesEvent event, + Emitter emit, + ) async { + emit(const BackgroundImagesLoadingState()); + + final result = await getBackgroundImages(const NoParams()); + result.fold( + (failure) => emit( + BackgroundImagesErrorState( + message: failure.message, + cause: failure.cause, + ), + ), + (photos) => emit(BackgroundImagesLoadedState(photos)), + ); + } +} diff --git a/lib/features/quote/presentation/bloc/background_images_events.dart b/lib/features/quote/presentation/bloc/background_images_events.dart new file mode 100644 index 0000000..bb6261c --- /dev/null +++ b/lib/features/quote/presentation/bloc/background_images_events.dart @@ -0,0 +1,12 @@ +part of 'background_images_bloc.dart'; + +abstract class BackgroundImagesEvent extends Equatable { + const BackgroundImagesEvent(); +} + +class GetBackgroundImagesEvent extends BackgroundImagesEvent { + const GetBackgroundImagesEvent(); + + @override + List get props => []; +} diff --git a/lib/features/quote/presentation/bloc/background_images_states.dart b/lib/features/quote/presentation/bloc/background_images_states.dart new file mode 100644 index 0000000..a67a114 --- /dev/null +++ b/lib/features/quote/presentation/bloc/background_images_states.dart @@ -0,0 +1,45 @@ +part of 'background_images_bloc.dart'; + +abstract class BackgroundImagesState extends Equatable { + const BackgroundImagesState(); + + @override + String toString() => runtimeType.toString(); +} + +class BackgroundImagesInitialState extends BackgroundImagesState { + const BackgroundImagesInitialState(); + + @override + List get props => []; +} + +class BackgroundImagesLoadingState extends BackgroundImagesState { + const BackgroundImagesLoadingState(); + + @override + List get props => []; +} + +class BackgroundImagesLoadedState extends BackgroundImagesState { + final List backgroundImages; + + const BackgroundImagesLoadedState(this.backgroundImages); + + @override + List get props => [backgroundImages]; +} + +class BackgroundImagesErrorState extends BackgroundImagesState + implements ErrorState { + @override + final String message; + + @override + final Exception? cause; + + const BackgroundImagesErrorState({required this.message, this.cause}); + + @override + List get props => [message, cause]; +} diff --git a/lib/features/quote/presentation/bloc/quote_bloc.dart b/lib/features/quote/presentation/bloc/quote_bloc.dart new file mode 100644 index 0000000..803568c --- /dev/null +++ b/lib/features/quote/presentation/bloc/quote_bloc.dart @@ -0,0 +1,83 @@ +import 'package:bloc_concurrency/bloc_concurrency.dart'; +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:kuwot/core/data/local/config.dart'; +import 'package:kuwot/core/data/local/translation_target_config.dart'; +import 'package:kuwot/core/presentation/bloc/error_state.dart'; +import 'package:kuwot/features/quote/domain/entities/quote.dart'; +import 'package:kuwot/features/quote/domain/use_cases/get_quote.dart'; +import 'package:kuwot/features/quote/domain/use_cases/get_translated_quote.dart'; + +part 'quote_events.dart'; +part 'quote_states.dart'; + +class QuoteBloc extends Bloc { + final GetQuote getQuote; + final GetTranslatedQuote getTranslatedQuote; + final Config translationTargetConfig; + + int _originalQuoteId = -1; + + QuoteBloc({ + required this.getQuote, + required this.getTranslatedQuote, + required this.translationTargetConfig, + }) : super(const QuoteInitialState()) { + on(_onGetQuoteEvent, transformer: droppable()); + on( + _onGetTranslatedQuoteEvent, + transformer: droppable(), + ); + } + + Future _onGetQuoteEvent( + QuoteEvent event, + Emitter emit, + ) async { + emit(const QuoteLoadingState()); + + // add delay to limit the number of api calls + await Future.delayed(const Duration(seconds: 1)); + + // check if need to translate the quote + final translationTarget = await translationTargetConfig.get(); + + // get quote + final result = await getQuote(GetQuoteParams(translationTarget)); + result.fold((failure) => emit(QuoteErrorState(message: failure.message)), ( + quote, + ) { + _originalQuoteId = quote.id; + emit(QuoteLoadedState(quote: quote)); + }); + } + + Future _onGetTranslatedQuoteEvent( + GetTranslatedQuoteEvent event, + Emitter emit, + ) async { + emit(const QuoteLoadingState()); + + // add delay to limit the number of api calls + await Future.delayed(const Duration(seconds: 1)); + + // get translation target + final translationTarget = await translationTargetConfig.get(); + if (translationTarget == null) { + emit(const QuoteErrorState(message: 'Translation target is not set')); + return; + } + + // get translated quote + final result = await getTranslatedQuote( + GetTranslatedQuoteParams( + id: _originalQuoteId, + translationTarget: translationTarget, + ), + ); + result.fold( + (failure) => emit(QuoteErrorState(message: failure.message)), + (quote) => emit(QuoteLoadedState(quote: quote)), + ); + } +} diff --git a/lib/features/quote/presentation/bloc/quote_events.dart b/lib/features/quote/presentation/bloc/quote_events.dart new file mode 100644 index 0000000..028d278 --- /dev/null +++ b/lib/features/quote/presentation/bloc/quote_events.dart @@ -0,0 +1,21 @@ +part of 'quote_bloc.dart'; + +abstract class QuoteEvent extends Equatable { + const QuoteEvent(); +} + +class GetQuoteEvent extends QuoteEvent { + const GetQuoteEvent(); + + @override + List get props => []; +} + +class GetTranslatedQuoteEvent extends QuoteEvent { + final TranslationTarget translationTarget; + + const GetTranslatedQuoteEvent(this.translationTarget); + + @override + List get props => [translationTarget]; +} diff --git a/lib/features/quote/presentation/bloc/quote_states.dart b/lib/features/quote/presentation/bloc/quote_states.dart new file mode 100644 index 0000000..71c24b0 --- /dev/null +++ b/lib/features/quote/presentation/bloc/quote_states.dart @@ -0,0 +1,44 @@ +part of 'quote_bloc.dart'; + +abstract class QuoteState extends Equatable { + const QuoteState(); + + @override + String toString() => runtimeType.toString(); +} + +class QuoteInitialState extends QuoteState { + const QuoteInitialState(); + + @override + List get props => []; +} + +class QuoteLoadingState extends QuoteState { + const QuoteLoadingState(); + + @override + List get props => []; +} + +class QuoteLoadedState extends QuoteState { + final Quote quote; + + const QuoteLoadedState({required this.quote}); + + @override + List get props => [quote]; +} + +class QuoteErrorState extends QuoteState implements ErrorState { + @override + final String message; + + @override + final Exception? cause; + + const QuoteErrorState({required this.message, this.cause}); + + @override + List get props => [message, cause]; +} diff --git a/lib/features/quote/presentation/bloc/translations_bloc.dart b/lib/features/quote/presentation/bloc/translations_bloc.dart new file mode 100644 index 0000000..f9683eb --- /dev/null +++ b/lib/features/quote/presentation/bloc/translations_bloc.dart @@ -0,0 +1,31 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:kuwot/core/domain/no_params.dart'; +import 'package:kuwot/core/presentation/bloc/error_state.dart'; +import 'package:kuwot/features/quote/domain/entities/translation.dart'; +import 'package:kuwot/features/quote/domain/use_cases/get_translations.dart'; + +part 'translations_events.dart'; +part 'translations_states.dart'; + +class TranslationsBloc extends Bloc { + final GetTranslations getTranslations; + + TranslationsBloc({required this.getTranslations}) + : super(const TranslationsInitialState()) { + on(_onGetTranslationEvent); + } + + Future _onGetTranslationEvent( + TranslationsEvent event, + Emitter emit, + ) async { + emit(const TranslationsLoadingState()); + final translations = await getTranslations(const NoParams()); + translations.fold( + (failure) => emit(TranslationsErrorState(message: failure.message)), + (translations) => + emit(TranslationsLoadedState(translations: translations)), + ); + } +} diff --git a/lib/features/quote/presentation/bloc/translations_events.dart b/lib/features/quote/presentation/bloc/translations_events.dart new file mode 100644 index 0000000..45725fb --- /dev/null +++ b/lib/features/quote/presentation/bloc/translations_events.dart @@ -0,0 +1,12 @@ +part of 'translations_bloc.dart'; + +abstract class TranslationsEvent extends Equatable { + const TranslationsEvent(); +} + +class GetTranslationsEvent extends TranslationsEvent { + const GetTranslationsEvent(); + + @override + List get props => []; +} diff --git a/lib/features/quote/presentation/bloc/translations_states.dart b/lib/features/quote/presentation/bloc/translations_states.dart new file mode 100644 index 0000000..cdb0e0d --- /dev/null +++ b/lib/features/quote/presentation/bloc/translations_states.dart @@ -0,0 +1,41 @@ +part of 'translations_bloc.dart'; + +abstract class TranslationsState extends Equatable { + const TranslationsState(); +} + +class TranslationsInitialState extends TranslationsState { + const TranslationsInitialState(); + + @override + List get props => []; +} + +class TranslationsLoadingState extends TranslationsState { + const TranslationsLoadingState(); + + @override + List get props => []; +} + +class TranslationsLoadedState extends TranslationsState { + final List translations; + + const TranslationsLoadedState({required this.translations}); + + @override + List get props => [translations]; +} + +class TranslationsErrorState extends TranslationsState implements ErrorState { + @override + final String message; + + @override + final Exception? cause; + + const TranslationsErrorState({required this.message, this.cause}); + + @override + List get props => [message, cause]; +} diff --git a/lib/features/quote/presentation/quote_page.dart b/lib/features/quote/presentation/quote_page.dart new file mode 100644 index 0000000..97f54dc --- /dev/null +++ b/lib/features/quote/presentation/quote_page.dart @@ -0,0 +1,209 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_svg/svg.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:kuwot/core/data/local/translation_target_config.dart'; +import 'package:kuwot/core/router/app_router.gr.dart'; +import 'package:kuwot/features/quote/data/data_sources/remote/kuwot_api_remote_data_source.dart'; +import 'package:kuwot/features/quote/presentation/bloc/background_images_bloc.dart'; +import 'package:kuwot/features/quote/presentation/bloc/quote_bloc.dart'; +import 'package:kuwot/features/quote/presentation/widgets/background_image_widget.dart'; +import 'package:kuwot/features/quote/presentation/widgets/quote_widget.dart'; +import 'package:kuwot/features/quote/presentation/widgets/translate_target_dialog.dart'; +import 'package:screenshot/screenshot.dart'; +import 'package:share_plus/share_plus.dart'; + +@RoutePage() +class QuotePage extends StatefulWidget { + const QuotePage({super.key}); + + @override + State createState() => _QuotePageState(); +} + +class _QuotePageState extends State { + final _screenshotController = ScreenshotController(); + int _backgroundIndex = 0; + bool _isSharingQuote = false; + + late QuoteBloc _dailyQuoteBloc; + late BackgroundImagesBloc _backgroundImagesBloc; + + @override + void initState() { + super.initState(); + + _dailyQuoteBloc = context.read(); + _backgroundImagesBloc = context.read(); + + // get daily quote & background photos + _dailyQuoteBloc.add(const GetQuoteEvent()); + _backgroundImagesBloc.add(const GetBackgroundImagesEvent()); + } + + @override + Widget build(BuildContext context) { + final header = Padding( + padding: const EdgeInsets.fromLTRB(24, 8, 16, 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Text('Kuwot', style: GoogleFonts.sriracha(fontSize: 30)), + const SizedBox(width: 2), + SvgPicture.asset( + 'assets/svgs/chat-quote.svg', + height: 24, + colorFilter: ColorFilter.mode( + Theme.of(context).colorScheme.onSurface, + BlendMode.srcIn, + ), + ), + ], + ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + IconButton( + onPressed: () { + context.router.push(const DonationRoute()); + }, + icon: const FaIcon(FontAwesomeIcons.mugHot), + ), + IconButton( + onPressed: () { + context.router.push(const AppSettingsRoute()); + }, + icon: const FaIcon(FontAwesomeIcons.sliders), + ), + ], + ), + ], + ), + ); + + final body = SafeArea( + child: Stack( + fit: StackFit.expand, + children: [ + Align(alignment: Alignment.topLeft, child: header), + Padding( + padding: const EdgeInsets.fromLTRB(24, 70, 24, 24), + child: _buildQuote(), + ), + ], + ), + ); + + return Scaffold(body: body); + } + + Widget _buildQuote() { + final screenshotEnabledQuote = Screenshot( + controller: _screenshotController, + child: Stack( + fit: StackFit.expand, + children: [ + BackgroundPhotoWidget( + backgroundIndex: _backgroundIndex, + hideImageInfoButton: _isSharingQuote, + ), + const Align(alignment: Alignment.center, child: QuoteWidget()), + ], + ), + ); + + final actionButtons = [ + Expanded( + child: _buildQuoteActionButton( + onPressed: () { + _dailyQuoteBloc.add(const GetQuoteEvent()); + }, + icon: const FaIcon(FontAwesomeIcons.quoteRight), + ), + ), + Expanded( + child: _buildQuoteActionButton( + onPressed: _cycleBackground, + icon: const FaIcon(FontAwesomeIcons.image), + ), + ), + Expanded( + child: _buildQuoteActionButton( + onPressed: () async { + final result = await showAdaptiveDialog( + context: context, + barrierDismissible: true, + builder: (context) => const TranslateTargetDialog(), + ); + + if (result != null) { + _dailyQuoteBloc.add(GetTranslatedQuoteEvent(result)); + } + }, + icon: const FaIcon(FontAwesomeIcons.language), + ), + ), + Expanded( + child: _buildQuoteActionButton( + onPressed: _shareQuote, + icon: const FaIcon(FontAwesomeIcons.shareNodes), + ), + ), + ]; + + return Card( + clipBehavior: Clip.antiAlias, + margin: const EdgeInsets.all(0), + elevation: 12, + child: Column( + children: [ + Expanded(child: screenshotEnabledQuote), + Row(children: actionButtons), + ], + ), + ); + } + + Widget _buildQuoteActionButton({ + required VoidCallback onPressed, + required Widget icon, + }) { + return InkWell( + onTap: onPressed, + child: Container( + height: 50, + alignment: Alignment.center, + padding: const EdgeInsets.all(8), + child: icon, + ), + ); + } + + void _cycleBackground() { + setState(() { + _backgroundIndex = ++_backgroundIndex % imagesPerPage; + }); + } + + Future _shareQuote() async { + setState(() => _isSharingQuote = true); + final image = await _screenshotController.capture(); + setState(() => _isSharingQuote = false); + if (image == null) return; + + final shareParams = ShareParams( + files: [ + XFile.fromData( + image, + mimeType: 'image/png', + name: 'kuwot_${DateTime.now().millisecondsSinceEpoch}.png', + ), + ], + ); + await SharePlus.instance.share(shareParams); + } +} diff --git a/lib/features/quote/presentation/widgets/about_image_dialog.dart b/lib/features/quote/presentation/widgets/about_image_dialog.dart new file mode 100644 index 0000000..6962998 --- /dev/null +++ b/lib/features/quote/presentation/widgets/about_image_dialog.dart @@ -0,0 +1,134 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:flutter/material.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:kuwot/features/quote/domain/entities/background_image.dart'; +import 'package:url_launcher/url_launcher_string.dart'; + +class AboutImageDialog extends StatelessWidget { + final BackgroundImage image; + + const AboutImageDialog({required this.image, super.key}); + + @override + Widget build(BuildContext context) { + final header = Padding( + padding: const EdgeInsets.fromLTRB(20, 16, 8, 16), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('About Image', style: GoogleFonts.sriracha(fontSize: 24)), + IconButton( + onPressed: () { + context.router.maybePop(); + }, + icon: const FaIcon(FontAwesomeIcons.xmark), + ), + ], + ), + ); + + final info = Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + CircleAvatar( + radius: 40, + child: ClipOval( + child: CachedNetworkImage( + imageUrl: image.authorProfileImageUrl, + placeholder: (context, url) => CircularProgressIndicator( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + ), + const SizedBox(height: 8), + Text( + image.authorName, + style: Theme.of(context).textTheme.titleLarge, + textAlign: TextAlign.center, + ), + Text(image.authorBio, textAlign: TextAlign.center), + const SizedBox(height: 4), + Wrap( + alignment: WrapAlignment.center, + children: [ + _buildUserInfoChip( + icon: FontAwesomeIcons.locationDot, + text: image.authorLocation, + ), + _buildUserInfoChip( + icon: FontAwesomeIcons.cameraRetro, + text: '${image.authorTotalPhotos} photos', + ), + _buildUserInfoChip( + icon: FontAwesomeIcons.thumbsUp, + text: '${image.authorTotalLikes} likes', + ), + image.authorIsForHire + ? _buildUserInfoChip( + icon: FontAwesomeIcons.handshake, + text: 'For hire', + ) + : const SizedBox.shrink(), + ], + ), + const SizedBox(height: 16), + Text( + image.description, + style: Theme.of( + context, + ).textTheme.bodyLarge?.copyWith(fontStyle: FontStyle.italic), + ), + ], + ), + ); + + final footer = Padding( + padding: const EdgeInsets.all(8), + child: Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: () { + launchUrlString(image.authorUrl); + }, + child: const Text('Author profile'), + ), + TextButton( + onPressed: () { + launchUrlString(image.originUrl); + }, + child: const Text('Original image'), + ), + ], + ), + ); + + return Dialog( + clipBehavior: Clip.antiAlias, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [header, const Divider(height: 1), info, footer], + ), + ); + } + + Widget _buildUserInfoChip({required IconData icon, required String text}) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + FaIcon(icon, size: 16), + const SizedBox(width: 4), + Flexible(child: Text(text)), + ], + ), + ); + } +} diff --git a/lib/features/quote/presentation/widgets/background_image_widget.dart b/lib/features/quote/presentation/widgets/background_image_widget.dart new file mode 100644 index 0000000..223b5d2 --- /dev/null +++ b/lib/features/quote/presentation/widgets/background_image_widget.dart @@ -0,0 +1,152 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import 'package:kuwot/core/presentation/error_retry_snackbar.dart'; +import 'package:kuwot/features/quote/data/data_sources/remote/kuwot_api_remote_data_source.dart'; +import 'package:kuwot/features/quote/presentation/bloc/background_images_bloc.dart'; +import 'package:kuwot/features/quote/presentation/widgets/about_image_dialog.dart'; +import 'package:kuwot/utilities.dart'; +import 'package:url_launcher/url_launcher_string.dart'; + +class BackgroundPhotoWidget extends StatelessWidget { + final int backgroundIndex; + final bool hideImageInfoButton; + + const BackgroundPhotoWidget({ + required this.backgroundIndex, + this.hideImageInfoButton = false, + super.key, + }) : assert(backgroundIndex < imagesPerPage); + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // handle error state + if (state is BackgroundImagesErrorState) { + ErrorRetrySnackbar.show( + context, + errorMessage: state.message, + onRetry: () { + context.read().add( + const GetBackgroundImagesEvent(), + ); + }, + ); + } + }, + builder: (context, state) { + if (state is BackgroundImagesLoadedState) { + const borderRadius = BorderRadius.only( + bottomLeft: Radius.circular(16), + ); + final imageInfoButton = Material( + color: Colors.black26, + borderRadius: borderRadius, + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () { + showAdaptiveDialog( + context: context, + barrierDismissible: true, + builder: (context) => AboutImageDialog( + image: state.backgroundImages[backgroundIndex], + ), + ); + }, + child: Container( + height: 40, + width: 40, + alignment: Alignment.center, + decoration: const BoxDecoration(borderRadius: borderRadius), + child: const FaIcon( + FontAwesomeIcons.circleInfo, + size: 20, + color: Colors.white54, + ), + ), + ), + ); + final imageAttribution = ColoredBox( + color: Colors.black38, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 2), + child: Wrap( + alignment: WrapAlignment.center, + children: [ + Text( + 'Photo by ', + style: Theme.of( + context, + ).textTheme.bodySmall?.copyWith(color: Colors.white54), + ), + GestureDetector( + child: Text( + state.backgroundImages[backgroundIndex].authorName, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + decoration: TextDecoration.underline, + color: Colors.white.withValues(alpha: 0.85), + decorationColor: Colors.white.withValues(alpha: 0.85), + ), + ), + onTap: () async { + await launchUrlString( + state.backgroundImages[backgroundIndex].authorUrl, + ); + }, + ), + Text( + ' on ', + style: Theme.of( + context, + ).textTheme.bodySmall?.copyWith(color: Colors.white54), + ), + GestureDetector( + child: Text( + 'Unsplash', + style: Theme.of(context).textTheme.bodySmall?.copyWith( + decoration: TextDecoration.underline, + color: Colors.white.withValues(alpha: 0.85), + decorationColor: Colors.white.withValues(alpha: 0.85), + ), + ), + onTap: () async { + await launchUrlString( + "https://unsplash.com?utm_source=kuwot&utm_medium=referral", + ); + }, + ), + ], + ), + ), + ); + + return Stack( + fit: StackFit.expand, + children: [ + CachedNetworkImage( + imageUrl: state.backgroundImages[backgroundIndex].url, + fit: BoxFit.cover, + placeholder: (_, _) { + final avgColor = + state.backgroundImages[backgroundIndex].color; + return Container(color: getColorFromHexString(avgColor)); + }, + errorWidget: (_, _, _) { + return Container(color: Colors.grey); + }, + ), + hideImageInfoButton + ? const SizedBox() + : Positioned(top: 0, right: 0, child: imageInfoButton), + Positioned(bottom: 0, left: 0, right: 0, child: imageAttribution), + ], + ); + } + + return Container(color: Colors.grey); + }, + ); + } +} diff --git a/lib/features/quote/presentation/widgets/quote_widget.dart b/lib/features/quote/presentation/widgets/quote_widget.dart new file mode 100644 index 0000000..ddcc1cc --- /dev/null +++ b/lib/features/quote/presentation/widgets/quote_widget.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_svg/svg.dart'; +import 'package:kuwot/core/presentation/error_retry_snackbar.dart'; +import 'package:kuwot/features/quote/presentation/bloc/quote_bloc.dart'; + +class QuoteWidget extends StatefulWidget { + const QuoteWidget({super.key}); + + @override + State createState() => _QuoteWidgetState(); +} + +class _QuoteWidgetState extends State + with SingleTickerProviderStateMixin { + late AnimationController _animationController; + + String? _quoteBody; + String? _quoteAuthor; + + @override + void initState() { + super.initState(); + + // init animation + _animationController = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 500), + ); + _animationController.addListener(() => setState(() {})); + } + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, state) { + // animate quote loading state + if (state is QuoteLoadingState) { + _animationController.repeat(reverse: true); + } else { + _animationController.forward(); + } + + // handle error state + if (state is QuoteErrorState) { + ErrorRetrySnackbar.show( + context, + errorMessage: state.message, + onRetry: () { + context.read().add(const GetQuoteEvent()); + }, + ); + } + }, + builder: (context, state) { + if (state is QuoteLoadedState) { + _quoteBody = state.quote.body; + _quoteAuthor = state.quote.author; + } + + return Container( + decoration: BoxDecoration( + color: Colors.black54, + borderRadius: BorderRadius.circular(16), + ), + padding: const EdgeInsets.all(16.0), + margin: const EdgeInsets.all(16.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Opacity( + opacity: _animationController.value, + child: SvgPicture.asset( + 'assets/svgs/chat-quote-fill.svg', + height: 54, + colorFilter: const ColorFilter.mode( + Colors.white54, + BlendMode.srcIn, + ), + ), + ), + const SizedBox(height: 30), + Text( + _quoteBody ?? '...', + style: Theme.of( + context, + ).textTheme.headlineSmall?.copyWith(color: Colors.white), + textAlign: TextAlign.center, + ), + const SizedBox(height: 30), + Text( + '- ${_quoteAuthor ?? 'Kuwot'}', + style: Theme.of( + context, + ).textTheme.bodyLarge?.copyWith(color: Colors.white), + textAlign: TextAlign.right, + ), + ], + ), + ); + }, + ); + } + + @override + void dispose() { + _animationController.dispose(); + super.dispose(); + } +} diff --git a/lib/features/quote/presentation/widgets/translate_target_dialog.dart b/lib/features/quote/presentation/widgets/translate_target_dialog.dart new file mode 100644 index 0000000..90626e2 --- /dev/null +++ b/lib/features/quote/presentation/widgets/translate_target_dialog.dart @@ -0,0 +1,104 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import 'package:google_fonts/google_fonts.dart'; +import 'package:kuwot/core/data/local/translation_target_config.dart'; +import 'package:kuwot/core/presentation/bloc/config/translation_target_cubit.dart'; +import 'package:kuwot/features/quote/presentation/bloc/translations_bloc.dart'; + +class TranslateTargetDialog extends StatefulWidget { + const TranslateTargetDialog({super.key}); + + @override + State createState() => _TranslateTargetDialogState(); +} + +class _TranslateTargetDialogState extends State { + @override + void initState() { + super.initState(); + + // load translations + context.read().add(const GetTranslationsEvent()); + } + + @override + Widget build(BuildContext context) { + final header = Padding( + padding: const EdgeInsets.fromLTRB(20, 16, 8, 16), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('Quote Language', style: GoogleFonts.sriracha(fontSize: 24)), + IconButton( + onPressed: () { + Navigator.of(context).pop(null); + }, + icon: const FaIcon(FontAwesomeIcons.xmark), + ), + ], + ), + ); + + final currentTranslationTarget = context + .read() + .state; + + final languageList = SizedBox( + height: MediaQuery.of(context).size.height / 2, + child: BlocBuilder( + builder: (context, state) { + if (state is TranslationsLoadedState) { + final translations = state.translations; + + return ListView.builder( + padding: EdgeInsets.zero, + itemCount: translations.length, + itemBuilder: (context, index) { + final isSelected = + currentTranslationTarget.id == translations[index].id; + return ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 20), + title: Text( + translations[index].language, + style: Theme.of(context).textTheme.bodyLarge?.copyWith( + fontWeight: isSelected + ? FontWeight.bold + : FontWeight.normal, + ), + ), + trailing: isSelected + ? const FaIcon(FontAwesomeIcons.check) + : null, + onTap: () { + final translationTarget = TranslationTarget( + id: translations[index].id, + name: translations[index].language, + ); + context.read().set( + translationTarget, + ); + Navigator.of( + context, + ).pop(translationTarget); + }, + ); + }, + ); + } + + return const Center(child: CircularProgressIndicator()); + }, + ), + ); + + return Dialog( + clipBehavior: Clip.antiAlias, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [header, const Divider(height: 1), languageList], + ), + ); + } +} diff --git a/lib/injection_container.dart b/lib/injection_container.dart new file mode 100644 index 0000000..88a512f --- /dev/null +++ b/lib/injection_container.dart @@ -0,0 +1,159 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:get_it/get_it.dart'; +import 'package:in_app_purchase/in_app_purchase.dart'; +import 'package:kuwot/core/app_updater.dart'; +import 'package:kuwot/core/data/local/config.dart'; +import 'package:kuwot/core/data/local/theme_mode_config.dart'; +import 'package:kuwot/core/data/local/translation_target_config.dart'; +import 'package:kuwot/core/env.dart'; +import 'package:kuwot/core/network/network.dart'; +import 'package:kuwot/core/presentation/bloc/config/theme_mode_cubit.dart'; +import 'package:kuwot/core/presentation/bloc/config/translation_target_cubit.dart'; +import 'package:kuwot/core/time.dart'; +import 'package:kuwot/features/in_app_purchase/data/data_sources/remote/in_app_purchase_remote_data_source.dart'; +import 'package:kuwot/features/in_app_purchase/data/repositories/in_app_purchase_repository_impl.dart'; +import 'package:kuwot/features/in_app_purchase/domain/repositories/in_app_purchase_repository.dart'; +import 'package:kuwot/features/in_app_purchase/domain/use_case/get_consumable_products.dart'; +import 'package:kuwot/features/in_app_purchase/domain/use_case/listen_purchase.dart'; +import 'package:kuwot/features/in_app_purchase/domain/use_case/purchase_consumable_product.dart'; +import 'package:kuwot/features/in_app_purchase/presentation/bloc/in_app_purchase_bloc.dart'; +import 'package:kuwot/features/in_app_purchase/presentation/bloc/purchase_details_cubit.dart'; +import 'package:kuwot/features/in_app_update/presentation/bloc/in_app_update_bloc.dart'; +import 'package:kuwot/features/quote/data/data_sources/remote/kuwot_api_remote_data_source.dart'; +import 'package:kuwot/features/quote/data/repositories/quote_repository_impl.dart'; +import 'package:kuwot/features/quote/domain/repositories/quote_repository.dart'; +import 'package:kuwot/features/quote/domain/use_cases/get_background_images.dart'; +import 'package:kuwot/features/quote/domain/use_cases/get_quote.dart'; +import 'package:kuwot/features/quote/domain/use_cases/get_translated_quote.dart'; +import 'package:kuwot/features/quote/domain/use_cases/get_translations.dart'; +import 'package:kuwot/features/quote/presentation/bloc/background_images_bloc.dart'; +import 'package:kuwot/features/quote/presentation/bloc/quote_bloc.dart'; +import 'package:kuwot/features/quote/presentation/bloc/translations_bloc.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +final getIt = GetIt.instance; + +void setup() { + // network + getIt.registerLazySingleton(() => NetworkImpl()); + + // shared preferences + getIt.registerSingletonAsync(() async { + final prefs = await SharedPreferences.getInstance(); + return prefs; + }); + + // env + getIt.registerLazySingleton(() => EnvImpl()); + + // configs + getIt.registerSingletonWithDependencies>( + () => ThemeModeConfig(sharedPreferences: getIt()), + dependsOn: [SharedPreferences], + ); + getIt.registerSingletonWithDependencies>( + () => TranslationTargetConfig(sharedPreferences: getIt()), + dependsOn: [SharedPreferences], + ); + + // data sources + getIt.registerLazySingleton( + () => KuwotApiRemoteApiImpl(env: getIt(), network: getIt()), + ); + getIt.registerLazySingleton( + () => InAppPurchaseRemoteDataSourceImpl(iap: getIt()), + ); + + // repositories + getIt.registerLazySingleton( + () => QuoteRepositoryImpl(quoteDataSource: getIt()), + ); + getIt.registerLazySingleton( + () => InAppPurchaseRepositoryImpl(inAppPurchaseDataSource: getIt()), + ); + + // use cases + getIt.registerLazySingleton(() => GetQuote(getIt())); + getIt.registerLazySingleton( + () => GetTranslatedQuote(getIt()), + ); + getIt.registerLazySingleton( + () => GetBackgroundImages(getIt()), + ); + getIt.registerLazySingleton(() => GetTranslations(getIt())); + getIt.registerLazySingleton( + () => GetConsumableProducts(getIt()), + ); + getIt.registerLazySingleton( + () => PurchaseConsumableProduct(getIt()), + ); + getIt.registerLazySingleton(() => ListenPurchase(getIt())); + + // blocs + getIt.registerSingletonAsync(() async { + final initialThemeMode = await getIt>().get(); + return ThemeModeCubit( + themeModeConfig: getIt(), + initialThemeMode: initialThemeMode ?? ThemeMode.system, + ); + }, dependsOn: [SharedPreferences, Config]); + getIt.registerLazySingleton( + () => InAppUpdateBloc(appUpdater: getIt()), + ); + getIt.registerLazySingleton( + () => InAppPurchaseBloc( + getConsumableProducts: getIt(), + purchaseConsumableProduct: getIt(), + ), + ); + getIt.registerLazySingleton( + () => PurchaseDetailsCubit(getIt()), + ); + getIt.registerSingletonAsync(() async { + final initialTranslationTarget = await getIt>() + .get(); + return TranslationTargetCubit( + translationTargetConfig: getIt(), + initialTranslationTarget: + initialTranslationTarget ?? defaultTranslationTarget, + ); + }, dependsOn: [SharedPreferences, Config]); + getIt.registerFactory( + () => QuoteBloc( + getQuote: getIt(), + getTranslatedQuote: getIt(), + translationTargetConfig: getIt(), + ), + ); + getIt.registerFactory( + () => BackgroundImagesBloc(getBackgroundImages: getIt()), + ); + getIt.registerFactory( + () => TranslationsBloc(getTranslations: getIt()), + ); + + // others + getIt.registerLazySingleton(() => AppUpdaterImpl()); + getIt.registerLazySingleton