Repository: yukino-app/yukino Branch: next Commit: b06f52e9f616 Files: 211 Total size: 286.0 KB Directory structure: gitextract_eju0jcu_/ ├── .github/ │ └── workflows/ │ └── code-analysis.yml ├── .gitignore ├── .metadata ├── .phrasey/ │ ├── config.toml │ ├── hooks/ │ │ ├── dart-sync.js │ │ └── utils.js │ └── schema.toml ├── .prettierrc ├── .vscode/ │ └── settings.json ├── LICENSE ├── README.md ├── analysis_options.yaml ├── android/ │ ├── .gitignore │ ├── app/ │ │ ├── build.gradle │ │ └── src/ │ │ ├── debug/ │ │ │ └── AndroidManifest.xml │ │ ├── main/ │ │ │ ├── AndroidManifest.xml │ │ │ ├── java/ │ │ │ │ └── io/ │ │ │ │ └── flutter/ │ │ │ │ └── app/ │ │ │ │ └── FlutterMultiDexApplication.java │ │ │ ├── kotlin/ │ │ │ │ └── com/ │ │ │ │ └── example/ │ │ │ │ └── kazahana/ │ │ │ │ └── MainActivity.kt │ │ │ └── res/ │ │ │ ├── drawable/ │ │ │ │ └── launch_background.xml │ │ │ ├── drawable-v21/ │ │ │ │ └── launch_background.xml │ │ │ ├── values/ │ │ │ │ └── styles.xml │ │ │ └── values-night/ │ │ │ └── styles.xml │ │ └── profile/ │ │ └── AndroidManifest.xml │ ├── build.gradle │ ├── gradle/ │ │ └── wrapper/ │ │ └── gradle-wrapper.properties │ ├── gradle.properties │ └── settings.gradle ├── cli/ │ ├── code_analysis.dart │ ├── prerequisites.dart │ ├── run.dart │ ├── tasks/ │ │ ├── build_runner.dart │ │ ├── i18n.dart │ │ ├── icon.dart │ │ ├── meta.dart │ │ └── version.dart │ └── utils/ │ ├── exports.dart │ ├── logger.dart │ └── paths.dart ├── i18n/ │ └── en.toml ├── lib/ │ ├── core/ │ │ ├── anilist/ │ │ │ ├── auth.dart │ │ │ ├── credentials.dart │ │ │ ├── exports.dart │ │ │ └── translations.dart │ │ ├── app/ │ │ │ ├── events.dart │ │ │ ├── exports.dart │ │ │ ├── loader.dart │ │ │ └── meta.dart │ │ ├── database/ │ │ │ ├── cache/ │ │ │ │ ├── database.dart │ │ │ │ └── exports.dart │ │ │ ├── exports.dart │ │ │ ├── secure/ │ │ │ │ ├── database.dart │ │ │ │ ├── exports.dart │ │ │ │ └── schema.dart │ │ │ └── settings/ │ │ │ ├── database.dart │ │ │ ├── exports.dart │ │ │ └── schema.dart │ │ ├── exports.dart │ │ ├── internals/ │ │ │ ├── deeplink.dart │ │ │ ├── exports.dart │ │ │ └── router/ │ │ │ ├── exports.dart │ │ │ ├── route.dart │ │ │ ├── routes/ │ │ │ │ ├── anilist.dart │ │ │ │ └── exports.dart │ │ │ └── routes.dart │ │ ├── packages.dart │ │ ├── paths.dart │ │ ├── player/ │ │ │ └── video_player.dart │ │ ├── state/ │ │ │ ├── exports.dart │ │ │ ├── states.dart │ │ │ └── value.dart │ │ ├── tenka/ │ │ │ ├── exports.dart │ │ │ ├── manager.dart │ │ │ └── utils.dart │ │ ├── themes/ │ │ │ ├── colors.dart │ │ │ ├── exports.dart │ │ │ └── fonts.dart │ │ ├── translator/ │ │ │ ├── exports.dart │ │ │ └── translator.dart │ │ └── utils/ │ │ ├── dates.dart │ │ ├── durations.dart │ │ ├── exports.dart │ │ ├── kawaii_faces.dart │ │ └── provider.dart │ ├── main.dart │ └── ui/ │ ├── base.dart │ ├── components/ │ │ ├── anilist/ │ │ │ ├── exports.dart │ │ │ ├── media_row.dart │ │ │ ├── media_slide.dart │ │ │ └── media_tile.dart │ │ ├── body_padding.dart │ │ ├── cross_draggable_scroll_behaviour.dart │ │ ├── exports.dart │ │ ├── kawaii_face.dart │ │ ├── rounded_back_button.dart │ │ ├── scrollable_row.dart │ │ ├── slideshow.dart │ │ ├── stated_builder.dart │ │ ├── super_imposer.dart │ │ └── toast.dart │ ├── exports.dart │ ├── keys.dart │ ├── pages/ │ │ ├── _home/ │ │ │ ├── components/ │ │ │ │ ├── appbar.dart │ │ │ │ ├── body.dart │ │ │ │ ├── bottombar.dart │ │ │ │ └── exports.dart │ │ │ ├── provider.dart │ │ │ └── view.dart │ │ ├── _splash/ │ │ │ └── view.dart │ │ ├── anilist/ │ │ │ ├── components/ │ │ │ │ ├── body/ │ │ │ │ │ ├── exports.dart │ │ │ │ │ ├── login.dart │ │ │ │ │ └── profile/ │ │ │ │ │ ├── body.dart │ │ │ │ │ ├── exports.dart │ │ │ │ │ ├── hero.dart │ │ │ │ │ ├── provider.dart │ │ │ │ │ └── wrapper.dart │ │ │ │ └── exports.dart │ │ │ ├── provider.dart │ │ │ ├── route.dart │ │ │ └── view.dart │ │ ├── home/ │ │ │ ├── route.dart │ │ │ └── view.dart │ │ ├── modules/ │ │ │ ├── provider.dart │ │ │ ├── route.dart │ │ │ └── view.dart │ │ ├── search/ │ │ │ ├── components/ │ │ │ │ ├── exports.dart │ │ │ │ ├── results_grid.dart │ │ │ │ └── search_bar.dart │ │ │ ├── provider.dart │ │ │ ├── route.dart │ │ │ └── view.dart │ │ ├── settings/ │ │ │ ├── components/ │ │ │ │ ├── appearance.dart │ │ │ │ ├── exports.dart │ │ │ │ └── tiles/ │ │ │ │ ├── choice.dart │ │ │ │ ├── exports.dart │ │ │ │ └── wrapper.dart │ │ │ ├── route.dart │ │ │ └── view.dart │ │ └── view/ │ │ ├── components/ │ │ │ ├── appbar.dart │ │ │ ├── body.dart │ │ │ ├── content/ │ │ │ │ ├── content.dart │ │ │ │ ├── exports.dart │ │ │ │ └── provider.dart │ │ │ ├── exports.dart │ │ │ ├── hero.dart │ │ │ └── overview.dart │ │ ├── provider.dart │ │ ├── route.dart │ │ └── view.dart │ ├── router/ │ │ ├── exports.dart │ │ ├── navigator.dart │ │ └── route/ │ │ ├── exports.dart │ │ ├── info.dart │ │ ├── page.dart │ │ └── pages.dart │ └── utils/ │ ├── animations.dart │ ├── exports.dart │ ├── placeholders.dart │ ├── relative_scale.dart │ ├── themer.dart │ └── translations.dart ├── linux/ │ ├── .gitignore │ ├── CMakeLists.txt │ ├── flutter/ │ │ ├── CMakeLists.txt │ │ ├── generated_plugin_registrant.cc │ │ ├── generated_plugin_registrant.h │ │ └── generated_plugins.cmake │ ├── main.cc │ ├── my_application.cc │ └── my_application.h ├── package.json ├── packages/ │ ├── anilist/ │ │ ├── .gitignore │ │ ├── .vscode/ │ │ │ └── settings.json │ │ ├── README.md │ │ ├── analysis_options.yaml │ │ ├── lib/ │ │ │ ├── anilist.dart │ │ │ ├── endpoints/ │ │ │ │ ├── exports.dart │ │ │ │ ├── graphql.dart │ │ │ │ ├── media.dart │ │ │ │ ├── media_list.dart │ │ │ │ ├── relation.dart │ │ │ │ └── user.dart │ │ │ ├── models/ │ │ │ │ ├── character.dart │ │ │ │ ├── character_edge.dart │ │ │ │ ├── character_role.dart │ │ │ │ ├── exports.dart │ │ │ │ ├── fuzzy_date.dart │ │ │ │ ├── media.dart │ │ │ │ ├── media_format.dart │ │ │ │ ├── media_list_entry.dart │ │ │ │ ├── media_list_sort.dart │ │ │ │ ├── media_list_status.dart │ │ │ │ ├── media_sort.dart │ │ │ │ ├── media_status.dart │ │ │ │ ├── media_type.dart │ │ │ │ ├── relation_edge.dart │ │ │ │ ├── relation_type.dart │ │ │ │ ├── seasons.dart │ │ │ │ ├── token.dart │ │ │ │ └── user.dart │ │ │ └── utils.dart │ │ ├── pubspec.yaml │ │ └── tests/ │ │ ├── _utils.dart │ │ ├── search.dart │ │ └── trends.dart │ └── shared/ │ ├── .gitignore │ ├── .vscode/ │ │ └── settings.json │ ├── README.md │ ├── analysis_options.yaml │ ├── lib/ │ │ └── http.dart │ └── pubspec.yaml └── pubspec.yaml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/code-analysis.yml ================================================ name: Code Analysis on: push: branches: - main - next paths: - "packages/**" - "lib/**" pull_request: branches: - main - next paths: - "packages/**" - "lib/**" workflow_dispatch: jobs: dart-analyze: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: subosito/flutter-action@v2 with: channel: master - name: 🚧 Do prerequisites run: | flutter pub get dart run cli/prerequisites.dart - name: 🩺 Code Analysis run: dart run cli/code_analysis.dart ================================================ FILE: .gitignore ================================================ *.class *.log *.pyc *.swp .DS_Store .atom/ .buildlog/ .history .svn/ migrate_working_dir/ *.iml *.ipr *.iws .idea/ **/doc/api/ **/ios/Flutter/.last_build_id .dart_tool/ .flutter-plugins .flutter-plugins-dependencies .packages .pub-cache/ .pub/ /build/ app.*.symbols app.*.map.json /android/app/debug /android/app/profile /android/app/release node_modules *.g.dart assets/translations ================================================ FILE: .metadata ================================================ # 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: "476aa717cd342d11e16439b71f4f4c9209c50712" channel: "beta" project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: 476aa717cd342d11e16439b71f4f4c9209c50712 base_revision: 476aa717cd342d11e16439b71f4f4c9209c50712 - platform: linux create_revision: 476aa717cd342d11e16439b71f4f4c9209c50712 base_revision: 476aa717cd342d11e16439b71f4f4c9209c50712 # 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' ================================================ FILE: .phrasey/config.toml ================================================ [input] files = ["../i18n/**.toml"] format = "toml" fallback = "../i18n/en.toml" [schema] file = "./schema.toml" format = "toml" [output] dir = "../assets/translations" format = "json" stringFormat = "python-positional-format-string" [hooks] files = ["./hooks/dart-sync.js"] ================================================ FILE: .phrasey/hooks/dart-sync.js ================================================ const p = require("path"); const fs = require("fs-extra"); const { rootDir, appI18nDir } = require("./utils"); /** * @type {import("phrasey").PhraseyHooksHandler} */ const hook = { onTranslationsBuildFinished: async ({ phrasey, state, log }) => { if (phrasey.options.source !== "build") { log.info("Skipping post-build due to non-build source"); return; } await createTranslationDart(phrasey, state, log); }, }; module.exports = hook; /** * * @param {import("phrasey").Phrasey} phrasey * @param {import("phrasey").PhraseyState} state * @param {import("phrasey").PhraseyLogger} log */ async function createTranslationDart(phrasey, state, log) { const translations = state.getTranslations(); const locales = [...translations.translations.keys()]; /** * @type {string[]} */ const staticKeys = []; /** * @type {string[]} */ const dynamicKeys = []; for (const x of state.getSchema().z.keys) { const cname = camel(x.name); if (x.parameters && x.parameters.length > 0) { const params = x.parameters .map((x) => `final String ${x}`) .join(", "); const callArgs = x.parameters.join(", "); dynamicKeys.push( ` String ${cname}(${params}) => StringUtils.formatPositional(_key('${x.name}'), [${callArgs}]);` ); } else { staticKeys.push(` String get ${cname} => _key('${x.name}');`); } } const content = ` part of 'translator.dart'; class Translation { const Translation(this._json); final Map _json; JsonMap get _localeJson => _json['locale'] as JsonMap; String get localeDisplayName => _localeJson['display']; String get localeNativeName => _localeJson['native']; String get localeCode => _localeJson['code']; Locale get locale => Locale(localeDisplayName, localeNativeName, localeCode); JsonMap get _keysJson => _json['keys'] as JsonMap; String _key(final String name) => _keysJson[name] as String; ${staticKeys.join("\n")} ${dynamicKeys.join("\n")} static const List availableLocales = [${locales .map((x) => `'${x}'`) .join(", ")}]; static const String unk = '?'; } `; const path = p.join(appI18nDir, "translation.g.dart"); await fs.writeFile(path, content); log.success(`Generated "${p.relative(rootDir, path)}".`); } /** * * @param {string} text * @returns {string} */ function camel(text) { return text[0].toLowerCase() + text.substring(1); } ================================================ FILE: .phrasey/hooks/utils.js ================================================ const p = require("path"); const rootDir = p.resolve(__dirname, "../.."); const rootI18nDir = p.join(rootDir, "i18n"); const appI18nDir = p.join(rootDir, "lib/core/translator"); module.exports = { rootDir, appI18nDir, rootI18nDir, }; ================================================ FILE: .phrasey/schema.toml ================================================ [[keys]] name = "Anime" description = "Anime" [[keys]] name = "Manga" description = "Manga" [[keys]] name = "SearchAnAnimeOrManga" description = "Search an Anime or Manga" [[keys]] name = "MostPopularAnime" description = "Most Popular Anime" [[keys]] name = "TopOngoingAnime" description = "Top Ongoing Anime" [[keys]] name = "MostPopularManga" description = "Most Popular Manga" [[keys]] name = "TopOngoingManga" description = "Top Ongoing Manga" [[keys]] name = "Winter" description = "Winter" [[keys]] name = "Spring" description = "Spring" [[keys]] name = "Summer" description = "Summer" [[keys]] name = "Fall" description = "Fall" [[keys]] name = "NEps" description = "Episodes" parameters = ["n"] [[keys]] name = "NChs" description = "Chapters" parameters = ["n"] [[keys]] name = "Episodes" description = "Episodes" [[keys]] name = "Chapters" description = "Chapters" [[keys]] name = "NMins" description = "Minutes" parameters = ["n"] [[keys]] name = "NHrsOMins" description = "Hours and minutes" parameters = ["n", "o"] [[keys]] name = "Relations" description = "Relations" [[keys]] name = "Cancelled" description = "Cancelled" [[keys]] name = "Releasing" description = "Releasing" [[keys]] name = "NotYetReleased" description = "Not yet released" [[keys]] name = "Finished" description = "Finished" [[keys]] name = "Hiatus" description = "Hiatus" [[keys]] name = "Nsfw" description = "NSFW" [[keys]] name = "Characters" description = "Characters" [[keys]] name = "Settings" description = "Settings" [[keys]] name = "Appearance" description = "Appearance" [[keys]] name = "DarkMode" description = "Dark mode" [[keys]] name = "AccentColor" description = "Accent color" [[keys]] name = "BackgroundColor" description = "Background color" [[keys]] name = "DisableAnimations" description = "Disable animations" [[keys]] name = "UseSystemTheme" description = "Use system theme" [[keys]] name = "Overview" description = "Overview" [[keys]] name = "Extensions" description = "Extensions" [[keys]] name = "ByX" description = "By something" parameters = ["x"] [[keys]] name = "AuthenticatedAsX" description = "Authenticated as someone" parameters = ["x"] [[keys]] name = "Anilist" description = "Anilist" [[keys]] name = "LoginUsingAnilist" description = "Login using Anilist" [[keys]] name = "SomethingWentWrong" description = "Something went wrong" [[keys]] name = "TrackYourProgressUsingAnilist" description = "Track your progress using AniList" [[keys]] name = "Current" description = "Current" [[keys]] name = "Planning" description = "Planning" [[keys]] name = "Completed" description = "Completed" [[keys]] name = "Dropped" description = "Dropped" [[keys]] name = "Paused" description = "Paused" [[keys]] name = "Repeating" description = "Repeating" [[keys]] name = "TotalAnime" description = "Total anime" [[keys]] name = "EpisodesWatched" description = "Episodes watched" [[keys]] name = "MeanScore" description = "Mean score" [[keys]] name = "TimeSpent" description = "Time spent" [[keys]] name = "TotalManga" description = "Total manga" [[keys]] name = "ChaptersRead" description = "Chapters read" [[keys]] name = "VolumesRead" description = "Volumes read" [[keys]] name = "Red" description = "Red" [[keys]] name = "Orange" description = "Orange" [[keys]] name = "Amber" description = "Amber" [[keys]] name = "Yellow" description = "Yellow" [[keys]] name = "Lime" description = "Lime" [[keys]] name = "Green" description = "Green" [[keys]] name = "Emerald" description = "Emerald" [[keys]] name = "Teal" description = "Teal" [[keys]] name = "Cyan" description = "Cyan" [[keys]] name = "Sky" description = "Sky" [[keys]] name = "Blue" description = "Blue" [[keys]] name = "Indigo" description = "Indigo" [[keys]] name = "Violet" description = "Violet" [[keys]] name = "Purple" description = "Purple" [[keys]] name = "Fuchsia" description = "Fuchsia" [[keys]] name = "Pink" description = "Pink" [[keys]] name = "Rose" description = "Rose" ================================================ FILE: .prettierrc ================================================ { "tabWidth": 4, "useTabs": false } ================================================ FILE: .vscode/settings.json ================================================ { "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "[dart]": { "editor.defaultFormatter": "Dart-Code.dart-code" }, "[toml]": { "editor.defaultFormatter": "tamasfe.even-better-toml" } } ================================================ FILE: LICENSE ================================================ 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. Yukino lets you read manga or stream anime ad-free from multiple sources for free! Copyright (C) 2021 Zyrouge This program is free software: 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: Yukino Copyright (C) 2021 Zyrouge 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 . ================================================ FILE: README.md ================================================

# Kazahana An extension-based Anime and Manga client. [![Code Analysis](https://github.com/yukino-org/kazahana/actions/workflows/code-analysis.yml/badge.svg)](https://github.com/yukino-org/kazahana/actions/workflows/code-analysis.yml) ## Links - [Wiki](https://yukino-org.github.io/wiki/) - [GitHub](https://github.com/yukino-org/kazahana/) - [Patreon](https://patreon.com/yukino_app/) For any queries, contact me at [yukino-org@hotmail.com](mailto:yukino-org@hotmail.com). ## Branding ### Colors [![Primary](https://img.shields.io/badge/Primary-%236366F1-white.svg?style=flat&color=6366F1)](https://img.shields.io/badge/Indigo-%236366F1-white.svg?color=6366F1) [![Secondary](https://img.shields.io/badge/Secondary-%2318181b-white.svg?style=flat&color=18181b)](https://img.shields.io/badge/Indigo-%236366F1-white.svg?color=6366F1) ## Technology - [Dart](https://dart.dev/) (Language) - [Flutter](https://flutter.dev/) (UI Framework) - [Pub](https://pub.dev/) (Dependency Manager) - [Git](https://git-scm.com/) (Code Manager) ## Code structure - [./lib](./lib) - Contains the core application - [./cli](./cli) - Contains the command-line tool - [./android](./android) - Contains the android project ## Contributing Ways to contribute to this project: - Submitting bugs and feature requests at [issues](https://github.com/yukino-org/kazahana/issues). - Opening [pull requests](https://github.com/yukino-org/kazahana/pulls) containing bug fixes, new features, etc. ## License [GPL-3.0](./LICENSE) ================================================ FILE: analysis_options.yaml ================================================ include: package:devx/analysis_options.yaml linter: rules: prefer_relative_imports: false ================================================ FILE: android/.gitignore ================================================ 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 **/*.jks ================================================ FILE: android/app/build.gradle ================================================ def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion flutter.compileSdkVersion ndkVersion flutter.ndkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // ? Application ID applicationId "io.github.yukino_org.kazahana" minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" } ================================================ FILE: android/app/src/debug/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/java/io/flutter/app/FlutterMultiDexApplication.java ================================================ // Generated file. // // If you wish to remove Flutter's multidex support, delete this entire file. // // Modifications to this file should be done in a copy under a different name // as this file may be regenerated. package io.flutter.app; import android.app.Application; import android.content.Context; import androidx.annotation.CallSuper; import androidx.multidex.MultiDex; /** * Extension of {@link android.app.Application}, adding multidex support. */ public class FlutterMultiDexApplication extends Application { @Override @CallSuper protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } } ================================================ FILE: android/app/src/main/kotlin/com/example/kazahana/MainActivity.kt ================================================ package com.example.kazahana import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { } ================================================ FILE: android/app/src/main/res/drawable/launch_background.xml ================================================ ================================================ FILE: android/app/src/main/res/drawable-v21/launch_background.xml ================================================ ================================================ FILE: android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: android/app/src/main/res/values-night/styles.xml ================================================ ================================================ FILE: android/app/src/profile/AndroidManifest.xml ================================================ ================================================ FILE: android/build.gradle ================================================ buildscript { ext.kotlin_version = "1.9.10" repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.1.2' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } 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 } ================================================ FILE: android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip ================================================ FILE: android/gradle.properties ================================================ org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true ================================================ FILE: android/settings.gradle ================================================ include ':app' def localPropertiesFile = new File(rootProject.projectDir, "local.properties") def properties = new Properties() assert localPropertiesFile.exists() localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" ================================================ FILE: cli/code_analysis.dart ================================================ import 'dart:io'; import 'utils/exports.dart'; const Logger _logger = Logger('code-analysis'); Future main() async { final Stopwatch watch = Stopwatch()..start(); _logger.info('Checking code format...'); await checkCodeFormat(); watch.stop(); _logger.info('Validated code format in ${watch.elapsedMilliseconds}ms'); watch.reset(); _logger.info('Analyzing code...'); await analyzeCode(); watch.stop(); _logger.info('Analyzed code in ${watch.elapsedMilliseconds}ms'); } Future analyzeCode() async { final ProcessResult result = await Process.run('flutter', ['analyze']); if (result.exitCode == 0) return; throw Exception( 'Code analyse failed with exit code ${result.exitCode}\nstdout: ${result.stdout}\nstdout: ${result.stderr}', ); } Future checkCodeFormat() async { final ProcessResult result = await Process.run( 'flutter', [ 'format', '--output=none', '--set-exit-if-changed', '.', ], ); if (result.exitCode == 0) return; final List files = RegExp('Changed (.*)') .allMatches(result.stdout.toString()) .map((final RegExpMatch x) => x.group(1)!) .toList(); final RegExp ignoredFilesRegex = RegExp(r'\.g\.dart$'); final List filtered = files.where(ignoredFilesRegex.hasMatch).toList(); if (filtered.isNotEmpty) { throw Exception('Invalid files: ${filtered.join(' ')}'); } } ================================================ FILE: cli/prerequisites.dart ================================================ import 'tasks/build_runner.dart' as build_runner; import 'tasks/i18n.dart' as i18n; import 'tasks/icon.dart' as icon; import 'tasks/meta.dart' as meta; Future main(final List args) async { await i18n.main(args); await build_runner.main(args); await meta.main(); await icon.main(); } ================================================ FILE: cli/run.dart ================================================ import 'dart:io'; import 'prerequisites.dart' as prerequisites; import 'utils/exports.dart'; const Logger _logger = Logger('run'); Future main(final List args) async { await prerequisites.main(args); _logger.info('Starting...'); final Process process = await Process.start( 'flutter', ['run'], mode: ProcessStartMode.inheritStdio, runInShell: true, ); final int exitCode = await process.exitCode; if (exitCode != 0) { throw Exception('Debug run failed with error code $exitCode'); } } ================================================ FILE: cli/tasks/build_runner.dart ================================================ import 'dart:io'; import '../utils/exports.dart'; const Logger _logger = Logger('build_runner'); Future main(final List args) async { await runBuildRunner( deleteConflictingOutputs: args.contains('--force-build-runner'), ); } Future runBuildRunner({ final bool deleteConflictingOutputs = false, }) async { _logger.info('Running...'); final Stopwatch watch = Stopwatch()..start(); final Process process = await Process.start( 'dart', [ 'run', 'build_runner', 'build', '--fail-on-severe', if (deleteConflictingOutputs) '--delete-conflicting-outputs', ], ); process.stdout.listen(stdout.add, onError: stdout.addError); final int exitCode = await process.exitCode; watch.stop(); if (exitCode == 78 && !deleteConflictingOutputs) { _logger.info('Failed with error code $exitCode'); _logger.info('Retrying with --delete-conflicting-outputs flag...'); return runBuildRunner(deleteConflictingOutputs: true); } if (exitCode != 0) { throw Exception('Build runner failed with error code $exitCode'); } _logger.info('Finished in ${watch.elapsedMilliseconds}ms'); } ================================================ FILE: cli/tasks/i18n.dart ================================================ import 'dart:io'; Future main(final List args) async { final ProcessResult result = await Process.run( 'npm', ['run', 'i18n:build'], ); if (result.exitCode != 0) { throw Exception('i18n builder failed with error code $exitCode'); } } ================================================ FILE: cli/tasks/icon.dart ================================================ import 'dart:io'; import 'dart:typed_data'; import 'package:image/image.dart'; import 'package:path/path.dart' as path; import '../utils/exports.dart'; const Logger _logger = Logger('icon'); const int defaultImageSize = 1000; const int overlayContentSize = 250; const List<(int, String)> androidIconSizes = <(int, String)>[ (defaultImageSize ~/ 1, 'mdpi'), (defaultImageSize ~/ 1.5, 'hdpi'), (defaultImageSize ~/ 2, 'xhdpi'), (defaultImageSize ~/ 3, 'xxhdpi'), (defaultImageSize ~/ 4, 'xxxhdpi'), ]; String getAndroidIconPath(final String code) => path.join( Paths.rootDir, 'android/app/src/main/res/mipmap-$code/ic_launcher.png', ); Future main() async { final String backgroundImagePath = path.join(Paths.iconsDir, 'background.png'); final String overlayImagePath = path.join(Paths.iconsDir, 'overlay.png'); _logger.info('Background Image Path: $backgroundImagePath'); _logger.info('Overlay Image Path: $overlayImagePath'); final Uint8List backgroundImageBytes = await File(backgroundImagePath).readAsBytes(); final Uint8List overlayImageBytes = await File(overlayImagePath).readAsBytes(); final Image backgroundImage = decodePng(backgroundImageBytes)!; final Image overlayImage = decodePng(overlayImageBytes)!; final Image iconImage = compositeImage( overlayImage, copyCrop( backgroundImage, x: 0, y: overlayContentSize ~/ 2, width: defaultImageSize, height: defaultImageSize - overlayContentSize, ), ); for (final (int size, String code) in androidIconSizes) { final String iconPath = getAndroidIconPath(code); final File iconFile = File(iconPath); final List icon = encodeNamedImage( path.basename(iconFile.path), copyResizeCropSquare(iconImage, size: size), )!; await iconFile.writeAsBytes(icon); _logger.info('Generated $iconPath ($code)'); } } ================================================ FILE: cli/tasks/meta.dart ================================================ import 'dart:io'; import 'package:path/path.dart' as path; import '../utils/exports.dart'; import 'version.dart'; const Logger _logger = Logger('meta'); final String generatedAppMetaPath = path.join(Paths.libDir, 'core/app/meta.g.dart'); Future main() async { await File(generatedAppMetaPath) .writeAsString(await getGeneratedAppMetaContent()); _logger.info('Generated $generatedAppMetaPath'); } Future getGeneratedAppMetaContent() async => ''' part of 'meta.dart'; abstract class GeneratedAppMeta { static const String version = '${await getVersion()}'; static const int builtAtMs = ${DateTime.now().millisecondsSinceEpoch}; } '''; ================================================ FILE: cli/tasks/version.dart ================================================ import 'dart:io'; import 'package:path/path.dart' as path; import '../utils/exports.dart'; final String pubspecYamlPath = path.join(Paths.rootDir, 'pubspec.yaml'); Future getVersion() async { final String content = await File(pubspecYamlPath).readAsString(); return RegExp(r'version: ([\w+\.-]+)').firstMatch(content)!.group(1)!; } ================================================ FILE: cli/utils/exports.dart ================================================ export 'logger.dart'; export 'paths.dart'; ================================================ FILE: cli/utils/logger.dart ================================================ // ignore_for_file: avoid_print class Logger { const Logger(this.name); final String name; void info(final Object text) { print('[$time info] $name: $text'); } void fatal(final Object text) { print('[$time err!] $name: $text'); } void println() { print(' '); } String get time { final DateTime now = DateTime.now(); return '${now.hour}:${now.minute}:${now.second}'; } } ================================================ FILE: cli/utils/paths.dart ================================================ import 'dart:io'; import 'package:path/path.dart' as path; abstract class Paths { static final String rootDir = Directory.current.path; static final String cliDir = path.join(rootDir, 'cli'); static final String assetsDir = path.join(rootDir, 'assets'); static final String libDir = path.join(rootDir, 'lib'); static final String iconsDir = path.join(assetsDir, 'icon'); } ================================================ FILE: i18n/en.toml ================================================ locale = "en" [keys] Anime = "Anime" Manga = "Manga" SearchAnAnimeOrManga = "Search an anime or manga" MostPopularAnime = "Most Popular Anime" TopOngoingAnime = "Top Ongoing Anime" MostPopularManga = "Most Popular Manga" TopOngoingManga = "Top Ongoing Manga" Winter = "Winter" Spring = "Spring" Summer = "Summer" Fall = "Fall" NEps = "{n} eps." NChs = "{n} chs." Episodes = "Episodes" Chapters = "Chapters" NMins = "{n} mins." NHrsOMins = "{n} hrs. {o} mins." Relations = "Relations" Cancelled = "Cancelled" Releasing = "Releasing" NotYetReleased = "Unreleased" Finished = "Finished" Hiatus = "Hiatus" Nsfw = "NSFW" Characters = "Characters" Settings = "Settings" Appearance = "Appearance" DarkMode = "Dark mode" AccentColor = "Accent color" BackgroundColor = "Background color" DisableAnimations = "Disable animations" UseSystemTheme = "Use system theme" Overview = "Overview" Extensions = "Extensions" ByX = "By {x}" AuthenticatedAsX = "Authenticated as {x}" Anilist = "Anilist" LoginUsingAnilist = "Login using Anilist" SomethingWentWrong = "Something went wrong!" TrackYourProgressUsingAnilist = "Track your progress using Anilist" Current = "Current" Planning = "Planning" Completed = "Completed" Dropped = "Dropped" Paused = "Paused" Repeating = "Repeating" TotalAnime = "Total anime" EpisodesWatched = "Episodes watched" MeanScore = "Mean score" TimeSpent = "Time spent" TotalManga = "Total manga" ChaptersRead = "Chapters read" VolumesRead = "Volumes read" Red = "Red" Orange = "Orange" Amber = "Amber" Yellow = "Yellow" Lime = "Lime" Green = "Green" Emerald = "Emerald" Teal = "Teal" Cyan = "Cyan" Sky = "Sky" Blue = "Blue" Indigo = "Indigo" Violet = "Violet" Purple = "Purple" Fuchsia = "Fuchsia" Pink = "Pink" Rose = "Rose" ================================================ FILE: lib/core/anilist/auth.dart ================================================ import 'package:anilist/anilist.dart'; import 'package:kazahana/ui/exports.dart'; import '../app/exports.dart'; import '../database/exports.dart'; import '../packages.dart'; import 'credentials.dart'; abstract class AnilistAuth { static const String baseURL = 'https://anilist.co/api/v2'; static AnilistUser? user; static Future initialize() async { updateAnilistClient(SecureDatabase.data.anilistToken); await fetchUser(); } static Future authenticate(final AnilistToken token) async { SecureDatabase.data.anilistToken = token; await SecureDatabase.save(); updateAnilistClient(SecureDatabase.data.anilistToken); await fetchUser(); if (user != null) { Toast( content: Text( [ '${gNavigatorKey.currentContext!.t.anilist}:', gNavigatorKey.currentContext!.t.authenticatedAsX(user!.name), ].join(' '), ), ).show(); } } static Future unauthenticate() async { SecureDatabase.data.anilistToken = null; await SecureDatabase.save(); updateAnilistClient(null); } static Future fetchUser() async { try { user = await AnilistUserEndpoints.getAuthenticatedUser(); } catch (_) {} } static void updateAnilistClient(final AnilistToken? token) { AnilistGraphQL.updateClient( token: token, onTokenExpired: token != null ? unauthenticate : null, additionalHeaders: const { 'User-Agent': '${AppMeta.name} v${AppMeta.version}', }, ); AppEvents.controller.add(AppEvent.anilistStateChange); } static String get oauthURL => Uri.encodeFull( '$baseURL/oauth/authorize?client_id=${AnilistCredentials.clientId}&response_type=token', ); } ================================================ FILE: lib/core/anilist/credentials.dart ================================================ abstract class AnilistCredentials { static const String clientId = '6444'; } ================================================ FILE: lib/core/anilist/exports.dart ================================================ export 'package:anilist/anilist.dart'; export 'auth.dart'; export 'translations.dart'; ================================================ FILE: lib/core/anilist/translations.dart ================================================ import 'package:anilist/anilist.dart'; import 'package:tenka/tenka.dart'; import '../translator/exports.dart'; import '../utils/exports.dart'; extension AnilistFuzzyDateTUtils on AnilistFuzzyDate { String get pretty => PrettyDates.constructDateString( day: day?.toString() ?? Translation.unk, month: month?.toString() ?? Translation.unk, year: year?.toString() ?? Translation.unk, ); String? get maybePretty => isValidDateTime ? pretty : null; } const Map _anilistMediaTypeTenkaTypeMap = { AnilistMediaType.anime: TenkaType.anime, AnilistMediaType.manga: TenkaType.manga, }; extension AnilistMediaTypeTUtils on AnilistMediaType { TenkaType get asTenkaType => _anilistMediaTypeTenkaTypeMap[this]!; } extension TenkaTypeAnilistUtils on TenkaType { AnilistMediaType get asAnilistMediaType => _anilistMediaTypeTenkaTypeMap.entries .firstWhere( (final MapEntry x) => x.value == this, ) .key; } extension AnimeSeasonsTUtils on AnimeSeasons { String getTitleCase(final Translation translation) => switch (this) { AnimeSeasons.winter => translation.winter, AnimeSeasons.spring => translation.spring, AnimeSeasons.summer => translation.summer, AnimeSeasons.fall => translation.fall, }; } extension AnilistMediaTUtils on AnilistMedia { String getWatchtime(final Translation translation) => switch (type) { AnilistMediaType.anime when format == AnilistMediaFormat.movie => duration != null ? PrettyDurations.prettyHoursMinutesShort( translation, Duration(minutes: duration!), ) : translation.nMins(Translation.unk), AnilistMediaType.anime => translation.nEps(episodes?.toString() ?? Translation.unk), AnilistMediaType.manga => translation.nChs(chapters?.toString() ?? Translation.unk), }; String get airdate { final String startDatePretty = startDate?.maybePretty ?? Translation.unk; final String endDatePretty = endDate?.maybePretty ?? Translation.unk; if (startDatePretty == endDatePretty) return startDatePretty; return '$startDatePretty - $endDatePretty'; } } extension AnilistRelationTypeTUtils on AnilistRelationType { String getTitleCase(final Translation translation) => StringCase(name).titleCase; } extension AnilistCharacterRoleTUtils on AnilistCharacterRole { String getTitleCase(final Translation translation) => StringCase(name).titleCase; } extension AnilistMediaStatusTUtils on AnilistMediaStatus { String getTitleCase(final Translation translation) => switch (this) { AnilistMediaStatus.cancelled => translation.cancelled, AnilistMediaStatus.releasing => translation.releasing, AnilistMediaStatus.notYetReleased => translation.notYetReleased, AnilistMediaStatus.finished => translation.finished, AnilistMediaStatus.hiatus => translation.hiatus, }; } extension AnilistMediaFormatTUtils on AnilistMediaFormat { String getTitleCase(final Translation translation) => switch (this) { AnilistMediaFormat.tv => 'TV', AnilistMediaFormat.tvShort => 'TV (Short)', AnilistMediaFormat.movie => 'Movie', AnilistMediaFormat.special => 'Special', AnilistMediaFormat.ova => 'OVA', AnilistMediaFormat.ona => 'ONA', AnilistMediaFormat.music => 'Music', AnilistMediaFormat.manga => 'Manga', AnilistMediaFormat.novel => 'Novel', AnilistMediaFormat.oneshot => 'OneShot', }; } extension AnilistMediaListStatusTUtils on AnilistMediaListStatus { String getTitleCase(final Translation translation) => switch (this) { AnilistMediaListStatus.current => translation.current, AnilistMediaListStatus.planning => translation.planning, AnilistMediaListStatus.completed => translation.completed, AnilistMediaListStatus.dropped => translation.dropped, AnilistMediaListStatus.paused => translation.paused, AnilistMediaListStatus.repeating => translation.repeating, }; } ================================================ FILE: lib/core/app/events.dart ================================================ import 'dart:async'; class AppEvent { const AppEvent(this.name, [this.data]); final String name; final dynamic data; @override bool operator ==(final Object other) => other is AppEvent && other.name == name; @override int get hashCode => Object.hash(name, data); static const AppEvent initialized = AppEvent('initialized'); static const AppEvent afterAnitialized = AppEvent('after_initialized'); static const AppEvent anilistStateChange = AppEvent('anilist_state_change'); static const AppEvent settingsChange = AppEvent('settings_change'); static const AppEvent translationsChange = AppEvent('translations_change'); } abstract class AppEvents { static final StreamController controller = StreamController.broadcast(); static final Stream stream = controller.stream; } ================================================ FILE: lib/core/app/exports.dart ================================================ export 'events.dart'; export 'loader.dart'; export 'meta.dart'; ================================================ FILE: lib/core/app/loader.dart ================================================ import '../anilist/exports.dart'; import '../database/exports.dart'; import '../internals/exports.dart'; import '../paths.dart'; import '../tenka/exports.dart'; import '../translator/exports.dart'; import 'events.dart'; abstract class AppLoader { static bool ready = false; static Future initialize() async { await Paths.initialize(); await SettingsDatabase.initialize(); await SecureDatabase.initialize(); await CacheDatabase.initialize(); await TenkaManager.initialize(); await Translator.initialize(); await AnilistAuth.initialize(); ready = true; AppEvents.controller.add(AppEvent.initialized); initializeAfterLoad(); } static Future initializeAfterLoad() async { await Deeplink.initializeAfterLoad(); AppEvents.controller.add(AppEvent.afterAnitialized); } } ================================================ FILE: lib/core/app/meta.dart ================================================ part 'meta.g.dart'; abstract class AppMeta { static const String name = 'Kazahana'; static const String code = 'kazahana'; static const String scheme = 'kazahana'; static const String yuki = '雪'; static const String version = GeneratedAppMeta.version; static final DateTime builtAt = DateTime.fromMillisecondsSinceEpoch(GeneratedAppMeta.builtAtMs); } ================================================ FILE: lib/core/database/cache/database.dart ================================================ import 'package:flutter/foundation.dart'; import 'package:path/path.dart' as path; import 'package:perks/perks.dart'; import '../../paths.dart'; import '../../utils/exports.dart'; abstract class CacheDatabase { static const String kDataKey = 'data'; static const String kExpiresAtKey = 'expires_at'; static const int recommendedTtlMs = 21600000; static final String cacheFilePath = path.join(Paths.docsDir.path, 'cache.db'); static final PerksNameValueBox box = PerksNameValueBox( adapter: PerksFileAdapter(cacheFilePath), ); static Future initialize() async { _removeExpiredData(); } static Future get(final String key) async { final JsonMap? data = await box.get(key); if (data == null) return null; final T? value = data[kDataKey] as T?; final int? expiresAtMs = data[kExpiresAtKey] as int?; if (expiresAtMs != null && expiresAtMs < DateTime.now().millisecondsSinceEpoch) { await box.delete(key); return null; } return value; } static Future set( final String key, final T? data, { final int? ttlMs, }) async { if (data == null) return delete(key); await box.set(key, { kDataKey: data, if (ttlMs != null) kExpiresAtKey: DateTime.now().millisecondsSinceEpoch + ttlMs, }); } static Future delete(final String key) async => box.delete(key); static Future _removeExpiredData() async { await box.transaction((final PerksNameValueMap data) async { await compute(_filterExpiredData, data); return data; }); } static void _filterExpiredData( final Map data, ) { final int nowMs = DateTime.now().millisecondsSinceEpoch; for (final MapEntry x in data.entries) { final int? expiresAtMs = x.value[kExpiresAtKey] as int?; if (expiresAtMs != null && expiresAtMs < nowMs) { data.remove(x.key); } } } } ================================================ FILE: lib/core/database/cache/exports.dart ================================================ export 'database.dart'; ================================================ FILE: lib/core/database/exports.dart ================================================ export 'cache/exports.dart'; export 'secure/exports.dart'; export 'settings/exports.dart'; ================================================ FILE: lib/core/database/secure/database.dart ================================================ import 'dart:convert'; import 'package:encrypt/encrypt.dart'; import 'package:path/path.dart' as path; import 'package:perks/perks.dart'; import '../../paths.dart'; import '../../utils/exports.dart'; import 'schema.dart'; abstract class SecureDatabase { static final Key key = Key.fromUtf8('ThIs_Is_HiGhLy_SeCuRe_KeY_nO_cAp'); static final IV iv = IV.fromLength(16); static final Encrypter encrypter = Encrypter(AES(key, mode: AESMode.cbc)); static final PerksFileAdapter adapter = PerksFileAdapter(path.join(Paths.docsDir.path, 'secure.db')); static late SecureSchema data; static Future initialize() async { final String content = await adapter.read(); data = content.isNotEmpty ? SecureSchema.fromJson(json.decode(decryptData(content)) as JsonMap) : SecureSchema(); } static Future save() async { await adapter.write(encryptData(json.encode(data.toJson()))); } static String encryptData(final String data) => encrypter.encrypt(data, iv: iv).base64; static String decryptData(final String data) => encrypter.decrypt(Encrypted.fromBase64(data), iv: iv); } ================================================ FILE: lib/core/database/secure/exports.dart ================================================ export 'database.dart'; export 'schema.dart'; ================================================ FILE: lib/core/database/secure/schema.dart ================================================ import 'package:json_annotation/json_annotation.dart'; import '../../exports.dart'; part 'schema.g.dart'; @JsonSerializable() class SecureSchema { SecureSchema({ this.anilistToken, }); factory SecureSchema.fromJson(final JsonMap json) => _$SecureSchemaFromJson(json.cast()); @JsonKey(fromJson: _anilistTokenFromJson, toJson: _anilistTokenToJson) AnilistToken? anilistToken; JsonMap toJson() => _$SecureSchemaToJson(this); static AnilistToken? _anilistTokenFromJson(final dynamic value) => value is JsonMap ? AnilistToken(value.cast()) : null; static JsonMap? _anilistTokenToJson(final AnilistToken? value) => value?.json; } ================================================ FILE: lib/core/database/settings/database.dart ================================================ import 'dart:async'; import 'dart:convert'; import 'package:path/path.dart' as path; import 'package:perks/perks.dart'; import '../../app/events.dart'; import '../../paths.dart'; import '../../utils/exports.dart'; import 'schema.dart'; abstract class SettingsDatabase { static final PerksFileAdapter adapter = PerksFileAdapter(path.join(Paths.docsDir.path, 'settings.db')); static bool ready = false; static late SettingsSchema settings; static Future initialize() async { final String content = await adapter.read(); settings = content.isNotEmpty ? SettingsSchema.fromJson(json.decode(content) as JsonMap) : SettingsSchema(); ready = true; AppEvents.controller.add(AppEvent.settingsChange); } static Future save() async { await adapter.write(json.encode(settings.toJson())); AppEvents.controller.add(AppEvent.settingsChange); } } ================================================ FILE: lib/core/database/settings/exports.dart ================================================ export 'database.dart'; export 'schema.dart'; ================================================ FILE: lib/core/database/settings/schema.dart ================================================ import 'package:json_annotation/json_annotation.dart'; import 'package:kazahana/ui/utils/relative_scale.dart'; import '../../utils/exports.dart'; part 'schema.g.dart'; @JsonSerializable() class SettingsSchema { SettingsSchema({ this.locale, this.ignoreSSLCertificate = true, this.darkMode = true, this.primaryColor, this.backgroundColor, this.disableAnimations = false, this.useSystemPreferredTheme = false, this.scaleMultiplier = RelativeScaleData.defaultScaleMultiplier, }); factory SettingsSchema.fromJson(final JsonMap json) => _$SettingsSchemaFromJson(json.cast()); @JsonKey(fromJson: _localeFromJson, toJson: _localeToJson) Locale? locale; bool ignoreSSLCertificate; bool darkMode; String? primaryColor; String? backgroundColor; bool disableAnimations; bool useSystemPreferredTheme; double scaleMultiplier; JsonMap toJson() => _$SettingsSchemaToJson(this); static Locale? _localeFromJson(final String? value) => value != null ? Locale.parse(value) : null; static String? _localeToJson(final Locale? value) => value?.code; } ================================================ FILE: lib/core/exports.dart ================================================ export 'anilist/exports.dart'; export 'app/exports.dart'; export 'database/exports.dart'; export 'packages.dart'; export 'paths.dart'; export 'state/exports.dart'; export 'tenka/exports.dart'; export 'themes/exports.dart'; export 'translator/exports.dart'; export 'utils/exports.dart'; ================================================ FILE: lib/core/internals/deeplink.dart ================================================ import 'package:kazahana/ui/exports.dart'; import 'package:uni_links/uni_links.dart' as uni_links; import '../app/exports.dart'; import '../packages.dart'; import 'router/exports.dart'; abstract class Deeplink { static Future initializeAfterLoad() async { final String? path = await uni_links.getInitialLink(); if (path != null) handle(path); listen(); } static void listen() { uni_links.linkStream.listen((final String? path) { if (path == null) return; handle(path); }); } static void handle(final String path) { String resolvedPath = path; if (resolvedPath.startsWith(fullScheme)) { resolvedPath = resolvedPath.replaceFirst(fullScheme, ''); } debugPrint('Incoming deeplink: $resolvedPath'); final InternalRoute? internalRoute = InternalRoutes.findMatch(resolvedPath); if (internalRoute != null) { internalRoute.handle(resolvedPath); return; } gNavigatorKey.currentState!.pushNamed(resolvedPath); } static const String fullScheme = '${AppMeta.scheme}://'; } ================================================ FILE: lib/core/internals/exports.dart ================================================ export 'deeplink.dart'; ================================================ FILE: lib/core/internals/router/exports.dart ================================================ export 'route.dart'; export 'routes.dart'; ================================================ FILE: lib/core/internals/router/route.dart ================================================ abstract class InternalRoute { bool matches(final String route); Future handle(final String route); } ================================================ FILE: lib/core/internals/router/routes/anilist.dart ================================================ import '../../../anilist/exports.dart'; import '../route.dart'; class AnilistAuthRoute extends InternalRoute { @override bool matches(final String route) => route.startsWith(routeName); @override Future handle(final String route) async { final AnilistToken token = AnilistToken.parseURL(route); await AnilistAuth.authenticate(token); } static const String routeName = '/anilist/auth'; } ================================================ FILE: lib/core/internals/router/routes/exports.dart ================================================ export 'anilist.dart'; ================================================ FILE: lib/core/internals/router/routes.dart ================================================ import '../../utils/exports.dart'; import 'route.dart'; import 'routes/exports.dart'; abstract class InternalRoutes { static AnilistAuthRoute anilistAuth = AnilistAuthRoute(); static InternalRoute? findMatch(final String route) => all.firstWhereOrNull((final InternalRoute x) => x.matches(route)); static List get all => [anilistAuth]; } ================================================ FILE: lib/core/packages.dart ================================================ export 'dart:ui' show ImageFilter; export 'package:animations/animations.dart'; export 'package:flutter/material.dart' hide Locale; export 'package:provider/provider.dart'; export 'package:provider/single_child_widget.dart'; export 'package:url_launcher/url_launcher.dart' show LaunchMode, canLaunchUrl, launchUrl; ================================================ FILE: lib/core/paths.dart ================================================ import 'dart:io'; import 'package:path_provider/path_provider.dart' as path_provider; abstract class Paths { static late final Directory docsDir; static Future initialize() async { docsDir = await path_provider.getApplicationDocumentsDirectory(); } } abstract class AssetPaths { static const String anilistLogo = 'assets/images/anilist_logo.png'; } ================================================ FILE: lib/core/player/video_player.dart ================================================ import 'package:flutter/material.dart'; import 'package:media_kit/media_kit.dart' as media_kit; import 'package:media_kit_video/media_kit_video.dart' as media_kit; class PlayerPage extends StatefulWidget { const PlayerPage({super.key}); @override _PlayerPageState createState() => _PlayerPageState(); } String sourceurl = ''; // TODO: Placeholder variable. Swap this out for the new video url provider. String fileContents = ''; // TODO: Placeholder variable. Subtitles will have to be implemented later. class _PlayerPageState extends State { late media_kit.Player _player; late media_kit.VideoController _controller; // final ValueNotifier _subtitlesEnabled = ValueNotifier(true); @override void initState() { super.initState(); _player = media_kit.Player(); _controller = media_kit.VideoController(_player); _setDataSource(); } @override void dispose() { super.dispose(); _player.dispose(); } Future _setDataSource() async { await _player.open(media_kit.Media(sourceurl)); // _controller.onClosedCaptionEnabled(true); } // Future _loadCaptions() async => // SubRipCaptionFile(fileContents); @override Widget build(final BuildContext context) => Scaffold( appBar: AppBar(), body: SafeArea( child: AspectRatio( aspectRatio: 16 / 9, child: media_kit.Video( controller: _controller, // bottomRight: ( // final BuildContext ctx, // final MeeduPlayerController controller, // final Responsive responsive, // ) { // final double fontSize = responsive.ip(3); // return CupertinoButton( // padding: const EdgeInsets.all(5), // minSize: 25, // child: ValueListenableBuilder( // valueListenable: _subtitlesEnabled, // builder: ( // final BuildContext context, // final bool enabled, // final _, // ) => // Text( // 'CC', // style: TextStyle( // fontSize: fontSize > 18 ? 18 : fontSize, // color: Colors.white.withOpacity( // enabled ? 1 : 0.4, // ), // ), // ), // ), // onPressed: () { // _subtitlesEnabled.value = !_subtitlesEnabled.value; // _controller.onClosedCaptionEnabled(_subtitlesEnabled.value); // }, // ); // }, ), ), ), ); } ================================================ FILE: lib/core/state/exports.dart ================================================ export 'states.dart'; export 'value.dart'; ================================================ FILE: lib/core/state/states.dart ================================================ enum States { waiting, processing, finished, failed, } ================================================ FILE: lib/core/state/value.dart ================================================ import 'package:flutter/material.dart'; import 'states.dart'; class StatedValue { StatedValue({ this.state = States.waiting, }); States state; late T value; Object? error; StackTrace? stackTrace; void _change( final States state, { final T? value, final Object? error, final StackTrace? stackTrace, }) { this.state = state; if (value != null) { this.value = value; } if (error != null) { this.error = error; } if (stackTrace != null) { this.stackTrace = stackTrace; } } void waiting([final T? value]) { _change(States.waiting, value: value); } void loading([final T? value]) { _change(States.processing, value: value); } void finish(final T value) { _change(States.finished, value: value); } void fail([ final Object? error, final StackTrace? stackTrace, ]) { _change(States.failed, error: error, stackTrace: stackTrace); } bool get isWaiting => state == States.waiting; bool get isProcessing => state == States.processing; bool get hasFinished => state == States.finished; bool get hasFailed => state == States.failed; bool get hasFinishedOrFailed => hasFinished || hasFailed; } class ListenableStatedValue extends StatedValue with ChangeNotifier { @override void _change( final States state, { final T? value, final Object? error, final StackTrace? stackTrace, }) { super._change(state, value: value, error: error, stackTrace: stackTrace); notifyListeners(); } } ================================================ FILE: lib/core/tenka/exports.dart ================================================ export 'package:tenka/tenka.dart'; export 'manager.dart'; export 'utils.dart'; ================================================ FILE: lib/core/tenka/manager.dart ================================================ import 'package:path/path.dart' as path; import 'package:tenka/tenka.dart'; import '../database/exports.dart'; import '../paths.dart'; abstract class TenkaManager { static late final TenkaRepository repository; static final Map _extractors = {}; static Future initialize() async { await TenkaInternals.initialize( runtime: TenkaRuntimeOptions( http: TenkaRuntimeHttpClientOptions( ignoreSSLCertificate: SettingsDatabase.settings.ignoreSSLCertificate, ), ), ); repository = TenkaRepository( resolver: const TenkaStoreURLResolver(), baseDir: path.join(Paths.docsDir.path, 'tenka'), ); // await repository.initialize(); } static Future getExtractor(final TenkaMetadata metadata) async { if (!_extractors.containsKey(metadata.id)) { final BeizeProgramConstant program = BeizeProgramConstant.deserialize( (metadata.source as TenkaBase64DS).data, ); final TenkaRuntimeInstance runtime = await TenkaRuntimeManager.create(program); final T extractor; if (T is AnimeExtractor) { extractor = await runtime.getAnimeExtractor() as T; } else if (T is MangaExtractor) { extractor = await runtime.getMangaExtractor() as T; } else { throw UnsupportedError('Invalid extractor type: $T'); } _extractors[metadata.id] = extractor; } return _extractors[metadata.id] as T; } } ================================================ FILE: lib/core/tenka/utils.dart ================================================ import 'package:tenka/tenka.dart'; import '../translator/exports.dart'; extension TenkaTypeUtils on TenkaType { String getTitleCase(final Translation translation) => switch (this) { TenkaType.anime => translation.anime, TenkaType.manga => translation.manga, }; } ================================================ FILE: lib/core/themes/colors.dart ================================================ import 'package:flutter/material.dart'; import '../translator/exports.dart'; abstract class ForegroundColors { static const Color red = Color(0xffef4444); static const Color orange = Color(0xfff97316); static const Color amber = Color(0xfff59e0b); static const Color yellow = Color(0xffeab308); static const Color lime = Color(0xff84cc16); static const Color green = Color(0xff22c55e); static const Color emerald = Color(0xff10b981); static const Color teal = Color(0xff14b8a6); static const Color cyan = Color(0xff06b6d4); static const Color sky = Color(0xff0ea5e9); static const Color blue = Color(0xff3b82f6); static const Color indigo = Color(0xff6366f1); static const Color violet = Color(0xff8b5cf6); static const Color purple = Color(0xffa855f7); static const Color fuchsia = Color(0xffd946ef); static const Color pink = Color(0xffec4899); static const Color rose = Color(0xfff43f5e); static const Map colors = { 'red': red, 'orange': orange, 'amber': amber, 'yellow': yellow, 'lime': lime, 'green': green, 'emerald': emerald, 'teal': teal, 'cyan': cyan, 'sky': sky, 'blue': blue, 'indigo': indigo, 'violet': violet, 'purple': purple, 'fuchsia': fuchsia, 'pink': pink, 'rose': rose, }; static Color? find(final String name) => colors[name]; static List names() => colors.keys.toList(); static String getTitleCase( final Translation translation, final String name, ) => switch (name) { 'red' => translation.red, 'orange' => translation.orange, 'amber' => translation.amber, 'yellow' => translation.yellow, 'lime' => translation.lime, 'green' => translation.green, 'emerald' => translation.emerald, 'teal' => translation.teal, 'cyan' => translation.cyan, 'sky' => translation.sky, 'blue' => translation.blue, 'indigo' => translation.indigo, 'violet' => translation.violet, 'purple' => translation.purple, 'fuchsia' => translation.fuchsia, 'pink' => translation.pink, 'rose' => translation.rose, _ => name, }; } ================================================ FILE: lib/core/themes/exports.dart ================================================ export 'colors.dart'; export 'fonts.dart'; ================================================ FILE: lib/core/themes/fonts.dart ================================================ abstract class Fonts { static const String inter = 'Inter'; static const String greatVibes = 'GreatVibes'; } ================================================ FILE: lib/core/translator/exports.dart ================================================ export 'translator.dart'; ================================================ FILE: lib/core/translator/translator.dart ================================================ import 'dart:convert'; import 'package:flutter/services.dart' show rootBundle; import 'package:utilx/locale.dart'; import 'package:utilx/utilx.dart'; import '../app/exports.dart'; import '../database/exports.dart'; part 'translation.g.dart'; abstract class Translator { static const Locale defaultLocale = LocalesRepository.en; static late Translation currentTranslation; static Future initialize() async { await updateCurrentTranslation(); AppEvents.stream.listen((final AppEvent event) async { if (event != AppEvent.settingsChange) return; await updateCurrentTranslation(); }); } static Future updateCurrentTranslation() async { final Locale? settingsLocale = SettingsDatabase.settings.locale; final Locale locale = settingsLocale != null && hasTranslation(settingsLocale) ? settingsLocale : defaultLocale; currentTranslation = await parseTranslation(locale); AppEvents.controller.add(AppEvent.translationsChange); } static bool hasTranslation(final Locale locale) => Translation.availableLocales.contains(locale.code); static Future parseTranslation(final Locale locale) async { final String content = await rootBundle.loadString('assets/translations/${locale.code}.json'); final JsonMap parsed = json.decode(content) as JsonMap; return Translation(parsed); } static Locale get locale => currentTranslation.locale; static String get identifier => locale.code; } ================================================ FILE: lib/core/utils/dates.dart ================================================ abstract class PrettyDates { static String constructDateString({ required final String day, required final String month, required final String year, }) => '$day-$month-$year'; static String toDateString(final DateTime date) => constructDateString( day: date.day.toString(), month: date.month.toString(), year: date.year.toString(), ); } ================================================ FILE: lib/core/utils/durations.dart ================================================ import '../translator/exports.dart'; abstract class PrettyDurations { static String prettyHoursMinutesShort( final Translation translation, final Duration duration, ) { final int hours = duration.inHours; final int mins = duration.inMinutes.remainder(60); if (hours == 0) return translation.nMins(mins.toString()); return translation.nHrsOMins(hours.toString(), mins.toString()); } } ================================================ FILE: lib/core/utils/exports.dart ================================================ export 'package:collection/collection.dart'; export 'package:utilx/locale.dart'; export 'package:utilx/utilx.dart'; export 'dates.dart'; export 'durations.dart'; export 'provider.dart'; ================================================ FILE: lib/core/utils/kawaii_faces.dart ================================================ // ? Source: https://kawaiiface.net (how pensive) abstract class KawaiiFaces { static const List sad = [ 'ಥ_ಥ', '(-’๏_๏’-)', '˚⌇˚', 'o(╥﹏╥)o', '(⊙﹏⊙✿)', '●︿●', '( /)w(\\✿)', '(╯︵╰,)', '(︶︹︺)', '(◡﹏◡✿)', '(✖﹏✖)', '‘︿’', 'v( ‘.’ )v', '◄.►', '(ㄒoㄒ)', '⊙︿⊙', '(◕︿◕✿)', 'ਉ_ਉ', '┐(‘~`;)┌', '(︶︹︺)', '흫_흫', 'ب_ب', '╮(─▽─)╭', 'ಥ‿ಥ', '(-’_’-)', '(╥╥)', '(•̪●)', '(∩︵∩)', '(o_-)', '(。-_-。)', '(╯_╰)', '(╥_╥)', 'v(ಥ ̯ ಥ)v', "<('.'<)", 'ಠ,ಥ', '(◕︵◕)', '(´ヘ`()', '(✖╭╮✖)', '(◕﹏◕✿)', '(+_+)', '★~(◠︿◕✿)', '(*´д`*)', '(◡△◡✿)', '٩(×̯×)۶', '(ノ_・。)', '┐(‘~`;)┌', '(つд`)', '(✖╭╮✖)', 'ಥ⌣ಥ', 'இ_இ', '✖‿✖', ]; static const List happy = [ '(◕‿◕✿)', '(◠‿◠✿)', '(◠﹏◠✿)', '(*^U^)人(≧V≦*)/', 'ôヮô', '∧( ‘Θ’ )∧', '(¤﹏¤)', '●‿●', 'ʕ·ᴥ·ʔ', '\(^○^)人(^○^)/', 'ヾ(@⌒▽⌒@)ノ', '(°∀°)', 'ヾ| ̄ー ̄|ノ', '(☉‿☉✿)', '┏(^0^)┛┗(^0^) ┓', '(◡‿◡✿)', '✿◕ ‿ ◕✿', 'ヽ(‘ ∇‘ )ノ', '☆(❁‿❁)☆', '❀◕ ‿ ◕❀', 'ヽ(^◇^*)/', '(•⊙ω⊙•)', '!⑈ˆ~ˆ!⑈', '(*^ -^*)', '(⊙‿⊙✿)', '◕3◕', '(゚ヮ゚)', '¢‿¢', 'ヅ', '●ᴥ●', '(∪ ◡ ∪)', '≖‿≖', '≧◡≦', '٩◔‿◔۶', '。◕ ‿ ◕。', 'ヾ(@^▽^@)ノ', '◃┆◉◡◉┆▷', '(✿◠‿◠)', '( ̄ー ̄)', '╰(◡‿◡✿╰)', '~,~', '(ノ◕ヮ◕)ノ*:・゚✧', '(*~▽~)', '❀‿❀', '◕‿◕', '(^L^)', '(^▽^)', '◕ ◡ ◕', '(◕‿◕✿)', '( ;´Д`)', '⊙﹏⊙', '✿。✿', 'ヽ(゜∇゜)ノ', '。(✿‿✿)。', '(´ー`)', 'ツ', 'q(❂‿❂)p', '( ́ ◕◞ε◟◕`)', '☆(◒‿◒)☆', '(∩▂∩)', '(¬‿¬)', '(^O^)', 'ʘ‿ʘ', '(’◎’)', '(◜௰◝)', '(^ー^)', '(o´ω`o)', '(^з^)-☆', '(◕ω◕✿)', '(づ。◕‿‿◕。)づ', '(゚▽^*)', '(⌒o⌒)', '(。◕‿◕。)', 'ت', '(. ゚ー゚)', '१˚◡˚५', '\(●~▽~●)', '(*˘︶˘*)', '(✪㉨✪)', '(ᅌᴗᅌ* )', '^L^', '(\\/) (°„°) (\\/)', '\(*^▽^*)/', '(◠△◠✿)', '( ಠ◡ಠ )', '(〃^∇^)ノ', '^^', '|◔◡◉|', '(●⌒∇⌒●)', '⊂◉‿◉つ', '.ʕʘ‿ʘʔ.', '(*・∀・*)人(*・∀・*)', '\(^-^)/', '∩(︶▽︶)∩', '(☉∀☉)', '(´ω`)', '●﹏●', '( ´∀`)☆', '•ᴥ•', '✿◕ ‿ ◕✿', '(≧◡≦)', '(◡‿◡✿)', '(・ェ-)', '^‿^', '٩(̾●̮̮̃̾•̃̾)۶', '≖‿≖', '(⊙ω⊙✿)', '٩(-̮̮̃•̃)', '(´・ω・`)', '◤(¬‿¬)◥', '^.^', '(•‿•)', '(^⊆^)', "^( '‿' )^", '☆d(o⌒∇⌒o)b', '∑(゜Д゜;)', '(▰˘◡˘▰)', '(• ε •)', '( ͡° ͜ʖ ͡°)', '(\\/) (°,,°) (\\/)', '( ̄(エ) ̄)', '{◕ ◡ ◕}', '(>‘o’)>', 'シ', '(❀‿❀)', '< (^^,) >', 'ヾ(●⌒∇⌒●)ノ', '( ´∀`)', '☾˙❀‿❀˙☽', '°٢°', '^o^', '(=゚ω゚)ノ', '٩(●̮̮̃•̃)۶', '(☞゚∀゚)☞', '(=゜ω゜)', '(。✿‿✿。)', 'ó‿ó', '◎[‿]◎', '(▰˘◡˘▰)', '(︶ω︶)', '(ノ◕ヮ◕)ノ*:・゚✧', '(◠ω◠✿)', '٩(^‿^)۶', '(●*∩_∩*●)', '٩(-̮̮̃-̃)۶', '<丶´Д`>', '(✿◠‿◠)', 'ヽ(´▽`)ノ', '(°⌣°)', '☆(❁‿❁)☆', '(० ्०)', '٩(-̮̮̃•̃)۶', '(╹ェ╹)', 'ᵔᴥᵔ', '•(_)•', 'ヽ( ´ ∇ ` )ノ', '(ミ ̄ー ̄ミ)', '(─‿‿─)', '~(^з^)-', '(*≗*)', '~(^з^)-', '(´・ω・`)', '(。◕‿◕。)', '.=^.^=', '(◠︿◠✿)', 'ッ', '(`・ω・´)', '´ ▽ ` )ノ', '(´∀`)', '(◑‿◐)', 'ヽ(゚ー゚*ヽ)ヽ(*゚ー゚*)ノ(ノ*゚ー゚)ノ', '˚ᆺ˚', 'ヽ(〃^▽^〃)ノ', '。◕‿◕。', '❀◕ ‿ ◕❀', '( °٢° )', 'Ü', '(●´ω`●)', "<('o'<)", '◕‿◕', 'ᵔᴥᵔ', '◙‿◙', ]; } ================================================ FILE: lib/core/utils/provider.dart ================================================ import 'package:flutter/material.dart'; class StatedChangeNotifier extends ChangeNotifier { bool mounted = true; @override void dispose() { mounted = false; super.dispose(); } } ================================================ FILE: lib/main.dart ================================================ import 'package:flutter/material.dart'; import 'package:kazahana/ui/exports.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); runApp(const BaseApp()); } ================================================ FILE: lib/ui/base.dart ================================================ import 'package:kazahana/core/exports.dart'; import 'exports.dart'; class BaseApp extends StatefulWidget { const BaseApp({ super.key, }); @override State createState() => _BaseAppState(); } class _BaseAppState extends State { late ThemerThemeData theme; late double scaleMultiplier; late String translationId; @override void initState() { super.initState(); theme = Themer.defaultTheme(); scaleMultiplier = RelativeScaleData.defaultScaleMultiplier; translationId = ''; AppEvents.stream.listen((final AppEvent event) { if (event == AppEvent.settingsChange) { final ThemerThemeData nTheme = Themer.getCurrentTheme(); if (theme != nTheme) { setState(() { theme = nTheme; }); } final double nScaleMultiplier = RelativeScaleData.getScaleMultiplier(); if (scaleMultiplier != nScaleMultiplier) { setState(() { scaleMultiplier = nScaleMultiplier; }); } } if (event == AppEvent.translationsChange) { final String nTranslationId = Translator.identifier; if (translationId != nTranslationId) { setState(() { translationId = nTranslationId; }); } } }); } @override Widget build(final BuildContext context) => MaterialApp( title: AppMeta.name, navigatorKey: gNavigatorKey, debugShowCheckedModeBanner: false, builder: ( final BuildContext context, final Widget? child, ) => RelativeScaler( data: RelativeScaleData( multiplier: scaleMultiplier, screen: RelativeScaleData.getScreenSize(context), ), child: TranslationWrapper( id: translationId, child: Builder( builder: (final BuildContext context) => Theme( data: theme.getThemeData(context), child: Builder( builder: (final BuildContext context) => ClassicWrapper(child: child!), ), ), ), ), ), onGenerateRoute: (final RouteSettings settings) { final RouteInfo route = RouteInfo(settings); final RoutePage? page = RoutePages.findMatch(route); if (page == null) return null; return page.buildRoutePage(route); }, ); } class ClassicWrapper extends StatelessWidget { const ClassicWrapper({ required this.child, super.key, }); final Widget child; @override Widget build(final BuildContext context) => Stack(children: [child, const SuperImposer()]); } ================================================ FILE: lib/ui/components/anilist/exports.dart ================================================ export 'media_row.dart'; export 'media_slide.dart'; export 'media_tile.dart'; ================================================ FILE: lib/ui/components/anilist/media_row.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; class AnilistMediaRow extends StatelessWidget { const AnilistMediaRow( this.results, { super.key, }); final List results; @override Widget build(final BuildContext context) => ScrollableRow( results .map( (final AnilistMedia x) => SizedBox( width: getTileWidth(context.r), child: AnilistMediaTile(x), ), ) .toList(), ); static const double tileWidthAny = 8; static const double tileWidthMd = 9; static double getTileWidth(final RelativeScaler r) => r.scale(tileWidthAny, md: tileWidthMd); } ================================================ FILE: lib/ui/components/anilist/media_slide.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; class AnilistMediaSlide extends StatefulWidget { const AnilistMediaSlide( this.media, { super.key, }); final AnilistMedia media; @override State createState() => _AnilistMediaSlideState(); } class _AnilistMediaSlideState extends State with AutomaticKeepAliveClientMixin { Widget buildThumbnail(final BuildContext context) => ClipRRect( borderRadius: BorderRadius.circular(context.r.scale(1)), child: AspectRatio( aspectRatio: AnilistMediaTile.coverRatio, child: FadeInImage( placeholder: MemoryImage(Placeholders.transparent1x1Image), image: NetworkImage(widget.media.coverImageExtraLarge), fit: BoxFit.cover, ), ), ); Widget buildContent(final BuildContext context) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Wrap( spacing: context.r.scale(0.25), runSpacing: context.r.scale(0.2), alignment: WrapAlignment.center, children: [ AnilistMediaTile.buildFormatChip( context: context, media: widget.media, ), AnilistMediaTile.buildWatchtimeChip( context: context, media: widget.media, ), if (widget.media.averageScore != null) AnilistMediaTile.buildRatingChip( context: context, media: widget.media, ), if (widget.media.startDate != null || widget.media.endDate != null) AnilistMediaTile.buildAirdateChip( context: context, media: widget.media, ), if (widget.media.isAdult) AnilistMediaTile.buildNSFWChip( context: context, media: widget.media, ), ], ), SizedBox(height: context.r.scale(0.5)), Text( widget.media.titleUserPreferred, style: context.r .responsive( Theme.of(context).textTheme.titleLarge, md: Theme.of(context).textTheme.headlineSmall, )! .copyWith(fontWeight: FontWeight.bold), ), SizedBox(height: context.r.scale(0.25)), if (widget.media.description != null) Text( widget.media.description!, maxLines: 5, overflow: TextOverflow.ellipsis, ), ], ); @override Widget build(final BuildContext context) { super.build(context); return Stack( children: [ Container(color: Theme.of(context).bottomAppBarTheme.color), Positioned.fill( child: FadeInImage( placeholder: MemoryImage(Placeholders.transparent1x1Image), image: NetworkImage( widget.media.bannerImage ?? widget.media.coverImageExtraLarge, ), fit: BoxFit.cover, ), ), if (widget.media.bannerImage == null) ClipRRect( child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 4, sigmaY: 4), child: const SizedBox.expand(), ), ), Positioned.fill( child: Material( type: MaterialType.transparency, child: InkWell( child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ Theme.of(context) .colorScheme .background .withOpacity(0.25), Theme.of(context) .colorScheme .background .withOpacity(0.75), ], ), ), ), onTap: () { Navigator.of(context) .pusher .pushToViewPageFromMedia(widget.media); }, ), ), ), Align( alignment: Alignment.bottomLeft, child: IgnorePointer( child: Padding( padding: EdgeInsets.all(context.r.scale(1)), child: context.r.responsiveBuilder( () => Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: buildThumbnail(context), ), SizedBox(height: context.r.scale(1)), buildContent(context), ], ), md: () => Row( children: [ buildThumbnail(context), SizedBox(width: context.r.scale(1.5)), Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ buildContent(context), ], ), ), ], ), ), ), ), ), ], ); } @override bool get wantKeepAlive => true; } ================================================ FILE: lib/ui/components/anilist/media_tile.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; class AnilistMediaTile extends StatelessWidget { const AnilistMediaTile( this.media, { this.additionalBottomChips = const [], super.key, }); final AnilistMedia media; final List additionalBottomChips; @override Widget build(final BuildContext context) => InkWell( onTap: () { Navigator.of(context).pusher.pushToViewPageFromMedia(media); }, borderRadius: BorderRadius.circular(context.r.scale(0.5)), child: Column( mainAxisSize: MainAxisSize.min, children: [ ClipRRect( borderRadius: BorderRadius.circular(context.r.scale(0.5)), child: AspectRatio( aspectRatio: coverRatio, child: Stack( children: [ Positioned.fill( child: Container( color: Theme.of(context).bottomAppBarTheme.color, ), ), Positioned.fill( child: Image.network( media.coverImageExtraLarge, fit: BoxFit.cover, ), ), Align( alignment: Alignment.bottomRight, child: Padding( padding: EdgeInsets.all(context.r.scale(0.25)), child: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: ListUtils.insertBetween( [ if (media.averageScore != null) buildRatingChip( context: context, media: media, ), buildWatchtimeChip( context: context, media: media, ), buildFormatChip( context: context, media: media, ), if (media.isAdult) AnilistMediaTile.buildNSFWChip( context: context, media: media, ), ...additionalBottomChips, ], SizedBox(height: context.r.scale(0.2)), ), ), ), ), ], ), ), ), SizedBox(height: context.r.scale(0.5)), Flexible( child: Text( media.titleUserPreferred, style: Theme.of(context).textTheme.bodyMedium, textAlign: TextAlign.center, ), ), SizedBox(height: context.r.scale(0.25)), ], ), ); static const double coverRatio = 5 / 8; static Widget buildChip({ required final BuildContext context, required final Widget child, final Widget? icon, final Color? backgroundColor, final Color? textColor, }) => DecoratedBox( decoration: BoxDecoration( color: backgroundColor ?? Theme.of(context).colorScheme.background, borderRadius: BorderRadius.circular(context.r.scale(0.3)), ), child: Padding( padding: EdgeInsets.only( top: context.r.scale(0.05), bottom: context.r.scale(0.1), left: context.r.scale(0.25), right: context.r.scale(0.25), ), child: DefaultTextStyle( style: Theme.of(context).textTheme.labelLarge!.copyWith( fontWeight: FontWeight.normal, color: textColor ?? Theme.of(context).colorScheme.onBackground, ), child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ if (icon != null) ...[ IconTheme( data: Theme.of(context) .iconTheme .copyWith(size: context.r.scale(1)), child: icon, ), SizedBox(width: context.r.scale(0.25)), ], child, ], ), ), ), ); static Widget buildFormatChip({ required final BuildContext context, required final AnilistMedia media, final Color? backgroundColor, final Color? textColor, }) => AnilistMediaTile.buildChip( context: context, icon: media.status == AnilistMediaStatus.releasing ? AnilistMediaTile.ongoingIcon : null, child: Text(media.format.getTitleCase(context.t)), backgroundColor: backgroundColor, textColor: textColor, ); static Widget buildWatchtimeChip({ required final BuildContext context, required final AnilistMedia media, final Color? backgroundColor, final Color? textColor, }) => AnilistMediaTile.buildChip( context: context, child: Text(media.getWatchtime(context.t)), backgroundColor: backgroundColor, textColor: textColor, ); static Widget buildRatingChip({ required final BuildContext context, required final AnilistMedia media, final Color? backgroundColor, final Color? textColor, }) => AnilistMediaTile.buildChip( context: context, icon: AnilistMediaTile.ratingIcon, child: Text('${media.averageScore}%'), backgroundColor: backgroundColor, textColor: textColor, ); static Widget buildAirdateChip({ required final BuildContext context, required final AnilistMedia media, final Color? backgroundColor, final Color? textColor, }) => AnilistMediaTile.buildChip( context: context, icon: airdateIcon, child: Text(media.airdate), backgroundColor: backgroundColor, textColor: textColor, ); static Widget buildNSFWChip({ required final BuildContext context, required final AnilistMedia media, }) => AnilistMediaTile.buildChip( context: context, backgroundColor: ForegroundColors.red, child: Text(context.t.nsfw), ); static const Icon ratingIcon = Icon( Icons.star_rounded, color: ForegroundColors.yellow, ); static const Icon ongoingIcon = Icon( Icons.fiber_manual_record_outlined, color: ForegroundColors.green, ); static const Icon airdateIcon = Icon( Icons.date_range_rounded, color: ForegroundColors.fuchsia, ); } ================================================ FILE: lib/ui/components/body_padding.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../exports.dart'; class HorizontalBodyPadding extends StatelessWidget { const HorizontalBodyPadding( this.child, { super.key, }); final Widget child; @override Widget build(final BuildContext context) => Padding(padding: padding(context), child: child); static const double paddingAny = 0.75; static const double paddingMd = 1; static double paddingValue(final BuildContext context) => context.r.scale(paddingAny, md: paddingMd); static EdgeInsets padding(final BuildContext context) => EdgeInsets.symmetric(horizontal: paddingValue(context)); } ================================================ FILE: lib/ui/components/cross_draggable_scroll_behaviour.dart ================================================ import 'dart:ui'; import 'package:kazahana/core/exports.dart'; class DraggableScrollBehavior extends MaterialScrollBehavior { @override Set get dragDevices => { PointerDeviceKind.touch, PointerDeviceKind.mouse, }; } class DraggableScrollConfiguration extends StatelessWidget { const DraggableScrollConfiguration({ required this.child, super.key, }); final Widget child; @override Widget build(final BuildContext context) => ScrollConfiguration( behavior: DraggableScrollBehavior(), child: child, ); } ================================================ FILE: lib/ui/components/exports.dart ================================================ export 'anilist/exports.dart'; export 'body_padding.dart'; export 'cross_draggable_scroll_behaviour.dart'; export 'rounded_back_button.dart'; export 'scrollable_row.dart'; export 'slideshow.dart'; export 'stated_builder.dart'; export 'super_imposer.dart'; export 'toast.dart'; ================================================ FILE: lib/ui/components/kawaii_face.dart ================================================ import 'package:kazahana/core/exports.dart'; class KawaiiFace extends StatelessWidget { const KawaiiFace({ required this.face, this.text, this.child, super.key, }) : assert(text != null || child != null); final String face; final String? text; final InlineSpan? child; @override Widget build(final BuildContext context) => RichText( text: TextSpan( children: [ TextSpan(text: face), if (text != null) TextSpan(text: text), if (child != null) child!, ], ), textAlign: TextAlign.center, ); } ================================================ FILE: lib/ui/components/rounded_back_button.dart ================================================ import 'package:kazahana/core/exports.dart'; class RoundedBackButton extends StatelessWidget { const RoundedBackButton({ super.key, }); @override Widget build(final BuildContext context) => IconButton( icon: const Icon(Icons.arrow_back_rounded), onPressed: () { Navigator.maybePop(context); }, ); } ================================================ FILE: lib/ui/components/scrollable_row.dart ================================================ import 'package:kazahana/core/exports.dart'; import 'package:kazahana/ui/components/exports.dart'; import 'body_padding.dart'; class ScrollableRow extends StatefulWidget { const ScrollableRow( this.children, { super.key, }); final List children; @override State createState() => _ScrollableRowState(); } class _ScrollableRowState extends State { late final ScrollController scrollController; @override void initState() { super.initState(); scrollController = ScrollController(); } @override void dispose() { super.dispose(); scrollController.dispose(); } SizedBox buildSpacer(final BuildContext context) => SizedBox(width: HorizontalBodyPadding.paddingValue(context)); @override Widget build(final BuildContext context) => DraggableScrollConfiguration( child: SingleChildScrollView( controller: scrollController, scrollDirection: Axis.horizontal, child: Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ buildSpacer(context), ...ListUtils.insertBetween( widget.children, buildSpacer(context), ), buildSpacer(context), ], ), ), ); } ================================================ FILE: lib/ui/components/slideshow.dart ================================================ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:kazahana/ui/components/exports.dart'; class Slideshow extends StatefulWidget { const Slideshow({ required this.children, required this.slideDuration, required this.animationDuration, super.key, }); final List children; final Duration slideDuration; final Duration animationDuration; @override State createState() => _SlideshowState(); } class _SlideshowState extends State with SingleTickerProviderStateMixin { late final TabController tabController; Timer? timer; bool isDragged = false; @override void initState() { super.initState(); tabController = TabController( length: widget.children.length, vsync: this, ); scheduleSlideChange(); } @override void dispose() { super.dispose(); timer?.cancel(); tabController.dispose(); } void scheduleSlideChange() { timer = Timer(widget.slideDuration, () { if (!isDragged) { final int nextIndex = currentIndex + 1 < widget.children.length ? currentIndex + 1 : 0; tabController.animateTo(nextIndex, duration: widget.animationDuration); } scheduleSlideChange(); }); } @override Widget build(final BuildContext context) => DraggableScrollConfiguration( child: NotificationListener( onNotification: (final ScrollNotification x) { if (x is ScrollStartNotification) { isDragged = true; } else if (x is ScrollEndNotification) { isDragged = false; } return false; }, child: TabBarView( controller: tabController, children: widget.children, ), ), ); int get currentIndex => tabController.index; } ================================================ FILE: lib/ui/components/stated_builder.dart ================================================ import 'package:kazahana/core/exports.dart'; class StatedBuilder extends StatelessWidget { const StatedBuilder( this.state, { required this.waiting, required this.processing, required this.finished, required this.failed, super.key, }); final States state; final WidgetBuilder waiting; final WidgetBuilder processing; final WidgetBuilder finished; final WidgetBuilder failed; @override Widget build(final BuildContext context) { if (state == States.waiting) return waiting(context); if (state == States.processing) return processing(context); if (state == States.finished) return finished(context); return failed(context); } } ================================================ FILE: lib/ui/components/super_imposer.dart ================================================ import 'dart:async'; import 'package:kazahana/core/exports.dart'; class SuperImposerEntry { const SuperImposerEntry._({ required this.id, required this.builder, }); factory SuperImposerEntry.create(final WidgetBuilder builder) => SuperImposerEntry._(id: StringUtils.random(), builder: builder); final String id; final WidgetBuilder builder; } class SuperImposer extends StatefulWidget { const SuperImposer({ super.key, }); @override State createState() => _SuperImposerState(); static final Map entries = {}; static final StreamController onChangeController = StreamController.broadcast(); static final Stream onChange = onChangeController.stream; static void insert(final SuperImposerEntry entry) { entries[entry.id] = entry; onChangeController.add(null); } static void remove(final SuperImposerEntry entry) { entries.remove(entry.id); onChangeController.add(null); } } class _SuperImposerState extends State { StreamSubscription? subscription; @override void initState() { super.initState(); subscription = SuperImposer.onChange.listen((final _) { if (!mounted) return; setState(() {}); }); } @override void dispose() { subscription?.cancel(); super.dispose(); } @override Widget build(final BuildContext context) => Stack( children: SuperImposer.entries.values .map((final SuperImposerEntry x) => x.builder(context)) .toList(), ); } ================================================ FILE: lib/ui/components/toast.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../utils/exports.dart'; import 'super_imposer.dart'; class Toast extends StatefulWidget { const Toast({ required this.content, this.duration = defaultToastDuration, this.animationDuration, super.key, }); final Widget content; final Duration duration; final Duration? animationDuration; @override State createState() => _ToastState(); Future show() async => showToast(this); Duration get resolvedAnimationDuration => animationDuration ?? AnimationDurations.defaultNormalAnimation; static const Duration defaultToastDuration = Duration(seconds: 3); static Future showToast(final Toast toast) async { final SuperImposerEntry entry = SuperImposerEntry.create( (final _) => Align( alignment: Alignment.bottomCenter, child: toast, ), ); SuperImposer.insert(entry); await Future.delayed( toast.duration + (toast.resolvedAnimationDuration * 2), ); SuperImposer.remove(entry); } } class _ToastState extends State { bool visible = false; @override void initState() { super.initState(); Future.microtask(() async { setState(() { visible = true; }); await Future.delayed(widget.duration); if (!mounted) return; setState(() { visible = false; }); }); } @override Widget build(final BuildContext context) => AnimatedSwitcher( duration: widget.resolvedAnimationDuration, transitionBuilder: (final Widget child, final Animation animation) => FadeScaleTransition(animation: animation, child: child), child: visible ? Padding( padding: EdgeInsets.all(context.r.scale(0.4)), child: SizedBox( width: double.infinity, child: Material( color: Colors.transparent, child: DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).bottomAppBarTheme.color, borderRadius: BorderRadius.circular(context.r.scale(0.25)), ), child: Padding( padding: EdgeInsets.all(context.r.scale(0.5)), child: Row( children: [ widget.content, ], ), ), ), ), ), ) : const SizedBox.shrink(), ); } ================================================ FILE: lib/ui/exports.dart ================================================ export 'base.dart'; export 'components/exports.dart'; export 'keys.dart'; export 'router/exports.dart'; export 'utils/exports.dart'; ================================================ FILE: lib/ui/keys.dart ================================================ import 'package:kazahana/core/exports.dart'; final GlobalKey gNavigatorKey = GlobalKey(); ================================================ FILE: lib/ui/pages/_home/components/appbar.dart ================================================ import 'dart:async'; import 'package:kazahana/core/exports.dart'; import '../../../exports.dart'; class UnderScoreHomePageAppBar extends StatefulWidget implements PreferredSizeWidget { const UnderScoreHomePageAppBar({ super.key, }); @override State createState() => _UnderScoreHomePageAppBarState(); @override Size get preferredSize => const Size.fromHeight(kToolbarHeight); } class _UnderScoreHomePageAppBarState extends State { StreamSubscription? appEventSubscription; @override void initState() { super.initState(); appEventSubscription = AppEvents.stream.listen((final AppEvent event) { if (event != AppEvent.anilistStateChange) return; setState(() {}); }); } @override void dispose() { super.dispose(); appEventSubscription?.cancel(); } @override Widget build(final BuildContext context) => AppBar( centerTitle: true, title: Text( AppMeta.name, style: Theme.of(context).textTheme.headlineSmall!.copyWith( fontFamily: Fonts.greatVibes, color: Theme.of(context).textTheme.bodyLarge?.color, ), ), actions: [ Row( children: [ InkWell( child: Padding( padding: EdgeInsets.all(context.r.scale(0.5)), child: AnilistAuth.user?.avatarLarge != null ? ClipRRect( borderRadius: BorderRadius.circular(context.r.scale(1)), child: Image.network(AnilistAuth.user!.avatarLarge!), ) : ClipRRect( borderRadius: BorderRadius.circular(context.r.scale(0.2)), child: Image.asset(AssetPaths.anilistLogo), ), ), onTap: () { Navigator.of(context).pusher.pushToAnilistPage(); }, ), ], ), SizedBox(width: context.r.scale(0.5)), ], ); } ================================================ FILE: lib/ui/pages/_home/components/body.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../exports.dart'; import '../provider.dart'; class UnderScoreHomePageBody extends StatelessWidget { const UnderScoreHomePageBody({ super.key, }); Widget buildOnWaiting(final BuildContext context) => SizedBox( height: context.r.scale(12), child: const Center(child: CircularProgressIndicator()), ); Widget buildCarousel({ required final BuildContext context, required final StatedValue> results, }) => Padding( padding: EdgeInsets.only(bottom: context.r.scale(1)), child: StatedBuilder( results.state, waiting: buildOnWaiting, processing: buildOnWaiting, finished: (final _) => AnilistMediaRow(results.value), failed: (final _) => Text('Error: ${results.error}'), ), ); Widget buildText( final String text, { required final BuildContext context, }) => Padding( padding: HorizontalBodyPadding.padding(context) .copyWith(bottom: context.r.scale(0.75, md: 1)), child: Text(text, style: Theme.of(context).textTheme.titleMedium), ); Widget buildTrendsSlideshow(final StatedValue> data) => StatedBuilder( data.state, waiting: buildOnWaiting, processing: buildOnWaiting, finished: (final BuildContext context) => SizedBox( height: context.r.scale(25), child: Slideshow( slideDuration: defaultSlideDuration, animationDuration: AnimationDurations.defaultNormalAnimation, children: data.value .map((final AnilistMedia x) => AnilistMediaSlide(x)) .toList(), ), ), failed: (final _) => const Text('Error'), ); Widget buildBody(final BuildContext context) { final UnderScoreHomePageProvider provider = context.watch(); return switch (provider.type) { TenkaType.anime => Column( key: const ValueKey(TenkaType.anime), mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ buildTrendsSlideshow(provider.trendingAnime), SizedBox(height: context.r.scale(2)), buildText(context.t.topOngoingAnime, context: context), buildCarousel( context: context, results: provider.topOngoingAnime, ), SizedBox(height: context.r.scale(1)), buildText(context.t.mostPopularAnime, context: context), buildCarousel( context: context, results: provider.mostPopularAnime, ), SizedBox(height: context.r.scale(1)), ], ), TenkaType.manga => Column( key: const ValueKey(TenkaType.manga), mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ buildTrendsSlideshow(provider.trendingManga), SizedBox(height: context.r.scale(2)), buildText(context.t.topOngoingManga, context: context), buildCarousel( context: context, results: provider.topOngoingManga, ), SizedBox(height: context.r.scale(1)), buildText(context.t.mostPopularManga, context: context), buildCarousel( context: context, results: provider.mostPopularManga, ), SizedBox(height: context.r.scale(1)), ], ), }; } @override Widget build(final BuildContext context) => PageTransitionSwitcher( duration: AnimationDurations.defaultLongAnimation, transitionBuilder: ( final Widget child, final Animation animation, final Animation secondaryAnimation, ) => SharedAxisTransition( transitionType: SharedAxisTransitionType.vertical, fillColor: Colors.transparent, animation: animation, secondaryAnimation: secondaryAnimation, child: child, ), layoutBuilder: (final List children) => Stack(children: children), child: buildBody(context), ); static const Duration defaultSlideDuration = Duration(seconds: 5); } ================================================ FILE: lib/ui/pages/_home/components/bottombar.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../exports.dart'; import '../provider.dart'; class UnderScoreHomePageBottomBar extends StatelessWidget { const UnderScoreHomePageBottomBar({ required this.provider, super.key, }); final UnderScoreHomePageProvider provider; Future showTypeModal({ required final BuildContext context, required final UnderScoreHomePageProvider provider, }) async { await showModalBottomSheet( context: context, shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(context.r.scale(1))), ), builder: (final BuildContext context) => Padding( padding: EdgeInsets.symmetric(vertical: context.r.scale(0.5)), child: Column( mainAxisSize: MainAxisSize.min, children: [ ...TenkaType.values.map( (final TenkaType x) => RadioListTile( title: Text(x.getTitleCase(context.t)), value: x, groupValue: provider.type, onChanged: (final TenkaType? type) { if (type == null) return; provider.setType(type); Navigator.of(context).pop(); }, ), ), ], ), ), ); } @override Widget build(final BuildContext context) => Padding( padding: EdgeInsets.symmetric( horizontal: context.r.scale(1), vertical: context.r.scale(0.5), ), child: SizedBox( height: context.r.scale(2.5), child: Row( children: [ Expanded( child: Builder( builder: (final BuildContext context) => TextButton( style: TextButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.surfaceVariant, padding: EdgeInsets.symmetric( vertical: context.r.scale(0.5), ), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox(width: context.r.scale(0.5)), Text(provider.type.getTitleCase(context.t)), const Icon(Icons.arrow_drop_up_rounded), ], ), onPressed: () { showTypeModal(context: context, provider: provider); }, ), ), ), SizedBox(width: context.r.scale(0.5)), DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceVariant, borderRadius: BorderRadius.circular(context.r.scale(999)), ), child: IconTheme( data: IconThemeData( color: Theme.of(context).colorScheme.onSurfaceVariant, size: Theme.of(context).textTheme.titleSmall!.fontSize, ), child: Row( children: [ IconButton( icon: const Icon(Icons.search_rounded), onPressed: () { Navigator.of(context).pusher.pushToSearchPage(); }, ), SizedBox(width: context.r.scale(0.25)), IconButton( icon: const Icon(Icons.extension_rounded), onPressed: () { Navigator.of(context).pusher.pushToModulesPage(); }, ), SizedBox(width: context.r.scale(0.25)), IconButton( icon: const Icon(Icons.settings_rounded), onPressed: () { Navigator.of(context).pusher.pushToSettingsPage(); }, ), ], ), ), ), ], ), ), ); } ================================================ FILE: lib/ui/pages/_home/components/exports.dart ================================================ export 'appbar.dart'; export 'body.dart'; export 'bottombar.dart'; ================================================ FILE: lib/ui/pages/_home/provider.dart ================================================ import 'package:kazahana/core/exports.dart'; class UnderScoreHomePageProvider extends StatedChangeNotifier { TenkaType type = TenkaType.anime; final StatedValue> trendingAnime = StatedValue>(); final StatedValue> topOngoingAnime = StatedValue>(); final StatedValue> mostPopularAnime = StatedValue>(); final StatedValue> trendingManga = StatedValue>(); final StatedValue> topOngoingManga = StatedValue>(); final StatedValue> mostPopularManga = StatedValue>(); Future initialize() async { final TenkaType? lastVisitedType = await getHomeLastVisited(); if (lastVisitedType != null && type != lastVisitedType) { type = lastVisitedType; notifyListeners(); } fetch(type); } Future setType(final TenkaType type) async { this.type = type; fetch(type); notifyListeners(); await setHomeLastVisited(type); } void fetch(final TenkaType type) { switch (type) { case TenkaType.anime: fetchTrendingAnimes(); fetchTopOngoingAnimes(); fetchMostPopularAnimes(); case TenkaType.manga: fetchTrendingMangas(); fetchTopOngoingMangas(); fetchMostPopularMangas(); } } Future fetchTrendingAnimes() async { if (!trendingAnime.isWaiting) return; try { trendingAnime.finish(await AnilistMediaEndpoints.trendingAnimes()); } catch (error, stackTrace) { trendingAnime.fail(error, stackTrace); } if (!mounted) return; notifyListeners(); } Future fetchTopOngoingAnimes() async { if (!topOngoingAnime.isWaiting) return; try { topOngoingAnime.finish(await AnilistMediaEndpoints.topOngoingAnimes()); } catch (error, stackTrace) { topOngoingAnime.fail(error, stackTrace); } if (!mounted) return; notifyListeners(); } Future fetchMostPopularAnimes() async { if (!mostPopularAnime.isWaiting) return; try { mostPopularAnime.finish(await AnilistMediaEndpoints.mostPopularAnimes()); } catch (error, stackTrace) { mostPopularAnime.fail(error, stackTrace); } if (!mounted) return; notifyListeners(); } Future fetchTrendingMangas() async { if (!trendingManga.isWaiting) return; try { trendingManga.finish(await AnilistMediaEndpoints.trendingMangas()); } catch (error, stackTrace) { trendingManga.fail(error, stackTrace); } if (!mounted) return; notifyListeners(); } Future fetchTopOngoingMangas() async { if (!topOngoingManga.isWaiting) return; try { topOngoingManga.finish(await AnilistMediaEndpoints.topOngoingMangas()); } catch (error, stackTrace) { topOngoingManga.fail(error, stackTrace); } if (!mounted) return; notifyListeners(); } Future fetchMostPopularMangas() async { if (!mostPopularManga.isWaiting) return; try { mostPopularManga.finish(await AnilistMediaEndpoints.mostPopularMangas()); } catch (error, stackTrace) { mostPopularManga.fail(error, stackTrace); } if (!mounted) return; notifyListeners(); } static const String kHomeLastVisitedKey = 'home_last_visited'; static Future getHomeLastVisited() async { final String? value = await CacheDatabase.get(kHomeLastVisitedKey); return value != null ? EnumUtils.find(TenkaType.values, value) : null; } static Future setHomeLastVisited(final TenkaType type) async { await CacheDatabase.set(kHomeLastVisitedKey, type.name); } } ================================================ FILE: lib/ui/pages/_home/view.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; import 'components/exports.dart'; import 'provider.dart'; class UnderScoreHomePage extends StatelessWidget { const UnderScoreHomePage({ super.key, }); @override Widget build(final BuildContext context) => ChangeNotifierProvider( create: (final _) => UnderScoreHomePageProvider()..initialize(), lazy: false, child: Consumer( builder: ( final BuildContext context, final UnderScoreHomePageProvider provider, final _, ) => Scaffold( appBar: const UnderScoreHomePageAppBar(), extendBody: true, body: SingleChildScrollView( padding: EdgeInsets.only(bottom: context.r.scale(2.5)), child: const UnderScoreHomePageBody(), ), bottomNavigationBar: UnderScoreHomePageBottomBar(provider: provider), ), ), ); } ================================================ FILE: lib/ui/pages/_splash/view.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; class UnderScoreSplashPage extends StatelessWidget { const UnderScoreSplashPage({ super.key, }); @override Widget build(final BuildContext context) => Scaffold( body: Stack( children: [ Align( child: Column( mainAxisSize: MainAxisSize.min, children: [ Text( AppMeta.name, style: Theme.of(context) .textTheme .displayMedium! .copyWith(fontFamily: Fonts.greatVibes), ), Text( 'v${AppMeta.version}', style: Theme.of(context).textTheme.bodySmall, ), ], ), ), Align( alignment: Alignment.bottomRight, child: Padding( padding: EdgeInsets.all(context.r.scale(1)), child: Text( AppMeta.yuki, style: Theme.of(context) .textTheme .headlineMedium! .copyWith(color: Theme.of(context).colorScheme.primary), ), ), ), ], ), ); } ================================================ FILE: lib/ui/pages/anilist/components/body/exports.dart ================================================ export 'login.dart'; export 'profile/exports.dart'; ================================================ FILE: lib/ui/pages/anilist/components/body/login.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../../exports.dart'; class AnilistPageLoginBody extends StatelessWidget { const AnilistPageLoginBody({ super.key, }); @override Widget build(final BuildContext context) => SingleChildScrollView( padding: EdgeInsets.symmetric( horizontal: HorizontalBodyPadding.paddingValue(context), vertical: MediaQuery.of(context).size.height * 0.2, ), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( AppMeta.name, style: Theme.of(context) .textTheme .headlineLarge! .copyWith(fontFamily: Fonts.greatVibes), ), SizedBox(width: context.r.scale(1)), Text( '+', style: Theme.of(context).textTheme.titleLarge!.copyWith( color: Theme.of(context) .textTheme .titleLarge! .color! .withOpacity(0.3), ), ), SizedBox(width: context.r.scale(1)), ClipRRect( borderRadius: BorderRadius.circular(context.r.scale(0.5)), child: SizedBox.square( dimension: context.r.scale(2.5), child: Image.asset( AssetPaths.anilistLogo, fit: BoxFit.cover, ), ), ), ], ), SizedBox(height: context.r.scale(1)), const Divider(), SizedBox(height: context.r.scale(1)), Text( context.t.trackYourProgressUsingAnilist, style: Theme.of(context).textTheme.titleLarge, ), SizedBox(height: context.r.scale(1)), TextButton.icon( icon: const Icon(Icons.login_rounded), label: Text(context.t.loginUsingAnilist), style: TextButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Theme.of(context).colorScheme.onPrimary, padding: EdgeInsets.symmetric(horizontal: context.r.scale(0.75)), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(context.r.scale(0.5)), ), ), onPressed: () async { try { final bool didLaunch = await launchUrl( Uri.parse(AnilistAuth.oauthURL), mode: LaunchMode.externalApplication, ); if (!didLaunch) { throw Exception('Failed to launch URL'); } } catch (err) { if (!context.mounted) return; Toast( content: Text( '${context.t.somethingWentWrong} $err', ), //dart(use_build_context_synchronously) ).show(); } }, ), ], ), ); } ================================================ FILE: lib/ui/pages/anilist/components/body/profile/body.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../../../exports.dart'; import 'provider.dart'; class AnilistPageProfileBodyBody extends StatelessWidget { const AnilistPageProfileBodyBody({ required this.provider, super.key, }); final AnilistPageProfileProvider provider; Widget buildOnWaiting(final BuildContext context) => SizedBox( height: context.r.scale(12), child: const Center(child: CircularProgressIndicator()), ); Widget buildGridRow({ required final BuildContext context, required final List children, }) => Padding( padding: EdgeInsets.only(bottom: context.r.scale(1)), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: ListUtils.insertBetween( children.map((final Widget x) => Expanded(child: x)).toList(), SizedBox(width: context.r.scale(1)), ), ), ); String getMediaProgressText(final AnilistMedia media) => switch (media.type) { AnilistMediaType.anime => '${media.mediaListEntry?.progress ?? 0}/${media.episodes ?? Translation.unk}', AnilistMediaType.manga => [ '${media.mediaListEntry?.progress ?? 0}/${media.episodes ?? 0}', '(${media.mediaListEntry?.progressVolumes ?? 0}/${media.volumes ?? Translation.unk})', ].join(' '), }; List buildTiles({ required final BuildContext context, required final List list, }) => list .map( (final AnilistMedia x) => AnilistMediaTile( x, additionalBottomChips: [ AnilistMediaTile.buildChip( context: context, backgroundColor: Theme.of(context).colorScheme.primary, textColor: Theme.of(context).colorScheme.onPrimary, child: Text(getMediaProgressText(x)), ), ], ), ) .toList(); @override Widget build(final BuildContext context) => Padding( padding: EdgeInsets.symmetric( horizontal: HorizontalBodyPadding.paddingValue(context), vertical: context.r.scale(0.5), ), child: StatedBuilder( provider.list.state, waiting: buildOnWaiting, processing: buildOnWaiting, finished: (final _) => Column( children: ListUtils.chunk( buildTiles(context: context, list: provider.list.value.last), 2, const SizedBox.shrink(), ) .map( (final List x) => buildGridRow(context: context, children: x), ) .toList(), ), failed: (final _) => Text('Error: ${provider.list.error}'), ), ); } ================================================ FILE: lib/ui/pages/anilist/components/body/profile/exports.dart ================================================ export 'wrapper.dart'; ================================================ FILE: lib/ui/pages/anilist/components/body/profile/hero.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../../../exports.dart'; import 'provider.dart'; class AnilistPageProfileBodyHero extends StatelessWidget { const AnilistPageProfileBodyHero({ required this.provider, super.key, }); final AnilistPageProfileProvider provider; Widget buildStatisticsChild({ required final BuildContext context, required final String title, required final String value, }) => RichText( text: TextSpan( children: [ TextSpan( text: '$title: ', style: Theme.of(context).textTheme.bodySmall, ), TextSpan( text: value, style: Theme.of(context).textTheme.bodySmall!.copyWith( fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.primary, ), ), ], ), textAlign: TextAlign.center, ); List buildStatisticsTiles(final BuildContext context) { switch (provider.category.type) { case AnilistMediaType.anime: final AnilistUserStatistics? stats = user.animeStatistics; return [ buildStatisticsChild( context: context, title: context.t.totalAnime, value: stats?.count.toString() ?? Translation.unk, ), buildStatisticsChild( context: context, title: context.t.episodesWatched, value: stats?.episodesWatched.toString() ?? Translation.unk, ), buildStatisticsChild( context: context, title: context.t.timeSpent, value: stats?.minutesWatched != null ? PrettyDurations.prettyHoursMinutesShort( context.t, Duration(minutes: stats!.minutesWatched!), ) : Translation.unk, ), buildStatisticsChild( context: context, title: context.t.meanScore, value: stats != null ? '${stats.meanScore}%' : Translation.unk, ), ]; case AnilistMediaType.manga: final AnilistUserStatistics? stats = user.mangaStatistics; return [ buildStatisticsChild( context: context, title: context.t.totalManga, value: stats?.count.toString() ?? Translation.unk, ), buildStatisticsChild( context: context, title: context.t.volumesRead, value: stats?.volumesRead.toString() ?? Translation.unk, ), buildStatisticsChild( context: context, title: context.t.chaptersRead, value: stats?.chaptersRead.toString() ?? Translation.unk, ), buildStatisticsChild( context: context, title: context.t.meanScore, value: stats != null ? '${stats.meanScore}%' : Translation.unk, ), ]; } } Widget buildHeroContent(final BuildContext context) => Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.end, children: [ ClipRRect( borderRadius: BorderRadius.circular(context.r.scale(0.25)), child: SizedBox( height: context.r.scale(5), child: user.avatarLarge != null ? Image.network( user.avatarLarge!, fit: BoxFit.cover, ) : Image.asset(AssetPaths.anilistLogo), ), ), SizedBox(width: context.r.scale(1)), Expanded( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ ...buildStatisticsTiles(context), const Divider(), Text( user.name, style: Theme.of(context).textTheme.titleLarge!.copyWith( fontWeight: FontWeight.bold, ), ), ], ), ), ], ); @override Widget build(final BuildContext context) => SliverList( delegate: SliverChildListDelegate.fixed( [ Container( color: Theme.of(context).bottomAppBarTheme.color, height: context.r.scale(10), child: Stack( children: [ if (user.bannerImage != null) Positioned.fill( child: Image.network( user.bannerImage!, fit: BoxFit.cover, ), ), Positioned.fill( child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ Colors.transparent, Theme.of(context) .bottomAppBarTheme .color! .withOpacity(0.75), ], ), ), child: const SizedBox.expand(), ), ), Align( alignment: Alignment.bottomCenter, child: Padding( padding: EdgeInsets.all( HorizontalBodyPadding.paddingValue(context), ), child: buildHeroContent(context), ), ), ], ), ), ], ), ); AnilistUser get user => provider.pageProvider.user!; } ================================================ FILE: lib/ui/pages/anilist/components/body/profile/provider.dart ================================================ import 'dart:async'; import 'package:kazahana/core/exports.dart'; import '../../../provider.dart'; class AnilistProfileCategory { const AnilistProfileCategory(this.type, this.status); factory AnilistProfileCategory.parse(final String value) { final List split = value.split('_'); return AnilistProfileCategory( parseAnilistMediaType(split.first), parseAnilistMediaListStatus(split.last), ); } final AnilistMediaType type; final AnilistMediaListStatus status; AnilistProfileCategory copyWith({ final AnilistMediaType? type, final AnilistMediaListStatus? status, }) => AnilistProfileCategory(type ?? this.type, status ?? this.status); String get stringify => '${type.stringify}_${status.stringify}'; @override bool operator ==(final Object other) => other is AnilistProfileCategory && type == other.type && status == other.status; @override int get hashCode => Object.hash(type, status); } class AnilistPageProfileProvider extends StatedChangeNotifier { AnilistPageProfileProvider(this.pageProvider); final AnilistPageProvider pageProvider; AnilistProfileCategory category = const AnilistProfileCategory( AnilistMediaType.anime, AnilistMediaListStatus.current, ); final StatedValue>> list = StatedValue>>(); Future initialize() async { final AnilistProfileCategory? lastVisitedCategory = await getAnilistLastVisitedCategory(); if (lastVisitedCategory != null && lastVisitedCategory != category) { category = lastVisitedCategory; notifyListeners(); } fetch(); } Future change(final AnilistProfileCategory nCategory) async { if (category == nCategory) return; category = nCategory; await setAnilistLastVisitedCategory(category); await fetch(); } Future fetch() async { if (list.hasFinished && list.value.first == category) return; list.waiting(); notifyListeners(); try { list.finish( TwinTuple>( category, await AnilistMediaListEndpoints.fetch( userId: pageProvider.user!.id, type: category.type, status: category.status, sort: AnilistMediaListSort.addedTimeDesc, ), ), ); } catch (error, stackTrace) { list.fail(error, stackTrace); } notifyListeners(); } static const String kAnilistLastVisitedCategoryKey = 'anilist_last_visited_list'; static Future getAnilistLastVisitedCategory() async { final String? value = await CacheDatabase.get(kAnilistLastVisitedCategoryKey); return value != null ? AnilistProfileCategory.parse(value) : null; } static Future setAnilistLastVisitedCategory( final AnilistProfileCategory category, ) async { await CacheDatabase.set(kAnilistLastVisitedCategoryKey, category.stringify); } } ================================================ FILE: lib/ui/pages/anilist/components/body/profile/wrapper.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../../../exports.dart'; import '../../../provider.dart'; import 'body.dart'; import 'hero.dart'; import 'provider.dart'; class AnilistPageProfileBody extends StatefulWidget { const AnilistPageProfileBody({ required this.provider, super.key, }); final AnilistPageProvider provider; @override State createState() => _AnilistPageProfileBodyState(); } class _AnilistPageProfileBodyState extends State { @override Widget build(final BuildContext context) => ChangeNotifierProvider( create: (final _) => AnilistPageProfileProvider(widget.provider)..initialize(), builder: (final BuildContext context, final _) => Consumer( builder: ( final BuildContext context, final AnilistPageProfileProvider provider, final _, ) => NestedScrollView( headerSliverBuilder: ( final BuildContext context, final bool innerBoxIsScrolled, ) => [ AnilistPageProfileBodyHero(provider: provider), SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverPersistentHeader( pinned: true, floating: true, delegate: _AnilistControlsHeaderDelegate(provider), ), ), ], body: CustomScrollView( slivers: [ Builder( builder: (final BuildContext context) => SliverOverlapInjector( handle: NestedScrollView.sliverOverlapAbsorberHandleFor( context, ), ), ), SliverToBoxAdapter( child: AnilistPageProfileBodyBody(provider: provider), ), ], ), ), ), ); } class _AnilistControlsHeaderDelegate extends SliverPersistentHeaderDelegate { const _AnilistControlsHeaderDelegate(this.provider); final AnilistPageProfileProvider provider; Future showButtonOptionsModal({ required final BuildContext context, required final T value, required final List values, required final Map labels, required final void Function(T) onChange, }) async { await showModalBottomSheet( context: context, shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(context.r.scale(1))), ), builder: (final BuildContext context) => Padding( padding: EdgeInsets.symmetric(vertical: context.r.scale(0.5)), child: Column( mainAxisSize: MainAxisSize.min, children: values .map( (final T x) => RadioListTile( title: Text(labels[x]!), value: x, groupValue: value, onChanged: (final T? type) { if (type == null) return; onChange(type); Navigator.of(context).pop(); }, ), ) .toList(), ), ), ); } Widget buildButton({ required final BuildContext context, required final T value, required final List values, required final Map labels, required final void Function(T) onChange, }) => SizedBox( height: buttonHeight, child: TextButton( style: TextButton.styleFrom( backgroundColor: Theme.of(context).bottomAppBarTheme.color, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(context.r.scale(0.25)), ), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox(width: context.r.scale(0.5)), Text(labels[value]!), const Icon(Icons.arrow_drop_down_rounded), ], ), onPressed: () async { await showButtonOptionsModal( context: context, value: value, values: values, labels: labels, onChange: onChange, ); }, ), ); @override Widget build(final BuildContext context, final _, final __) => ColoredBox( color: Theme.of(context).scaffoldBackgroundColor, child: Column( children: [ SizedBox(height: verticalPaddingSize), Padding( padding: EdgeInsets.symmetric( horizontal: verticalPaddingSize, ), child: Row( children: [ Expanded( child: buildButton( context: context, value: provider.category.type, values: AnilistMediaType.values, labels: AnilistMediaType.values.asMap().map( (final _, final AnilistMediaType x) => MapEntry( x, x.asTenkaType.getTitleCase(context.t), ), ), onChange: (final AnilistMediaType value) { provider.change( provider.category.copyWith(type: value), ); }, ), ), SizedBox(width: verticalPaddingSize), Expanded( child: buildButton( context: context, value: provider.category.status, values: AnilistMediaListStatus.values, labels: AnilistMediaListStatus.values.asMap().map( (final _, final AnilistMediaListStatus x) => MapEntry( x, x.getTitleCase(context.t), ), ), onChange: (final AnilistMediaListStatus value) { provider.change( provider.category.copyWith(status: value), ); }, ), ), ], ), ), SizedBox(height: verticalPaddingSize), const Divider(height: 1, thickness: 1), ], ), ); @override bool shouldRebuild(final _AnilistControlsHeaderDelegate oldDelegate) => true; @override double get minExtent => fixedHeight; @override double get maxExtent => fixedHeight; static double get buttonHeight => RelativeScaleData.fromSettingsNoResponsive().scale(2); static double get verticalPaddingSize => RelativeScaleData.fromSettingsNoResponsive().scale(0.3); static double get fixedHeight => buttonHeight + (verticalPaddingSize * 2) + 1; } ================================================ FILE: lib/ui/pages/anilist/components/exports.dart ================================================ export 'body/exports.dart'; ================================================ FILE: lib/ui/pages/anilist/provider.dart ================================================ import 'dart:async'; import 'package:kazahana/core/exports.dart'; class AnilistPageProvider extends StatedChangeNotifier { StreamSubscription? appEventSubscription; void initialize() { fetch(); appEventSubscription = AppEvents.stream.listen((final AppEvent event) { if (mounted && event == AppEvent.anilistStateChange) { notifyListeners(); fetch(); } }); } @override void dispose() { appEventSubscription?.cancel(); super.dispose(); } Future fetch() async {} AnilistUser? get user => AnilistAuth.user; bool get isLoggedIn => user != null; } ================================================ FILE: lib/ui/pages/anilist/route.dart ================================================ import 'package:flutter/material.dart'; import '../../exports.dart'; import 'view.dart'; class AnilistPageRoute extends RoutePage { @override bool matches(final RouteInfo route) => route.name == routeName; @override Widget build(final RouteInfo route) => const AnilistPage(); static const String routeName = '/anilist'; } extension AnilistPageRouteUtils on RoutePusher { Future pushToAnilistPage() => navigator.pushNamed(AnilistPageRoute.routeName); } ================================================ FILE: lib/ui/pages/anilist/view.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; import 'components/exports.dart'; import 'provider.dart'; class AnilistPage extends StatelessWidget { const AnilistPage({ super.key, }); @override Widget build(final BuildContext context) => ChangeNotifierProvider( create: (final _) => AnilistPageProvider()..initialize(), child: Consumer( builder: ( final BuildContext context, final AnilistPageProvider provider, final _, ) => Scaffold( appBar: AppBar(title: Text(context.t.anilist)), body: provider.isLoggedIn ? AnilistPageProfileBody(provider: provider) : const AnilistPageLoginBody(), ), ), ); } ================================================ FILE: lib/ui/pages/home/route.dart ================================================ import 'package:flutter/material.dart'; import '../../exports.dart'; import 'view.dart'; class HomePageRoute extends RoutePage { @override bool matches(final RouteInfo route) => route.name == routeName; @override Widget build(final RouteInfo route) => const HomePage(); static const String routeName = '/'; } extension HomePageRouteUtils on RoutePusher { Future pushToViewPage() => navigator.pushNamed(HomePageRoute.routeName); } ================================================ FILE: lib/ui/pages/home/view.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; import '../_home/view.dart'; import '../_splash/view.dart'; class HomePage extends StatefulWidget { const HomePage({ super.key, }); @override State createState() => _HomePageState(); } class _HomePageState extends State { @override void initState() { super.initState(); AppLoader.initialize().then((final _) async { if (mounted) { setState(() {}); } }); } @override Widget build(final BuildContext context) => PageTransitionSwitcher( duration: AnimationDurations.defaultLongAnimation, transitionBuilder: ( final Widget child, final Animation animation, final Animation secondaryAnimation, ) => FadeThroughTransition( animation: animation, secondaryAnimation: secondaryAnimation, child: child, ), child: AppLoader.ready ? const UnderScoreHomePage() : const UnderScoreSplashPage(), ); } ================================================ FILE: lib/ui/pages/modules/provider.dart ================================================ import 'package:kazahana/core/exports.dart'; class ModulesPageProvider extends StatedChangeNotifier { final Set installing = {}; final Set uninstalling = {}; Future install(final TenkaMetadata metadata) async { installing.add(metadata.id); notifyListeners(); await TenkaManager.repository.install(metadata); if (!mounted) return; installing.remove(metadata.id); notifyListeners(); } Future uninstall(final TenkaMetadata metadata) async { uninstalling.add(metadata.id); notifyListeners(); await TenkaManager.repository.uninstall(metadata); if (!mounted) return; uninstalling.remove(metadata.id); notifyListeners(); } } ================================================ FILE: lib/ui/pages/modules/route.dart ================================================ import 'package:flutter/material.dart'; import '../../exports.dart'; import 'view.dart'; class ModulesPageRoute extends RoutePage { @override bool matches(final RouteInfo route) => route.name == routeName; @override Widget build(final RouteInfo route) => const ModulesPage(); static const String routeName = '/modules'; } extension ModulesPageRouteUtils on RoutePusher { Future pushToModulesPage() => navigator.pushNamed(ModulesPageRoute.routeName); } ================================================ FILE: lib/ui/pages/modules/view.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; import 'provider.dart'; class ModulesPage extends StatelessWidget { const ModulesPage({ super.key, }); VoidCallback createOnPressed({ required final ModulesPageProvider provider, required final TenkaMetadata metadata, }) => () { if (TenkaManager.repository.isInstalled(metadata)) { provider.uninstall(metadata); return; } provider.install(metadata); }; Widget buildModuleTile({ required final BuildContext context, required final ModulesPageProvider provider, required final TenkaMetadata metadata, }) { final bool isInstalling = provider.installing.contains(metadata.id); final bool isUninstalling = provider.uninstalling.contains(metadata.id); final bool isInstalled = TenkaManager.repository.isInstalled(metadata); final IconData icon; Color? iconColor; if (isInstalling) { icon = Icons.hourglass_bottom_rounded; } else if (isUninstalling) { icon = Icons.hourglass_bottom_rounded; } else if (isInstalled) { icon = Icons.done_rounded; iconColor = Theme.of(context).colorScheme.primary; } else { icon = Icons.add_rounded; iconColor = Theme.of(context).colorScheme.primary; } final VoidCallback? onPressed = isInstalling || isUninstalling ? null : createOnPressed(provider: provider, metadata: metadata); return ListTile( contentPadding: EdgeInsets.only( left: context.r.scale(0.75), right: context.r.scale(0.25), ), leading: SizedBox( height: double.infinity, child: SizedBox.square( dimension: context.r.scale(1.5), child: Image.network( TenkaManager.repository.resolver .resolveURL((metadata.thumbnail as TenkaCloudDS).url), ), ), ), title: RichText( text: TextSpan( children: [ TextSpan(text: metadata.name), if (metadata.nsfw) TextSpan( text: ' (${context.t.nsfw})', style: Theme.of(context) .textTheme .labelSmall ?.copyWith(color: ForegroundColors.red), ), ], style: Theme.of(context).textTheme.titleSmall, ), ), subtitle: Text( [ metadata.type.getTitleCase(context.t), context.t.byX(metadata.author), 'v${metadata.version}', ].join(' / '), ), trailing: IconButton( icon: Icon(icon, color: iconColor), onPressed: onPressed, ), onTap: onPressed, ); } @override Widget build(final BuildContext context) => ChangeNotifierProvider( create: (final _) => ModulesPageProvider(), child: Consumer( builder: ( final BuildContext context, final ModulesPageProvider provider, final _, ) => Scaffold( appBar: AppBar(title: Text(context.t.extensions)), body: SingleChildScrollView( child: Column( children: TenkaManager.repository.store.modules.values .sortedBy((final TenkaMetadata x) => x.name) .map( (final TenkaMetadata x) => buildModuleTile( context: context, provider: provider, metadata: x, ), ) .toList(), ), ), ), ), ); } ================================================ FILE: lib/ui/pages/search/components/exports.dart ================================================ export 'results_grid.dart'; export 'search_bar.dart'; ================================================ FILE: lib/ui/pages/search/components/results_grid.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../exports.dart'; class ResultsGrid extends StatelessWidget { const ResultsGrid( this.results, { super.key, }); final List results; Widget buildGridRow({ required final BuildContext context, required final List children, }) => Padding( padding: EdgeInsets.only(bottom: context.r.scale(1)), child: Row( children: ListUtils.insertBetween( children.map((final Widget x) => Expanded(child: x)).toList(), SizedBox(width: context.r.scale(1)), ), ), ); List buildTiles({ required final BuildContext context, }) => results.map((final AnilistMedia x) => AnilistMediaTile(x)).toList(); @override Widget build(final BuildContext context) => Column( children: ListUtils.chunk(buildTiles(context: context), 2) .map( (final List x) => buildGridRow(context: context, children: x), ) .toList(), ); } ================================================ FILE: lib/ui/pages/search/components/search_bar.dart ================================================ import 'dart:async'; import 'package:kazahana/core/exports.dart'; import '../../../exports.dart'; import '../provider.dart'; class SearchBar extends StatefulWidget implements PreferredSizeWidget { const SearchBar({ super.key, }); @override State createState() => _SearchBarState(); @override // TODO: Do something about this // Size get preferredSize => Size.fromHeight(context.r.size(2.5)); Size get preferredSize => const Size.fromHeight(50); } class _SearchBarState extends State { late final TextEditingController textEditingController; String? lastInputText; int? lastInputTime; Timer? searchTimer; @override void initState() { super.initState(); textEditingController = TextEditingController(); } @override void dispose() { super.dispose(); searchTimer?.cancel(); textEditingController.dispose(); } void onInputChange( final String input, { required final SearchPageProvider provider, }) { if (lastInputText == input) return; searchTimer?.cancel(); searchTimer = Timer( const Duration(milliseconds: defaultInputTimeInterval), () => provider.search(textEditingController.text), ); lastInputTime = DateTime.now().millisecondsSinceEpoch; lastInputText = input; } void onCloseButtonTap(final SearchPageProvider provider) { if (textEditingController.text.isNotEmpty) { textEditingController.clear(); provider.reset(); return; } Navigator.of(context).pop(); } @override Widget build(final BuildContext context) => Consumer( builder: ( final BuildContext context, final SearchPageProvider provider, final _, ) => SafeArea( child: Padding( padding: EdgeInsets.symmetric( horizontal: context.r.scale(0.75), vertical: context.r.scale(0.5), ), child: SizedBox( height: context.r.scale(1.5), child: DecoratedBox( decoration: BoxDecoration( borderRadius: BorderRadius.circular(context.r.scale(0.25)), // TODO // color: Theme.of(context).appBarTheme.backgroundColor, ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox(width: context.r.scale(0.5)), Icon( Icons.search_rounded, size: Theme.of(context).textTheme.bodyLarge?.fontSize, color: Theme.of(context).textTheme.bodySmall?.color, ), SizedBox(width: context.r.scale(0.4)), Expanded( child: Padding( padding: EdgeInsets.only(bottom: context.r.scale(0.2)), child: TextField( textAlignVertical: TextAlignVertical.center, textCapitalization: TextCapitalization.words, controller: textEditingController, autofocus: true, decoration: InputDecoration.collapsed( hintText: context.t.searchAnAnimeOrManga, ), onChanged: (final String input) => onInputChange(input, provider: provider), ), ), ), SizedBox(width: context.r.scale(0.4)), Material( color: Colors.transparent, child: InkWell( borderRadius: BorderRadius.circular(context.r.scale(1)), child: Padding( padding: EdgeInsets.all(context.r.scale(0.2)), child: Icon( Icons.close_rounded, size: Theme.of(context).textTheme.bodyLarge?.fontSize, color: Theme.of(context).textTheme.bodySmall?.color, ), ), onTap: () => onCloseButtonTap(provider), ), ), SizedBox(width: context.r.scale(0.2)), ], ), ), ), ), ), ); static const int defaultInputTimeInterval = 500; } ================================================ FILE: lib/ui/pages/search/provider.dart ================================================ import 'package:kazahana/core/exports.dart'; class SearchPageProvider extends StatedChangeNotifier { final StatedValue>> results = StatedValue>>(); void reset() { results.waiting(); notifyListeners(); } Future search(final String terms) async { results.loading(); notifyListeners(); try { results.finish( TwinTuple>( terms, await AnilistMediaEndpoints.search(terms), ), ); } catch (err, trace) { results.fail(err, trace); } if (!mounted) return; notifyListeners(); } } ================================================ FILE: lib/ui/pages/search/route.dart ================================================ import 'package:flutter/material.dart'; import '../../exports.dart'; import 'view.dart'; class SearchPageRoute extends RoutePage { @override bool matches(final RouteInfo route) => route.name == routeName; @override Widget build(final RouteInfo route) => const SearchPage(); static const String routeName = '/search'; } extension SearchPageRouteUtils on RoutePusher { Future pushToSearchPage() => navigator.pushNamed(SearchPageRoute.routeName); } ================================================ FILE: lib/ui/pages/search/view.dart ================================================ import 'package:kazahana/core/exports.dart' hide SearchBar; import '../../exports.dart'; import 'components/exports.dart'; import 'provider.dart'; class SearchPage extends StatefulWidget { const SearchPage({ super.key, }); @override State createState() => _SearchPageState(); } class _SearchPageState extends State { @override Widget build(final BuildContext context) => ChangeNotifierProvider( create: (final _) => SearchPageProvider(), child: Consumer( builder: ( final BuildContext context, final SearchPageProvider provider, final _, ) => Scaffold( appBar: const SearchBar(), body: SingleChildScrollView( padding: EdgeInsets.symmetric( horizontal: context.r.scale(0.75), vertical: context.r.scale(0.25), ), child: StatedBuilder( provider.results.state, waiting: (final _) => const SizedBox.shrink(), processing: (final _) => SizedBox( height: MediaQuery.of(context).size.height / 1.5, child: const Center(child: CircularProgressIndicator()), ), finished: (final _) => ResultsGrid(provider.results.value.last), failed: (final _) => Text(provider.results.error.toString()), ), ), ), ), ); } ================================================ FILE: lib/ui/pages/settings/components/appearance.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../exports.dart'; import 'tiles/exports.dart'; class ApperanceSettings extends StatefulWidget { const ApperanceSettings({ super.key, }); @override State createState() => _ApperanceSettingsState(); } class _ApperanceSettingsState extends State { Future saveSettings() async { await SettingsDatabase.save(); if (!mounted) return; setState(() {}); } @override Widget build(final BuildContext context) => SettingsBodyWrapper( child: Column( children: [ MultiChoiceListTile( title: Text(context.t.accentColor), secondary: const Icon(Icons.format_color_fill_rounded), value: SettingsDatabase.settings.primaryColor ?? ThemerThemeData.defaultForegroundName, items: ForegroundColors.names().asMap().map( (final _, final String name) => MapEntry( name, Text(ForegroundColors.getTitleCase(context.t, name)), ), ), onChanged: (final String value) { SettingsDatabase.settings.primaryColor = value; saveSettings(); }, ), SwitchListTile( title: Text(context.t.useSystemTheme), secondary: const Icon(Icons.highlight_rounded), value: SettingsDatabase.settings.useSystemPreferredTheme, onChanged: (final bool value) { SettingsDatabase.settings.useSystemPreferredTheme = value; saveSettings(); }, ), SwitchListTile( title: Text(context.t.darkMode), secondary: AnimatedSwitcher( duration: AnimationDurations.defaultNormalAnimation, child: Icon( SettingsDatabase.settings.darkMode ? Icons.dark_mode_rounded : Icons.light_mode_rounded, key: UniqueKey(), ), ), value: SettingsDatabase.settings.darkMode, onChanged: SettingsDatabase.settings.useSystemPreferredTheme ? null : (final bool value) { SettingsDatabase.settings.darkMode = value; saveSettings(); }, ), CheckboxListTile( title: Text(context.t.disableAnimations), secondary: const Icon(Icons.animation_rounded), value: SettingsDatabase.settings.disableAnimations, onChanged: (final bool? value) { if (value == null) return; SettingsDatabase.settings.disableAnimations = value; saveSettings(); }, ), ], ), ); } ================================================ FILE: lib/ui/pages/settings/components/exports.dart ================================================ export 'appearance.dart'; ================================================ FILE: lib/ui/pages/settings/components/tiles/choice.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../../exports.dart'; class MultiChoiceListTile extends StatefulWidget { const MultiChoiceListTile({ required this.title, required this.value, required this.items, required this.onChanged, this.secondary, super.key, }); final Widget? secondary; final Widget title; final T value; final Map items; final void Function(T) onChanged; @override State> createState() => _MultiChoiceListTileState(); } class _MultiChoiceListTileState extends State> { final GlobalKey _initActiveOptionKey = GlobalKey(); @override Widget build(final BuildContext context) => ListTile( leading: SizedBox( height: double.infinity, child: widget.secondary, ), title: widget.title, subtitle: widget.items[widget.value], onTap: () async { WidgetsBinding.instance.addPostFrameCallback((final _) { Scrollable.ensureVisible( _initActiveOptionKey.currentContext!, duration: AnimationDurations.defaultNormalAnimation, ); }); final T? value = await showModalBottomSheet( context: context, shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical( top: Radius.circular(context.r.scale(1)), ), ), builder: (final BuildContext context) => SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.only( left: context.r.scale(1), right: context.r.scale(1), top: context.r.scale(1), bottom: context.r.scale(0.5), ), child: DefaultTextStyle( style: Theme.of(context).textTheme.titleLarge!, child: widget.title, ), ), const Divider(), ...widget.items .map( (final T key, final Widget value) => MapEntry( key, RadioListTile( key: key == widget.value ? _initActiveOptionKey : null, value: key, groupValue: widget.value, title: value, onChanged: (final T? value) { if (value == null) return; Navigator.of(context).pop(value); }, ), ), ) .values, ], ), ), ); if (value != null && value != widget.value) { widget.onChanged(value); } }, ); } ================================================ FILE: lib/ui/pages/settings/components/tiles/exports.dart ================================================ export 'choice.dart'; export 'wrapper.dart'; ================================================ FILE: lib/ui/pages/settings/components/tiles/wrapper.dart ================================================ import 'package:kazahana/core/exports.dart'; class SettingsBodyWrapper extends StatelessWidget { const SettingsBodyWrapper({ required this.child, super.key, }); final Widget child; @override Widget build(final BuildContext context) => IconTheme( data: IconThemeData(color: Theme.of(context).colorScheme.primary), child: child, ); } ================================================ FILE: lib/ui/pages/settings/route.dart ================================================ import 'package:flutter/material.dart'; import '../../exports.dart'; import 'view.dart'; class SettingsPageRoute extends RoutePage { @override bool matches(final RouteInfo route) => route.name == routeName; @override Widget build(final RouteInfo route) => const SettingsPage(); static const String routeName = '/settings'; } extension SettingsPageRouteUtils on RoutePusher { Future pushToSettingsPage() => navigator.pushNamed(SettingsPageRoute.routeName); } ================================================ FILE: lib/ui/pages/settings/view.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; import 'components/exports.dart'; class SettingsPage extends StatefulWidget { const SettingsPage({ super.key, }); @override State createState() => _SettingsPageState(); } enum _SettingsCategory { appearance, } extension on _SettingsCategory { String getTitleCase(final Translation translation) => switch (this) { _SettingsCategory.appearance => translation.appearance, }; } class _SettingsPageState extends State { _SettingsCategory category = _SettingsCategory.appearance; PreferredSizeWidget buildAppBar(final BuildContext context) { final AppBar appBar = AppBar( leading: const RoundedBackButton(), title: Text(context.t.settings), ); final double appBarHeight = appBar.preferredSize.height; final double height = (appBarHeight * 2) + 1; return PreferredSize( preferredSize: Size.fromHeight(height), child: Column( children: [ appBar, const Divider(height: 1, thickness: 1), Container( color: Theme.of(context).bottomAppBarTheme.color, height: appBarHeight, width: double.infinity, padding: EdgeInsets.symmetric(horizontal: context.r.scale(0.5)), child: DropdownButtonHideUnderline( child: ButtonTheme( alignedDropdown: true, child: Container( color: Theme.of(context).bottomAppBarTheme.color, child: DropdownButton<_SettingsCategory>( isExpanded: true, value: category, icon: const Icon(Icons.arrow_drop_down_rounded), items: _SettingsCategory.values .map( (final _SettingsCategory x) => DropdownMenuItem<_SettingsCategory>( value: x, child: Text(x.getTitleCase(context.t)), ), ) .toList(), onChanged: (final _SettingsCategory? value) { if (value == null) return; setState(() { category = value; }); }, ), ), ), ), ), ], ), ); } Widget buildBody(final BuildContext context) => switch (category) { _SettingsCategory.appearance => const ApperanceSettings(), }; @override Widget build(final BuildContext context) => Scaffold( appBar: buildAppBar(context), body: SafeArea( child: AnimatedSwitcher( duration: AnimationDurations.defaultNormalAnimation, child: SingleChildScrollView( key: ValueKey<_SettingsCategory>(category), child: buildBody(context), ), ), ), ); } ================================================ FILE: lib/ui/pages/view/components/appbar.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../exports.dart'; import '../provider.dart'; class ViewPageAppBar extends StatelessWidget implements PreferredSizeWidget { const ViewPageAppBar({ super.key, }); Widget buildAppBarButton({ required final BuildContext context, required final Widget icon, required final VoidCallback onPressed, }) { final ViewPageViewProvider provider = context.watch(); return AnimatedSwitcher( duration: AnimationDurations.defaultQuickAnimation, transitionBuilder: (final Widget child, final Animation animation) => FadeTransition(opacity: animation, child: child), child: provider.showFloatingAppBar ? SizedBox.square( dimension: context.r.scale(2), child: DecoratedBox( decoration: BoxDecoration( color: Theme.of(context) .colorScheme .background .withOpacity(0.25), shape: BoxShape.circle, ), child: InkWell( borderRadius: BorderRadius.circular(context.r.scale(2)), onTap: onPressed, child: Center( child: IconTheme( data: IconThemeData( color: Theme.of(context).colorScheme.onBackground, ), child: icon, ), ), ), ), ) : Container(), ); } @override Widget build(final BuildContext context) { final ViewPageProvider provider = context.watch(); return SafeArea( child: SizedBox( height: preferredHeight, child: Row( children: [ SizedBox(width: context.r.scale(0.75)), buildAppBarButton( context: context, icon: const Icon(Icons.close_rounded), onPressed: () { Navigator.of(context).maybePop(); }, ), const Spacer(), if (provider.media.hasFinishedOrFailed) buildAppBarButton( context: context, icon: const Icon(Icons.refresh_rounded), onPressed: () { provider.fetch(); }, ), SizedBox(width: context.r.scale(0.75)), ], ), ), ); } double get preferredHeight => RelativeScaleData.fromSettingsNoResponsive().scale(3.5); @override Size get preferredSize => Size.fromHeight(preferredHeight); } ================================================ FILE: lib/ui/pages/view/components/body.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../exports.dart'; import '../provider.dart'; import 'content/content.dart'; import 'hero.dart'; import 'overview.dart'; enum _ViewPageTabs { overview, content, } extension on _ViewPageTabs { String getTitleCase(final Translation translation, final TenkaType type) => switch (this) { _ViewPageTabs.overview => translation.overview, _ViewPageTabs.content => switch (type) { TenkaType.anime => translation.episodes, TenkaType.manga => translation.chapters, } }; } class ViewPageBody extends StatefulWidget { const ViewPageBody({ super.key, }); @override State createState() => _ViewPageBodyState(); } class _ViewPageBodyState extends State with SingleTickerProviderStateMixin { final List<_ViewPageTabs> tabs = <_ViewPageTabs>[ _ViewPageTabs.overview, _ViewPageTabs.content, ]; late final TabController tabController; late final ScrollController scrollController; @override void initState() { super.initState(); tabController = TabController(length: tabs.length, vsync: this); scrollController = ScrollController() ..addListener(() { if (!mounted || !scrollController.hasClients) return; final ViewPageViewProvider provider = context.read(); provider.setFloatingAppBarVisibility( visible: scrollController.position.pixels < 50, ); }); } @override void dispose() { super.dispose(); tabController.dispose(); scrollController.dispose(); } Widget buildTabBarViewPage({ required final BuildContext context, required final WidgetBuilder builder, }) => Builder( builder: (final BuildContext context) => CustomScrollView( slivers: [ SliverOverlapInjector( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), ), SliverToBoxAdapter(child: builder(context)), ], ), ); @override Widget build(final BuildContext context) { final ViewPageProvider provider = context.watch(); final AnilistMedia media = provider.media.value; return NestedScrollView( controller: scrollController, floatHeaderSlivers: true, headerSliverBuilder: (final BuildContext context, final bool innerBoxIsScrolled) => [ SliverList( delegate: SliverChildListDelegate.fixed( [ ViewPageHero(media), SizedBox(height: context.r.scale(0.75)), const Divider(height: 0, thickness: 0), ], ), ), SliverOverlapAbsorber( handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), sliver: SliverPersistentHeader( pinned: true, floating: true, delegate: _SliverTabBarHeaderDelegate( TabBar( indicatorColor: Theme.of(context).colorScheme.primary, labelStyle: Theme.of(context).textTheme.bodyLarge, controller: tabController, tabs: tabs .asMap() .map( (final int i, final _ViewPageTabs x) => MapEntry( i, Tab( text: x.getTitleCase( context.t, media.type.asTenkaType, ), ), ), ) .values .toList(), ), ), ), ), ], body: MediaQuery.removePadding( removeTop: true, context: context, child: TabBarView( controller: tabController, children: [ buildTabBarViewPage( context: context, builder: (final _) => ViewPageOverview(media), ), buildTabBarViewPage( context: context, builder: (final _) => ViewPageContent(media), ), ], ), ), ); } } class _SliverTabBarHeaderDelegate extends SliverPersistentHeaderDelegate { const _SliverTabBarHeaderDelegate(this.tabBar); final TabBar tabBar; @override Widget build(final BuildContext context, final _, final __) => DecoratedBox( decoration: BoxDecoration(color: Theme.of(context).scaffoldBackgroundColor), child: tabBar, ); @override bool shouldRebuild(final _SliverTabBarHeaderDelegate oldDelegate) => false; @override double get minExtent => tabBar.preferredSize.height; @override double get maxExtent => tabBar.preferredSize.height; } ================================================ FILE: lib/ui/pages/view/components/content/content.dart ================================================ import 'package:kazahana/core/exports.dart'; import 'package:kazahana/core/player/video_player.dart'; import 'provider.dart'; List entries = ['A', 'B', 'C']; class ViewPageContent extends StatelessWidget { const ViewPageContent( this.media, { super.key, }); final AnilistMedia media; @override // TODO: Implement a return function to call the episodes from the provider selected and then open the video player widget after an episode is selected Widget build(final BuildContext context) => ChangeNotifierProvider( create: (final _) => ViewPageContentProvider(media)..initialize(), builder: (final BuildContext context, final _) => Consumer( builder: ( final BuildContext context, final ViewPageContentProvider provider, final _, ) => SafeArea( child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( width: MediaQuery.of(context).size.width, height: 60, child: InputDecorator( decoration: const InputDecoration( border: OutlineInputBorder(), ), child: DropdownButtonHideUnderline( child: DropdownButton( hint: const Text('Select provider:'), items: provider.extensions .map( (final TenkaMetadata x) => DropdownMenuItem( value: x, child: Text(x.name), ), ) .toList(), onChanged: (final TenkaMetadata? value) { if (value == null) { return; } else { entries = [ 'Episode one', 'Episode two', 'Episode three', ]; //placeholder values } }, ), ), ), ), const EpisodeList(), ], ), ), ), ), ); } class EpisodeList extends StatefulWidget { const EpisodeList({super.key}); @override _EpisodeListState createState() => _EpisodeListState(); } class _EpisodeListState extends State { late String selectedEntry; @override Widget build(final BuildContext context) => ListView.builder( shrinkWrap: true, itemCount: entries.length, itemBuilder: (final BuildContext context, final int index) => ListTile( title: Text(entries[index]), onTap: () { setState(() { selectedEntry = entries[index]; Navigator.push( context, MaterialPageRoute( builder: (final BuildContext context) => const PlayerPage(), ), ); }); }, ), ); } ================================================ FILE: lib/ui/pages/view/components/content/exports.dart ================================================ export 'content.dart'; ================================================ FILE: lib/ui/pages/view/components/content/provider.dart ================================================ import 'package:kazahana/core/exports.dart'; class ViewPageContentProvider extends StatedChangeNotifier { ViewPageContentProvider(this.media); final AnilistMedia media; TenkaMetadata? metadata; dynamic extractor; final StatedValue?> computed = StatedValue?>(); final StatedValue> searches = StatedValue>(); Future initialize() async { final String? lastUsedExtractorId = await getLastUsedExtractor(type); final TenkaMetadata? lastUsedExtractor = TenkaManager.repository.installed[lastUsedExtractorId]; if (lastUsedExtractor == null) return; await change(lastUsedExtractor); } Future change(final TenkaMetadata nMetadata) async { metadata = nMetadata; extractor = await TenkaManager.getExtractor(metadata!); notifyListeners(); await setLastUsedExtractor(type, id: metadata!.id); await fetch(); } Future> search(final String terms) async { switch (type) { case TenkaType.anime: final AnimeExtractor extractor = await getCastedExtractor(); return extractor.search(terms, extractor.defaultLocale); case TenkaType.manga: final MangaExtractor extractor = await getCastedExtractor(); return extractor.search(terms, extractor.defaultLocale); } } Future fetch() async { // switch (type) { // case TenkaType.anime: // fetchAnime(); // break; // case TenkaType.manga: // //fetchManga(); // break; // } } Future fetchAnime() async { searches.waiting(); computed.waiting(); notifyListeners(); final AnimeExtractor extractor = await getCastedExtractor(); try { searches.finish( await extractor.search( media.titleRomaji, extractor.defaultLocale, ), ); } catch (error, stackTrace) { searches.fail(error, stackTrace); computed.fail('Failed to fetch search results'); } notifyListeners(); if (searches.hasFailed) return; final String? lastComputedUrl = await getLastComputed( type: type, id: metadata!.id, mediaId: media.id, ); final dynamic computedSearchInfo = (lastComputedUrl != null ? searches.value.firstWhereOrNull( (final SearchInfo x) => x.url == lastComputedUrl, ) : null) ?? IterableExtension(searches.value).firstOrNull; if (computedSearchInfo == null) { computed.fail('Failed to find valid result'); } try { searches.finish( await extractor.search( media.titleRomaji, extractor.defaultLocale, ), ); } catch (error) { computed.fail('Failed to fetch search results'); } notifyListeners(); } T getCastedExtractor() => extractor as T; TenkaType get type => media.type.asTenkaType; List get extensions => TenkaManager.repository.installed.values .where((final TenkaMetadata x) => x.type == media.type.asTenkaType) .toList(); static String getLastUsedExtractorKey(final TenkaType type) => 'view_last_used_${type.name}_extractor'; static Future getLastUsedExtractor(final TenkaType type) async { final String? value = await CacheDatabase.get(getLastUsedExtractorKey(type)); return TenkaManager.repository.installed.containsKey(value) ? value : null; } static Future setLastUsedExtractor( final TenkaType type, { required final String id, }) async { await CacheDatabase.set(getLastUsedExtractorKey(type), id); } static String getLastComputedKey({ required final TenkaType type, required final String id, required final int mediaId, }) => 'view_last_computed_${type.name}_${id}_$mediaId'; static Future getLastComputed({ required final TenkaType type, required final String id, required final int mediaId, }) async => CacheDatabase.get( getLastComputedKey( type: type, id: id, mediaId: mediaId, ), ); static Future setLastComputed({ required final TenkaType type, required final String id, required final int mediaId, required final int url, }) async { await CacheDatabase.set( getLastComputedKey( type: type, id: id, mediaId: mediaId, ), url, ); } } ================================================ FILE: lib/ui/pages/view/components/exports.dart ================================================ export 'appbar.dart'; export 'body.dart'; export 'content/exports.dart'; export 'hero.dart'; export 'overview.dart'; ================================================ FILE: lib/ui/pages/view/components/hero.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../exports.dart'; class ViewPageHero extends StatelessWidget { const ViewPageHero( this.media, { super.key, }); final AnilistMedia media; @override Widget build(final BuildContext context) { final Color chipBackgroundColor = Theme.of(context).colorScheme.secondaryContainer; final Color chipTextColor = Theme.of(context).colorScheme.onSecondaryContainer; final double bannerHeight = context.r.scale(10, md: 15); return Column( mainAxisSize: MainAxisSize.min, children: [ SizedBox( height: context.r.scale(15, md: 20), child: Stack( children: [ SizedBox( height: bannerHeight, width: double.infinity, child: FadeInImage( fit: BoxFit.cover, placeholder: MemoryImage(Placeholders.transparent1x1Image), image: NetworkImage( media.bannerImage ?? media.coverImageExtraLarge, ), ), ), SizedBox( height: bannerHeight, child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ Colors.transparent, Theme.of(context) .bottomAppBarTheme .color! .withOpacity(0.75), ], ), ), child: const SizedBox.expand(), ), ), if (media.bannerImage == null) SizedBox( height: bannerHeight, child: ClipRRect( child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 4, sigmaY: 4), child: const SizedBox.expand(), ), ), ), Align( alignment: Alignment.bottomCenter, child: ClipRRect( borderRadius: BorderRadius.circular(context.r.scale(0.5)), child: Image.network( media.coverImageExtraLarge, height: context.r.scale(10, md: 15), ), ), ), ], ), ), SizedBox(height: context.r.scale(1)), HorizontalBodyPadding( Column( mainAxisSize: MainAxisSize.min, children: [ Text( media.titleUserPreferred, style: Theme.of(context).textTheme.headlineMedium!.copyWith( fontWeight: FontWeight.bold, color: Theme.of(context).textTheme.bodyLarge!.color, ), textAlign: TextAlign.center, ), SizedBox(height: context.r.scale(0.2)), Text( [ media.format.getTitleCase(context.t), media.getWatchtime(context.t), if (media.season != null || media.seasonYear != null) '${media.season?.getTitleCase(context.t) ?? Translation.unk} ${media.seasonYear ?? Translation.unk}', media.status.getTitleCase(context.t), ].join(' | '), style: Theme.of(context).textTheme.bodyLarge!.copyWith( color: Theme.of(context).textTheme.bodySmall!.color, ), ), SizedBox(height: context.r.scale(0.75)), Wrap( spacing: context.r.scale(0.4), runSpacing: context.r.scale(0.2), children: [ if (media.averageScore != null) AnilistMediaTile.buildRatingChip( context: context, media: media, backgroundColor: chipBackgroundColor, textColor: chipTextColor, ), if (media.startDate != null || media.endDate != null) AnilistMediaTile.buildAirdateChip( context: context, media: media, backgroundColor: chipBackgroundColor, textColor: chipTextColor, ), if (media.isAdult) AnilistMediaTile.buildNSFWChip( context: context, media: media, ), ], ), SizedBox(height: context.r.scale(0.4)), Wrap( spacing: context.r.scale(0.4), runSpacing: context.r.scale(0.2), children: media.genres .map( (final String x) => AnilistMediaTile.buildChip( context: context, child: Text(x), backgroundColor: chipBackgroundColor, textColor: chipTextColor, ), ) .toList(), ), ], ), ), SizedBox(height: context.r.scale(0.5)), ], ); } } ================================================ FILE: lib/ui/pages/view/components/overview.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../../exports.dart'; class ViewPageOverview extends StatelessWidget { const ViewPageOverview( this.media, { super.key, }); final AnilistMedia media; Widget buildCharacterTile({ required final BuildContext context, required final AnilistCharacterEdge character, }) => SizedBox( width: AnilistMediaRow.getTileWidth(context.r), child: Column( mainAxisSize: MainAxisSize.min, children: [ ClipRRect( borderRadius: BorderRadius.circular(context.r.scale(0.5)), child: AspectRatio( aspectRatio: AnilistMediaTile.coverRatio, child: Stack( children: [ Positioned.fill( child: Image.network( character.node.imageLarge, fit: BoxFit.cover, ), ), Align( alignment: Alignment.bottomRight, child: Padding( padding: EdgeInsets.all(context.r.scale(0.5)), child: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: ListUtils.insertBetween( [ AnilistMediaTile.buildChip( context: context, backgroundColor: Theme.of(context) .colorScheme .inverseSurface, textColor: Theme.of(context) .colorScheme .onInverseSurface, child: Text( character.role.getTitleCase(context.t), ), ), ], SizedBox(height: context.r.scale(0.2)), ), ), ), ), ], ), ), ), SizedBox(height: context.r.scale(0.25)), Flexible( child: Text( character.node.nameUserPreferred, style: Theme.of(context).textTheme.bodyLarge, textAlign: TextAlign.center, ), ), ], ), ); @override Widget build(final BuildContext context) => SafeArea( child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ if (media.description != null) ...[ SizedBox(height: context.r.scale(1)), HorizontalBodyPadding(Text(media.description!)), ], SizedBox(height: context.r.scale(1.5)), HorizontalBodyPadding( Text( context.t.characters, style: Theme.of(context).textTheme.titleMedium, ), ), SizedBox(height: context.r.scale(0.75, md: 1)), ScrollableRow( media.characters .map( (final AnilistCharacterEdge x) => buildCharacterTile(context: context, character: x), ) .toList(), ), if (media.relations?.isNotEmpty ?? false) ...[ SizedBox(height: context.r.scale(1.5)), HorizontalBodyPadding( Text( context.t.relations, style: Theme.of(context).textTheme.titleMedium, ), ), SizedBox(height: context.r.scale(0.75, md: 1)), ScrollableRow( media.relations! .map( (final AnilistRelationEdge x) => SizedBox( width: AnilistMediaRow.getTileWidth(context.r), child: AnilistMediaTile( x.node, additionalBottomChips: [ AnilistMediaTile.buildChip( context: context, backgroundColor: Theme.of(context) .colorScheme .inverseSurface, textColor: Theme.of(context) .colorScheme .onInverseSurface, child: Text( x.relationType.getTitleCase(context.t), ), ), ], ), ), ) .toList(), ), ], SizedBox(height: context.r.scale(2)), ], ), ), ); } ================================================ FILE: lib/ui/pages/view/provider.dart ================================================ import 'package:kazahana/core/exports.dart'; class ViewPageViewProvider extends ChangeNotifier { bool showFloatingAppBar = true; void setFloatingAppBarVisibility({ required final bool visible, }) { if (showFloatingAppBar != visible) { showFloatingAppBar = visible; notifyListeners(); } } } class ViewPageProvider extends StatedChangeNotifier { late final int mediaId; final StatedValue media = StatedValue(); Future initialize({ required final int id, final AnilistMedia? media, }) async { mediaId = id; if (media != null) { this.media.finish(media); await this.media.value.fetchAll(); if (!mounted) return; notifyListeners(); return; } await fetch(); } Future fetch() async { media.loading(); notifyListeners(); try { media.finish(await AnilistMediaEndpoints.fetchId(mediaId)); await media.value.fetchAll(); } catch (err, trace) { media.fail(err, trace); } if (!mounted) return; notifyListeners(); } } ================================================ FILE: lib/ui/pages/view/route.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; import 'view.dart'; class ViewPageRoute extends RoutePage { final RegExp pattern = RegExp(r'^\/view\/(\d+)$'); @override bool matches(final RouteInfo route) => pattern.hasMatch(route.name); int parseId(final String name) => int.parse(pattern.firstMatch(name)!.group(1)!); @override Widget build(final RouteInfo route) { final int id = parseId(route.name); final AnilistMedia? media = route.data as AnilistMedia?; return ViewPage(mediaId: id, media: media); } } extension ViewPageRouteUtils on RoutePusher { Future pushToViewPage({ required final int id, final AnilistMedia? media, }) => navigator.pushNamed('/view/$id', arguments: media); Future pushToViewPageFromMedia(final AnilistMedia media) => pushToViewPage(id: media.id, media: media); } ================================================ FILE: lib/ui/pages/view/view.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; import 'components/exports.dart'; import 'provider.dart'; class ViewPage extends StatelessWidget { const ViewPage({ required this.mediaId, this.media, super.key, }); final int mediaId; final AnilistMedia? media; @override Widget build(final BuildContext context) => MultiProvider( providers: [ ChangeNotifierProvider( create: (final _) => ViewPageViewProvider(), ), ChangeNotifierProvider( create: (final _) => ViewPageProvider()..initialize(id: mediaId, media: media), ), ], child: Consumer( builder: ( final BuildContext context, final ViewPageProvider provider, final _, ) => Scaffold( appBar: const ViewPageAppBar(), extendBodyBehindAppBar: true, extendBody: true, body: StatedBuilder( provider.media.state, waiting: (final _) => const SizedBox.shrink(), processing: (final _) => const SizedBox.shrink(), finished: (final _) => const ViewPageBody(), failed: (final _) => const SizedBox.shrink(), ), ), ), ); } ================================================ FILE: lib/ui/router/exports.dart ================================================ export 'navigator.dart'; export 'route/exports.dart'; ================================================ FILE: lib/ui/router/navigator.dart ================================================ import 'package:flutter/material.dart'; export '../pages/anilist/route.dart'; export '../pages/home/route.dart'; export '../pages/modules/route.dart'; export '../pages/search/route.dart'; export '../pages/settings/route.dart'; export '../pages/view/route.dart'; class RoutePusher { const RoutePusher(this.navigator); final NavigatorState navigator; } extension NavigatorStateUtils on NavigatorState { RoutePusher get pusher => RoutePusher(this); } ================================================ FILE: lib/ui/router/route/exports.dart ================================================ export 'info.dart'; export 'page.dart'; export 'pages.dart'; ================================================ FILE: lib/ui/router/route/info.dart ================================================ import 'package:kazahana/core/exports.dart'; class RouteInfo { const RouteInfo(this.settings); final RouteSettings settings; String get name => settings.name!; Object? get data => settings.arguments; } ================================================ FILE: lib/ui/router/route/page.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../exports.dart'; abstract class RoutePage { RouteTransitionsBuilder transitionBuilder = defaultTransitionBuilder; bool matches(final RouteInfo route); Widget build(final RouteInfo route); Route buildRoutePage(final RouteInfo route) => defaultRoutePageBuilder(route: route, page: this); static Widget defaultTransitionBuilder( final BuildContext context, final Animation animation, final Animation secondaryAnimation, final Widget child, ) => SharedAxisTransition( fillColor: Theme.of(context).scaffoldBackgroundColor, animation: animation, secondaryAnimation: secondaryAnimation, transitionType: SharedAxisTransitionType.scaled, child: child, ); static Route defaultRoutePageBuilder({ required final RouteInfo route, required final RoutePage page, }) => PageRouteBuilder( settings: route.settings, pageBuilder: (final _, final __, final ___) => page.build(route), transitionDuration: AnimationDurations.defaultNormalAnimation, reverseTransitionDuration: AnimationDurations.defaultNormalAnimation, transitionsBuilder: RoutePage.defaultTransitionBuilder, ); } ================================================ FILE: lib/ui/router/route/pages.dart ================================================ import 'package:kazahana/core/exports.dart'; import '../../pages/anilist/route.dart'; import '../../pages/home/route.dart'; import '../../pages/modules/route.dart'; import '../../pages/search/route.dart'; import '../../pages/settings/route.dart'; import '../../pages/view/route.dart'; import 'info.dart'; import 'page.dart'; abstract class RoutePages { static final HomePageRoute home = HomePageRoute(); static final SearchPageRoute search = SearchPageRoute(); static final ViewPageRoute view = ViewPageRoute(); static final SettingsPageRoute settings = SettingsPageRoute(); static final ModulesPageRoute modules = ModulesPageRoute(); static final AnilistPageRoute anilist = AnilistPageRoute(); static RoutePage? findMatch(final RouteInfo route) => all.firstWhereOrNull((final RoutePage x) => x.matches(route)); static List get all => [ home, search, view, settings, modules, anilist, ]; } ================================================ FILE: lib/ui/utils/animations.dart ================================================ import 'package:kazahana/core/exports.dart'; abstract class AnimationDurations { static const Duration _defaultQuickAnimation = Duration(milliseconds: 100); static const Duration _defaultNormalAnimation = Duration(milliseconds: 300); static const Duration _defaultLongAnimation = Duration(milliseconds: 500); static Duration onlyIfEnabled(final Duration duration) => disabled ? Duration.zero : duration; static bool get disabled => SettingsDatabase.ready && SettingsDatabase.settings.disableAnimations; static Duration get defaultQuickAnimation => onlyIfEnabled(_defaultQuickAnimation); static Duration get defaultNormalAnimation => onlyIfEnabled(_defaultNormalAnimation); static Duration get defaultLongAnimation => onlyIfEnabled(_defaultLongAnimation); } ================================================ FILE: lib/ui/utils/exports.dart ================================================ export 'animations.dart'; export 'placeholders.dart'; export 'relative_scale.dart'; export 'themer.dart'; export 'translations.dart'; ================================================ FILE: lib/ui/utils/placeholders.dart ================================================ import 'dart:convert'; import 'dart:typed_data'; abstract class Placeholders { static const String transparent1x1ImageBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='; static final Uint8List transparent1x1Image = base64.decode(transparent1x1ImageBase64); } ================================================ FILE: lib/ui/utils/relative_scale.dart ================================================ import 'package:kazahana/core/exports.dart'; class RelativeScaler extends InheritedWidget { const RelativeScaler({ required this.data, required super.child, super.key, }); factory RelativeScaler.of(final BuildContext context) => context.dependOnInheritedWidgetOfExactType()!; final RelativeScaleData data; @override bool updateShouldNotify(final RelativeScaler oldWidget) => oldWidget.data != data && oldWidget.data != data; double scale( final double any, { final double? sm, final double? md, final double? lg, final double? xl, }) => data.scale(any, sm: sm, md: md, lg: lg, xl: xl); T responsive( final T any, { final T? sm, final T? md, final T? lg, final T? xl, }) => data.responsive(any, sm: sm, md: md, lg: lg, xl: xl); T responsiveBuilder( final T Function() any, { final T Function()? sm, final T Function()? md, final T Function()? lg, final T Function()? xl, }) => data.responsiveBuilder(any, sm: sm, md: md, lg: lg, xl: xl); } class RelativeScaleData { const RelativeScaleData({ required this.multiplier, required this.screen, }); factory RelativeScaleData.fromSettingsNoResponsive() => RelativeScaleData(multiplier: getScaleMultiplier(), screen: Size.zero); final double multiplier; final Size screen; double scale( final double any, { final double? sm, final double? md, final double? lg, final double? xl, }) => scaleRatio * responsive(any, sm: sm, md: md, lg: lg, xl: xl); T responsive( final T any, { final T? sm, final T? md, final T? lg, final T? xl, }) => switch (screen.width) { > xlWidth when xl != null => xl, > lgWidth when lg != null => lg, > mdWidth when md != null => md, > smWidth when sm != null => sm, _ => any, }; T responsiveBuilder( final T Function() any, { final T Function()? sm, final T Function()? md, final T Function()? lg, final T Function()? xl, }) => switch (screen.width) { > xlWidth when xl != null => xl(), > lgWidth when lg != null => lg(), > mdWidth when md != null => md(), > smWidth when sm != null => sm(), _ => any(), }; RelativeScaleData copyWith({ final double? multiplier, final Size? screen, }) => RelativeScaleData( multiplier: multiplier ?? this.multiplier, screen: screen ?? this.screen, ); static const double scaleRatio = 14; static const double defaultScaleMultiplier = 1; static const double smWidth = 640; static const double mdWidth = 768; static const double lgWidth = 1024; static const double xlWidth = 1280; static double getScaleMultiplier() => SettingsDatabase.ready ? SettingsDatabase.settings.scaleMultiplier : defaultScaleMultiplier; static Size getScreenSize(final BuildContext context) => MediaQuery.of(context).size; } extension RelativeScalerUtils on BuildContext { RelativeScaler get r => RelativeScaler.of(this); } ================================================ FILE: lib/ui/utils/themer.dart ================================================ import 'package:flutter/scheduler.dart'; import 'package:kazahana/core/exports.dart'; import 'relative_scale.dart'; abstract class Themer { static Color _findColor(final String? color, final Color fallback) { if (color == null) return fallback; return ForegroundColors.find(color) ?? fallback; } static ThemerThemeData getCurrentTheme() { final Color foreground = _findColor( SettingsDatabase.settings.primaryColor, ThemerThemeData.defaultForeground, ); final Brightness brightness = SettingsDatabase.settings.useSystemPreferredTheme ? SchedulerBinding.instance.platformDispatcher.platformBrightness : SettingsDatabase.settings.darkMode ? Brightness.dark : Brightness.light; return ThemerThemeData(foreground: foreground, brightness: brightness); } static ThemerThemeData defaultTheme() => const ThemerThemeData(); } class ThemerThemeData { const ThemerThemeData({ this.foreground = defaultForeground, this.brightness = defaultBrightness, this.fontFamily = defaultFontFamily, }); final Color foreground; final Brightness brightness; final String fontFamily; ThemeData getThemeData(final BuildContext context) { final ColorScheme colorScheme = ColorScheme.fromSeed( seedColor: foreground, brightness: brightness, ); final Typography defaultTypography = Typography.material2021(colorScheme: colorScheme); final TextTheme defaultTextTheme = brightness == Brightness.light ? defaultTypography.black : defaultTypography.white; final TextTheme textTheme = defaultTextTheme .merge( TextTheme( displayLarge: TextStyle(fontSize: context.r.scale(3.2)), displayMedium: TextStyle(fontSize: context.r.scale(3)), displaySmall: TextStyle(fontSize: context.r.scale(2.8)), headlineLarge: TextStyle(fontSize: context.r.scale(2.6)), headlineMedium: TextStyle(fontSize: context.r.scale(2.4)), headlineSmall: TextStyle(fontSize: context.r.scale(2.2)), titleLarge: TextStyle(fontSize: context.r.scale(1.8)), titleMedium: TextStyle(fontSize: context.r.scale(1.6)), titleSmall: TextStyle(fontSize: context.r.scale(1.4)), bodyLarge: TextStyle(fontSize: context.r.scale(1.2)), bodyMedium: TextStyle(fontSize: context.r.scale(1.1)), bodySmall: TextStyle(fontSize: context.r.scale(1)), labelLarge: TextStyle(fontSize: context.r.scale(0.9)), labelMedium: TextStyle(fontSize: context.r.scale(0.8)), labelSmall: TextStyle(fontSize: context.r.scale(0.7)), ), ) .apply(fontFamily: fontFamily); return ThemeData( brightness: brightness, colorScheme: colorScheme, textTheme: textTheme, useMaterial3: true, // ? Below properties are workarounds until // ? https://github.com/flutter/flutter/issues/91772 is resolved. // appBarTheme: AppBarTheme(backgroundColor: backgroundColorLevel1), bottomAppBarTheme: BottomAppBarTheme(color: colorScheme.background), // scaffoldBackgroundColor: backgroundColorLevel0, // TODO: https://docs.flutter.dev/release/breaking-changes/toggleable-active-color#migration-guide // toggleableActiveColor: foreground.c500, // canvasColor: backgroundColorLevel2, // dialogBackgroundColor: backgroundColorLevel1, ); } static const String defaultForegroundName = 'indigo'; static const Color defaultForeground = ForegroundColors.indigo; static const Brightness defaultBrightness = Brightness.dark; static const String defaultFontFamily = Fonts.inter; } ================================================ FILE: lib/ui/utils/translations.dart ================================================ import 'package:kazahana/core/exports.dart'; class TranslationWrapper extends InheritedWidget { const TranslationWrapper({ required this.id, required super.child, super.key, }); final String id; @override bool updateShouldNotify(final TranslationWrapper oldWidget) => oldWidget.id != id; Translation get t => Translator.currentTranslation; static TranslationWrapper of(final BuildContext context) => context.dependOnInheritedWidgetOfExactType()!; } extension TranslationWrapperUtils on BuildContext { Translation get t => TranslationWrapper.of(this).t; } ================================================ FILE: linux/.gitignore ================================================ flutter/ephemeral ================================================ FILE: linux/CMakeLists.txt ================================================ # Project-level configuration. cmake_minimum_required(VERSION 3.10) project(runner LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. set(BINARY_NAME "kazahana") # The unique GTK application identifier for this application. See: # https://wiki.gnome.org/HowDoI/ChooseApplicationID set(APPLICATION_ID "io.github.yukino_org.kazahana") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. cmake_policy(SET CMP0063 NEW) # Load bundled libraries from the lib/ directory relative to the binary. set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") # Root filesystem for cross-building. if(FLUTTER_TARGET_PLATFORM_SYSROOT) set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) endif() # Define build configuration options. if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() # Compilation settings that should be applied to most targets. # # Be cautious about adding new options here, as plugins use this function by # default. In most cases, you should add new options to specific targets instead # of modifying this function. function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_14) target_compile_options(${TARGET} PRIVATE -Wall -Werror) target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") endfunction() # Flutter library and tool build rules. set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Define the application target. To change its name, change BINARY_NAME above, # not the value here, or `flutter run` will no longer work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) # Only the install-generated bundle's copy of the executable will launch # correctly, since the resources must in the right relative locations. To avoid # people trying to run the unbundled copy, put it in a subdirectory instead of # the default top-level location. set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) # === Installation === # By default, "installing" just makes a relocatable bundle in the build # directory. set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() # Start with a clean build bundle directory every time. install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ================================================ FILE: linux/flutter/CMakeLists.txt ================================================ # This file controls Flutter-level build steps. It should not be edited. cmake_minimum_required(VERSION 3.10) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. # Serves the same purpose as list(TRANSFORM ... PREPEND ...), # which isn't available in 3.10. function(list_prepend LIST_NAME PREFIX) set(NEW_LIST "") foreach(element ${${LIST_NAME}}) list(APPEND NEW_LIST "${PREFIX}${element}") endforeach(element) set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) endfunction() # === Flutter Library === # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "fl_basic_message_channel.h" "fl_binary_codec.h" "fl_binary_messenger.h" "fl_dart_project.h" "fl_engine.h" "fl_json_message_codec.h" "fl_json_method_codec.h" "fl_message_codec.h" "fl_method_call.h" "fl_method_channel.h" "fl_method_codec.h" "fl_method_response.h" "fl_plugin_registrar.h" "fl_plugin_registry.h" "fl_standard_message_codec.h" "fl_standard_method_codec.h" "fl_string_codec.h" "fl_value.h" "fl_view.h" "flutter_linux.h" ) list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") target_link_libraries(flutter INTERFACE PkgConfig::GTK PkgConfig::GLIB PkgConfig::GIO ) add_dependencies(flutter flutter_assemble) # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/_phony_ COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ================================================ FILE: linux/flutter/generated_plugin_registrant.cc ================================================ // // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" #include #include #include void fl_register_plugins(FlPluginRegistry* registry) { g_autoptr(FlPluginRegistrar) media_kit_libs_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "MediaKitLibsLinuxPlugin"); media_kit_libs_linux_plugin_register_with_registrar(media_kit_libs_linux_registrar); g_autoptr(FlPluginRegistrar) media_kit_video_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "MediaKitVideoPlugin"); media_kit_video_plugin_register_with_registrar(media_kit_video_registrar); g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); } ================================================ FILE: linux/flutter/generated_plugin_registrant.h ================================================ // // Generated file. Do not edit. // // clang-format off #ifndef GENERATED_PLUGIN_REGISTRANT_ #define GENERATED_PLUGIN_REGISTRANT_ #include // Registers Flutter plugins. void fl_register_plugins(FlPluginRegistry* registry); #endif // GENERATED_PLUGIN_REGISTRANT_ ================================================ FILE: linux/flutter/generated_plugins.cmake ================================================ # # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST media_kit_libs_linux media_kit_video url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST media_kit_native_event_loop ) set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) endforeach(ffi_plugin) ================================================ FILE: linux/main.cc ================================================ #include "my_application.h" int main(int argc, char** argv) { g_autoptr(MyApplication) app = my_application_new(); return g_application_run(G_APPLICATION(app), argc, argv); } ================================================ FILE: linux/my_application.cc ================================================ #include "my_application.h" #include #ifdef GDK_WINDOWING_X11 #include #endif #include "flutter/generated_plugin_registrant.h" struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) // Implements GApplication::activate. static void my_application_activate(GApplication* application) { MyApplication* self = MY_APPLICATION(application); GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); // Use a header bar when running in GNOME as this is the common style used // by applications and is the setup most users will be using (e.g. Ubuntu // desktop). // If running on X and not using GNOME then just use a traditional title bar // in case the window manager does more exotic layout, e.g. tiling. // If running on Wayland assume the header bar will work (may need changing // if future cases occur). gboolean use_header_bar = TRUE; #ifdef GDK_WINDOWING_X11 GdkScreen* screen = gtk_window_get_screen(window); if (GDK_IS_X11_SCREEN(screen)) { const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); if (g_strcmp0(wm_name, "GNOME Shell") != 0) { use_header_bar = FALSE; } } #endif if (use_header_bar) { GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); gtk_widget_show(GTK_WIDGET(header_bar)); gtk_header_bar_set_title(header_bar, "kazahana"); gtk_header_bar_set_show_close_button(header_bar, TRUE); gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); } else { gtk_window_set_title(window, "kazahana"); } gtk_window_set_default_size(window, 1280, 720); gtk_widget_show(GTK_WIDGET(window)); g_autoptr(FlDartProject) project = fl_dart_project_new(); fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); FlView* view = fl_view_new(project); gtk_widget_show(GTK_WIDGET(view)); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); gtk_widget_grab_focus(GTK_WIDGET(view)); } // Implements GApplication::local_command_line. static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { MyApplication* self = MY_APPLICATION(application); // Strip out the first argument as it is the binary name. self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); g_autoptr(GError) error = nullptr; if (!g_application_register(application, nullptr, &error)) { g_warning("Failed to register: %s", error->message); *exit_status = 1; return TRUE; } g_application_activate(application); *exit_status = 0; return TRUE; } // Implements GObject::dispose. static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } static void my_application_class_init(MyApplicationClass* klass) { G_APPLICATION_CLASS(klass)->activate = my_application_activate; G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; G_OBJECT_CLASS(klass)->dispose = my_application_dispose; } static void my_application_init(MyApplication* self) {} MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, "flags", G_APPLICATION_NON_UNIQUE, nullptr)); } ================================================ FILE: linux/my_application.h ================================================ #ifndef FLUTTER_MY_APPLICATION_H_ #define FLUTTER_MY_APPLICATION_H_ #include G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, GtkApplication) /** * my_application_new: * * Creates a new Flutter-based application. * * Returns: a new #MyApplication. */ MyApplication* my_application_new(); #endif // FLUTTER_MY_APPLICATION_H_ ================================================ FILE: package.json ================================================ { "name": "@yukino-org/kazahana", "description": "", "private": true, "version": "0.0.0", "author": "Zyrouge", "license": "GPL-3.0", "scripts": { "i18n:build": "phrasey build -p ./.phrasey/config.toml -f toml" }, "dependencies": { "@zyrouge/phrasey-json": "^1.0.3", "@zyrouge/phrasey-locales": "^1.1.9", "@zyrouge/phrasey-toml": "^1.0.3", "fs-extra": "^11.1.1", "phrasey": "^2.0.25" } } ================================================ FILE: packages/anilist/.gitignore ================================================ # Files and directories created by pub. .dart_tool/ .packages # Conventional directory for build output. build/ ================================================ FILE: packages/anilist/.vscode/settings.json ================================================ { "editor.formatOnSave": true } ================================================ FILE: packages/anilist/README.md ================================================ A sample command-line application with an entrypoint in `bin/`, library code in `lib/`, and example unit test in `test/`. ================================================ FILE: packages/anilist/analysis_options.yaml ================================================ include: package:devx/analysis_options.yaml ================================================ FILE: packages/anilist/lib/anilist.dart ================================================ export 'endpoints/exports.dart'; export 'models/exports.dart'; ================================================ FILE: packages/anilist/lib/endpoints/exports.dart ================================================ export 'graphql.dart'; export 'media.dart'; export 'media_list.dart'; export 'relation.dart'; export 'user.dart'; ================================================ FILE: packages/anilist/lib/endpoints/graphql.dart ================================================ import 'dart:convert'; import 'package:shared/http.dart' as http; import 'package:utilx/utilx.dart'; import '../models/exports.dart'; class AnilistGraphQLRequest { const AnilistGraphQLRequest({ required this.query, this.variables = const {}, }); final String query; final Map variables; String get body => json.encode({ 'query': query, 'variables': variables, }); } class AnilistGraphQLResponse { const AnilistGraphQLResponse(this.response); final http.Response response; JsonMap get body => json.decode(response.body) as JsonMap; JsonMap? get data => body['data'] as JsonMap?; List? get errors => hasErrors ? castList(body['errors']) .map((final JsonMap x) => x['message'] as String) .toList() : null; bool get hasErrors => body['errors'] != null; Exception get asException => throw Exception( 'Request failed with status code ${response.statusCode} and errors: ${errors?.map((final String x) => '"$x"').join(', ') ?? '?'}', ); } abstract class AnilistGraphQL { static final Uri baseURL = Uri.parse('https://graphql.anilist.co'); static const Map defaultHeaders = { 'Content-Type': 'application/json', 'Accept': 'application/json', }; static AnilistToken? token; static void Function()? onTokenExpired; static final Map additionalHeaders = {}; static void updateClient({ required final AnilistToken? token, required final void Function()? onTokenExpired, required final Map? additionalHeaders, }) { AnilistGraphQL.token = token; AnilistGraphQL.onTokenExpired = onTokenExpired; if (additionalHeaders != null) { AnilistGraphQL.additionalHeaders.addAll(additionalHeaders); } } static Future request( final AnilistGraphQLRequest request, { final bool retryOnExpiredSession = true, }) async { final http.Response resp = await http.client.post( baseURL, headers: { ...defaultHeaders, ...additionalHeaders, if (token != null) 'Authorization': '${token!.tokenType} ${token!.accessToken}', }, body: request.body, ); final AnilistGraphQLResponse parsed = AnilistGraphQLResponse(resp); if (parsed.hasErrors && retryOnExpiredSession && parsed.errors!.contains('Invalid token')) { token = null; return AnilistGraphQL.request(request); } return parsed; } static bool get isAuthenticated => token != null; } ================================================ FILE: packages/anilist/lib/endpoints/media.dart ================================================ import 'package:utilx/utilx.dart'; import '../models/exports.dart'; import 'graphql.dart'; abstract class AnilistMediaEndpoints { static Future fetchId( final int id, { final int page = 1, final int perPage = 20, }) async { final AnilistGraphQLResponse resp = await AnilistGraphQL.request( AnilistGraphQLRequest( query: ''' query (\$id: Int) { Media (id: \$id) ${AnilistMedia.query} } ''', variables: { 'id': id, }, ), ); final JsonMap? data = resp.data; if (data == null) throw resp.asException; return AnilistMedia(data['Media'] as JsonMap); } static Future> search( final String terms, { final int page = 1, final int perPage = 20, }) async => fetchBulk( >[ TripleTuple('search', 'String', terms), ], page: page, perPage: perPage, ); static Future> trendingAnimes() async { final DateTime now = DateTime.now(); return fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.anime.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.trendingDesc.stringify, AnilistMediaSort.popularityDesc.stringify, ], ), TripleTuple( 'season', 'MediaSeason', getAnimeSeasonFromMonth(now.month).stringify, ), TripleTuple( 'seasonYear', 'Int', now.year, ), ]); } static Future> topOngoingAnimes() async => fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.anime.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.trendingDesc.stringify, AnilistMediaSort.popularityDesc.stringify, ], ), TripleTuple( 'status', 'MediaStatus', AnilistMediaStatus.releasing.stringify, ), ]); static Future> mostPopularAnimes() async => fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.anime.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.popularityDesc.stringify, ], ), ]); static Future> trendingMangas() async => fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.manga.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.trendingDesc.stringify, AnilistMediaSort.popularityDesc.stringify, ], ), ]); static Future> topOngoingMangas() async => fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.manga.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.trendingDesc.stringify, AnilistMediaSort.popularityDesc.stringify, ], ), TripleTuple( 'status', 'MediaStatus', AnilistMediaStatus.releasing.stringify, ), ]); static Future> mostPopularMangas() async => fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.manga.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.popularityDesc.stringify, ], ), ]); static Future> fetchBulk( final List> queries, { final int page = 1, final int perPage = 20, }) async { final AnilistGraphQLResponse resp = await AnilistGraphQL.request( AnilistGraphQLRequest( query: ''' query ( \$page: Int, \$perPage: Int, ${queries.map((final TripleTuple x) => '\$${x.first}: ${x.middle}').join(',\n')} ) { Page (page: \$page, perPage: \$perPage) { media ( ${queries.map((final TripleTuple x) => '${x.first}: \$${x.first}').join(',\n')} ) ${AnilistMedia.query} } } ''', variables: { 'page': page, 'perPage': perPage, ...queries.asMap().map( (final _, final TripleTuple x) => MapEntry(x.first, x.last), ), }, ), ); final JsonMap? data = resp.data; if (data == null) throw resp.asException; return MapUtils.get>(data, ['Page', 'media']) .map((final dynamic x) => AnilistMedia(x as JsonMap)) .toList(); } } ================================================ FILE: packages/anilist/lib/endpoints/media_list.dart ================================================ import 'package:utilx/utilx.dart'; import '../models/exports.dart'; import 'graphql.dart'; abstract class AnilistMediaListEndpoints { static Future> fetch({ required final int userId, required final AnilistMediaType type, required final AnilistMediaListStatus status, required final AnilistMediaListSort sort, final int page = 1, final int perPage = 20, }) async { final AnilistGraphQLResponse resp = await AnilistGraphQL.request( AnilistGraphQLRequest( query: ''' query ( \$page: Int \$perPage: Int \$userId: Int \$type: MediaType \$status: MediaListStatus \$sort: [MediaListSort] ) { Page (page: \$page, perPage: \$perPage) { mediaList ( userId: \$userId type: \$type status: \$status sort: \$sort ) { media ${AnilistMedia.query} } } } ''', variables: { 'page': page, 'perPage': perPage, 'userId': userId, 'type': type.stringify, 'status': status.stringify, 'sort': sort.stringify, }, ), ); final JsonMap? data = resp.data; if (data == null) throw resp.asException; return MapUtils.get>(data, ['Page', 'mediaList']) .cast() .map((final JsonMap x) => AnilistMedia(x['media'] as JsonMap)) .toList(); } } ================================================ FILE: packages/anilist/lib/endpoints/relation.dart ================================================ import 'package:utilx/utilx.dart'; import '../models/exports.dart'; import 'graphql.dart'; abstract class AnilistMediaRelationEndpoints { static Future> fetchRelations( final int mediaId, ) async { final AnilistGraphQLResponse resp = await AnilistGraphQL.request( AnilistGraphQLRequest( query: ''' query (\$id: Int) { Media (id: \$id) { relations { edges { id relationType node ${AnilistMedia.query} } } } } ''', variables: { 'id': mediaId, }, ), ); final JsonMap? data = resp.data; if (data == null) throw resp.asException; return MapUtils.get>( data, ['Media', 'relations', 'edges'], ).map((final dynamic x) => AnilistRelationEdge(x as JsonMap)).toList(); } } ================================================ FILE: packages/anilist/lib/endpoints/user.dart ================================================ import 'package:utilx/utilx.dart'; import '../models/exports.dart'; import 'graphql.dart'; abstract class AnilistUserEndpoints { static Future getAuthenticatedUser() async { if (!AnilistGraphQL.isAuthenticated) { throw Exception('Authenticated required to perform this operation'); } final AnilistGraphQLResponse resp = await AnilistGraphQL.request( const AnilistGraphQLRequest( query: ''' query { Viewer ${AnilistUser.query} } ''', ), retryOnExpiredSession: false, ); final JsonMap? data = resp.data; if (data == null) throw resp.asException; return AnilistUser(data['Viewer'] as JsonMap); } static Future> search( final String terms, { final int page = 1, final int perPage = 20, }) async => fetchBulk( >[ TripleTuple('search', 'String', terms), ], page: page, perPage: perPage, ); static Future> trendingAnimes() async { final DateTime now = DateTime.now(); return fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.anime.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.trendingDesc.stringify, AnilistMediaSort.popularityDesc.stringify, ], ), TripleTuple( 'season', 'MediaSeason', getAnimeSeasonFromMonth(now.month).stringify, ), TripleTuple( 'seasonYear', 'Int', now.year, ), ]); } static Future> topOngoingAnimes() async => fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.anime.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.trendingDesc.stringify, AnilistMediaSort.popularityDesc.stringify, ], ), TripleTuple( 'status', 'MediaStatus', AnilistMediaStatus.releasing.stringify, ), ]); static Future> mostPopularAnimes() async => fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.anime.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.popularityDesc.stringify, ], ), ]); static Future> trendingMangas() async => fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.manga.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.trendingDesc.stringify, AnilistMediaSort.popularityDesc.stringify, ], ), ]); static Future> topOngoingMangas() async => fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.manga.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.trendingDesc.stringify, AnilistMediaSort.popularityDesc.stringify, ], ), TripleTuple( 'status', 'MediaStatus', AnilistMediaStatus.releasing.stringify, ), ]); static Future> mostPopularMangas() async => fetchBulk(>[ TripleTuple( 'type', 'MediaType', AnilistMediaType.manga.stringify, ), TripleTuple( 'sort', '[MediaSort]', [ AnilistMediaSort.popularityDesc.stringify, ], ), ]); static Future> fetchBulk( final List> queries, { final int page = 1, final int perPage = 20, }) async { final AnilistGraphQLResponse resp = await AnilistGraphQL.request( AnilistGraphQLRequest( query: ''' query ( \$page: Int, \$perPage: Int, ${queries.map((final TripleTuple x) => '\$${x.first}: ${x.middle}').join(',\n')} ) { Page (page: \$page, perPage: \$perPage) { media ( ${queries.map((final TripleTuple x) => '${x.first}: \$${x.first}').join(',\n')} ) ${AnilistMedia.query} } } ''', variables: { 'page': page, 'perPage': perPage, ...queries.asMap().map( (final _, final TripleTuple x) => MapEntry(x.first, x.last), ), }, ), ); final JsonMap? data = resp.data; if (data == null) throw resp.asException; return MapUtils.get>(data, ['Page', 'media']) .map((final dynamic x) => AnilistMedia(x as JsonMap)) .toList(); } } ================================================ FILE: packages/anilist/lib/models/character.dart ================================================ import 'package:utilx/utilx.dart'; import '../utils.dart'; import 'fuzzy_date.dart'; class AnilistCharacter { const AnilistCharacter(this.json); final JsonMap json; int get id => json['id'] as int; JsonMap get name => json['name'] as JsonMap; String? get nameFirst => name['first'] as String?; String? get nameMiddle => name['middle'] as String?; String? get nameLast => name['last'] as String?; String get nameFull => name['full'] as String; String? get nameNative => name['native'] as String?; String get nameUserPreferred => name['userPreferred'] as String; JsonMap get image => json['image'] as JsonMap; String get imageLarge => image['large'] as String; String get imageMedium => image['medium'] as String; String? get descriptionRaw => json['description'] as String?; String? get description => descriptionRaw != null ? cleanHtml(descriptionRaw!) : null; String? get gender => json['gender'] as String?; JsonMap get dateOfBirthRaw => json['dateOfBirth'] as JsonMap; AnilistFuzzyDate get dateOfBirth => AnilistFuzzyDate(dateOfBirthRaw); String? get age => json['age'] as String?; String? get bloodType => json['bloodType'] as String?; static const String query = ''' { id name { first middle last full native userPreferred } image { large medium } description gender dateOfBirth ${AnilistFuzzyDate.query} age bloodType } '''; } ================================================ FILE: packages/anilist/lib/models/character_edge.dart ================================================ import 'package:utilx/utilx.dart'; import 'character.dart'; import 'character_role.dart'; class AnilistCharacterEdge { const AnilistCharacterEdge(this.json); final JsonMap json; int get id => json['id'] as int; AnilistCharacterRole get role => parseAnilistCharacterRole(json['role'] as String); AnilistCharacter get node => AnilistCharacter(json['node'] as JsonMap); static const String query = ''' { node ${AnilistCharacter.query} id role } '''; } ================================================ FILE: packages/anilist/lib/models/character_role.dart ================================================ import 'package:utilx/utilx.dart'; enum AnilistCharacterRole { main, supporting, background, } extension AnilistCharacterRoleUtils on AnilistCharacterRole { String get stringify => name.toUpperCase(); } AnilistCharacterRole parseAnilistCharacterRole(final String value) => EnumUtils.find(AnilistCharacterRole.values, value.toLowerCase()); ================================================ FILE: packages/anilist/lib/models/exports.dart ================================================ export 'character.dart'; export 'character_edge.dart'; export 'character_role.dart'; export 'fuzzy_date.dart'; export 'media.dart'; export 'media_format.dart'; export 'media_list_entry.dart'; export 'media_list_sort.dart'; export 'media_list_status.dart'; export 'media_sort.dart'; export 'media_status.dart'; export 'media_type.dart'; export 'relation_edge.dart'; export 'relation_type.dart'; export 'seasons.dart'; export 'token.dart'; export 'user.dart'; ================================================ FILE: packages/anilist/lib/models/fuzzy_date.dart ================================================ import 'package:utilx/utilx.dart'; class AnilistFuzzyDate { const AnilistFuzzyDate(this.json); final JsonMap json; int? get year => json['year'] as int?; int? get month => json['month'] as int?; int? get day => json['day'] as int?; bool get isValidDateTime => year != null && month != null && day != null; DateTime? get asDateTime => isValidDateTime ? DateTime(year!, month!, day!) : null; static const String query = ''' { year month day } '''; } ================================================ FILE: packages/anilist/lib/models/media.dart ================================================ import 'package:utilx/utilx.dart'; import '../endpoints/exports.dart'; import '../utils.dart'; import 'character_edge.dart'; import 'fuzzy_date.dart'; import 'media_format.dart'; import 'media_list_entry.dart'; import 'media_status.dart'; import 'media_type.dart'; import 'relation_edge.dart'; import 'seasons.dart'; class AnilistMedia { AnilistMedia(this.json); final JsonMap json; List? relations; int get id => json['id'] as int; int? get idMal => json['idMal'] as int?; JsonMap get title => json['title'] as JsonMap; String get titleRomaji => title['romaji'] as String; String? get titleEnglish => title['english'] as String?; String get titleNative => title['native'] as String; String get titleUserPreferred => title['userPreferred'] as String; AnilistMediaType get type => parseAnilistMediaType(json['type'] as String); AnilistMediaFormat get format => parseAnilistMediaFormat(json['format'] as String); String? get descriptionRaw => json['description'] as String?; String? get description => descriptionRaw != null ? cleanHtml(descriptionRaw!) : null; JsonMap? get startDateRaw => json['startDate'] as JsonMap; AnilistFuzzyDate? get startDate => startDateRaw != null ? AnilistFuzzyDate(startDateRaw!) : null; JsonMap? get endDateRaw => json['endDate'] as JsonMap; AnilistFuzzyDate? get endDate => endDateRaw != null ? AnilistFuzzyDate(endDateRaw!) : null; AnimeSeasons? get season => json['season'] != null ? parseAnimeSeason(json['season'] as String) : null; int? get seasonYear => json['seasonYear'] as int?; int? get duration => json['duration'] as int?; int? get chapters => json['chapters'] as int?; int? get volumes => json['volumes'] as int?; int? get episodes => json['episodes'] as int?; JsonMap get coverImage => json['coverImage'] as JsonMap; String get coverImageMedium => coverImage['medium'] as String; String get coverImageLarge => coverImage['large'] as String; String get coverImageExtraLarge => coverImage['extraLarge'] as String; String? get coverImageColor => coverImage['color'] as String?; String? get bannerImage => json['bannerImage'] as String?; List get genres => castList(json['genres']); List get synonyms => castList(json['synonyms']); List get tags => castList(json['tags']) .map((final JsonMap x) => x['name'] as String) .toList(); List get characters => castList((json['characters'] as JsonMap)['edges']) .map((final JsonMap x) => AnilistCharacterEdge(x)) .toList(); int? get meanScore => json['meanScore'] as int?; bool get isAdult => json['isAdult'] as bool; String get siteUrl => json['siteUrl'] as String; int? get averageScore => json['averageScore'] as int?; int get popularity => json['popularity'] as int; AnilistMediaStatus get status => parseAnilistMediaStatus(json['status'] as String); AnilistMediaListEntry? get mediaListEntry => json['mediaListEntry'] != null ? AnilistMediaListEntry(json['mediaListEntry'] as JsonMap) : null; Future fetchAll() async { relations = await AnilistMediaRelationEndpoints.fetchRelations(id); } static const String query = ''' { id idMal title { romaji english native userPreferred } type format description startDate ${AnilistFuzzyDate.query} endDate ${AnilistFuzzyDate.query} season seasonYear episodes duration chapters volumes coverImage { medium large extraLarge color } bannerImage genres synonyms tags { name } characters (sort: ROLE, page: 0, perPage: 15) { edges ${AnilistCharacterEdge.query} } meanScore isAdult siteUrl averageScore popularity status mediaListEntry ${AnilistMediaListEntry.query} } '''; } ================================================ FILE: packages/anilist/lib/models/media_format.dart ================================================ enum AnilistMediaFormat { tv, tvShort, movie, special, ova, ona, music, manga, novel, oneshot, } const Map _anilistMediaFormatStringifyMap = { AnilistMediaFormat.tv: 'TV', AnilistMediaFormat.tvShort: 'TV_SHORT', AnilistMediaFormat.movie: 'MOVIE', AnilistMediaFormat.special: 'SPECIAL', AnilistMediaFormat.ova: 'OVA', AnilistMediaFormat.ona: 'ONA', AnilistMediaFormat.music: 'MUSIC', AnilistMediaFormat.manga: 'MANGA', AnilistMediaFormat.novel: 'NOVEL', AnilistMediaFormat.oneshot: 'ONE_SHOT', }; extension AnilistMediaFormatUtils on AnilistMediaFormat { String get stringify => _anilistMediaFormatStringifyMap[this]!; } AnilistMediaFormat parseAnilistMediaFormat(final String value) => _anilistMediaFormatStringifyMap.entries .firstWhere( (final MapEntry x) => x.value == value, ) .key; ================================================ FILE: packages/anilist/lib/models/media_list_entry.dart ================================================ import 'package:utilx/utilx.dart'; import 'fuzzy_date.dart'; import 'media_list_status.dart'; class AnilistMediaListEntry { const AnilistMediaListEntry(this.json); final JsonMap json; int get id => json['id'] as int; int get userId => json['userId'] as int; int get mediaId => json['mediaId'] as int; AnilistMediaListStatus get status => parseAnilistMediaListStatus(json['status'] as String); int get progress => json['progress'] as int; int? get progressVolumes => json['progressVolumes'] as int?; int get repeat => json['repeat'] as int; int get score => json['score'] as int; JsonMap? get startedAtRaw => json['startedAt'] as JsonMap?; AnilistFuzzyDate? get startedAt => startedAtRaw != null ? AnilistFuzzyDate(startedAtRaw!) : null; JsonMap? get completedAtRaw => json['completedAt'] as JsonMap?; AnilistFuzzyDate? get completedAt => completedAtRaw != null ? AnilistFuzzyDate(completedAtRaw!) : null; static const String query = ''' { id userId mediaId status progress progressVolumes repeat score (format: POINT_100) startedAt ${AnilistFuzzyDate.query} completedAt ${AnilistFuzzyDate.query} } '''; } ================================================ FILE: packages/anilist/lib/models/media_list_sort.dart ================================================ import 'package:utilx/utilx.dart'; enum AnilistMediaListSort { mediaId, mediaIdDesc, score, scoreDesc, status, statusDesc, progress, progressDesc, progressVolumes, progressVolumesDesc, repeat, repeatDesc, priority, priorityDesc, startedOn, startedOnDesc, finishedOn, finishedOnDesc, addedTime, addedTimeDesc, updatedTime, updatedTimeDesc, mediaTitleRomaji, mediaTitleRomajiDesc, mediaTitleEnglish, mediaTitleEnglishDesc, mediaTitleNative, mediaTitleNativeDesc, mediaPopularity, mediaPopularityDesc, } extension AnilistMediaListSortUtils on AnilistMediaListSort { String get stringify => StringCase(name).snakeCase.toUpperCase(); } ================================================ FILE: packages/anilist/lib/models/media_list_status.dart ================================================ import 'package:utilx/utilx.dart'; enum AnilistMediaListStatus { current, planning, completed, dropped, paused, repeating, } extension AnilistMediaListStatusUtils on AnilistMediaListStatus { String get stringify => name.toUpperCase(); } AnilistMediaListStatus parseAnilistMediaListStatus(final String value) => EnumUtils.find(AnilistMediaListStatus.values, value.toLowerCase()); ================================================ FILE: packages/anilist/lib/models/media_sort.dart ================================================ import 'package:utilx/utilx.dart'; enum AnilistMediaSort { id, idDesc, titleRomaji, titleRomajiDesc, titleEnglish, titleEnglishDesc, titleNative, titleNativeDesc, type, typeDesc, format, formatDesc, startDate, startDateDesc, endDate, endDateDesc, score, scoreDesc, popularity, popularityDesc, trending, trendingDesc, episodes, episodesDesc, duration, durationDesc, status, statusDesc, chapters, chaptersDesc, volumes, volumesDesc, updatedAt, updatedAtDesc, searchMatch, favourites, favouritesDesc, } extension AnilistMediaSortUtils on AnilistMediaSort { String get stringify => StringCase(name).snakeCase.toUpperCase(); } ================================================ FILE: packages/anilist/lib/models/media_status.dart ================================================ import 'package:utilx/utilx.dart'; enum AnilistMediaStatus { finished, releasing, notYetReleased, cancelled, hiatus, } final Map _anilistMediaStatusStringifyMap = AnilistMediaStatus.values.asMap().map( (final _, final AnilistMediaStatus x) => MapEntry( x, StringCase(x.name).snakeCase.toUpperCase(), ), ); extension AnilistMediaStatusUtils on AnilistMediaStatus { String get stringify => _anilistMediaStatusStringifyMap[this]!; } AnilistMediaStatus parseAnilistMediaStatus(final String value) => _anilistMediaStatusStringifyMap.entries .firstWhere( (final MapEntry x) => x.value == value, ) .key; ================================================ FILE: packages/anilist/lib/models/media_type.dart ================================================ import 'package:utilx/utilx.dart'; enum AnilistMediaType { anime, manga, } extension AnilistMediaTypeUtils on AnilistMediaType { String get stringify => name.toUpperCase(); } AnilistMediaType parseAnilistMediaType(final String value) => EnumUtils.find(AnilistMediaType.values, value.toLowerCase()); ================================================ FILE: packages/anilist/lib/models/relation_edge.dart ================================================ import 'package:utilx/utilx.dart'; import 'media.dart'; import 'relation_type.dart'; class AnilistRelationEdge { const AnilistRelationEdge(this.json); final JsonMap json; int get id => json['id'] as int; AnilistRelationType get relationType => parseAnilistRelationType(json['relationType'] as String); AnilistMedia get node => AnilistMedia(json['node'] as JsonMap); static const String query = ''' relations { edges { id relationType node ${AnilistMedia.query} } } '''; } ================================================ FILE: packages/anilist/lib/models/relation_type.dart ================================================ import 'package:utilx/utilx.dart'; enum AnilistRelationType { adaptation, prequel, sequel, parent, sideStory, character, summary, alternative, spinOff, other, source, compilation, contains, } final Map _anilistMediaStatusStringifyMap = AnilistRelationType.values.asMap().map( (final _, final AnilistRelationType x) => MapEntry( x, StringCase(x.name).snakeCase.toUpperCase(), ), ); extension AnilistRelationTypeUtils on AnilistRelationType { String get stringify => _anilistMediaStatusStringifyMap[this]!; } AnilistRelationType parseAnilistRelationType(final String value) => _anilistMediaStatusStringifyMap.entries .firstWhere( (final MapEntry x) => x.value == value, ) .key; ================================================ FILE: packages/anilist/lib/models/seasons.dart ================================================ import 'package:utilx/utilx.dart'; enum AnimeSeasons { winter, spring, summer, fall, } extension AnimeSeasonsUtils on AnimeSeasons { String get stringify => name.toUpperCase(); } AnimeSeasons parseAnimeSeason(final String code) => EnumUtils.find(AnimeSeasons.values, code.toLowerCase()); AnimeSeasons getAnimeSeasonFromMonth(final int month) => switch (month) { 1 || 2 || 3 => AnimeSeasons.winter, 4 || 5 || 6 => AnimeSeasons.spring, 7 || 8 || 9 => AnimeSeasons.summer, 10 || 11 || 12 => AnimeSeasons.fall, _ => throw Exception('Unexpected anime season month'), }; ================================================ FILE: packages/anilist/lib/models/token.dart ================================================ class AnilistToken { const AnilistToken(this.json); factory AnilistToken.parseURL(final String url) { final Map queries = Uri.splitQueryString(url.split('#')[1]); queries['expires_at'] = (DateTime.now().millisecondsSinceEpoch + (int.parse(queries['expires_in']!) * 1000)) .toString(); return AnilistToken(queries); } final Map json; String get accessToken => json['access_token']!; String get tokenType => json['token_type']!; int get expiresIn => int.parse(json['expires_in']!); int get expiresAtRaw => int.parse(json['expires_at']!); DateTime get expiresAt => DateTime.fromMillisecondsSinceEpoch(expiresAtRaw); } ================================================ FILE: packages/anilist/lib/models/user.dart ================================================ import 'package:utilx/utilx.dart'; class AnilistUserStatistics { const AnilistUserStatistics(this.json); final JsonMap json; int get count => json['count'] as int; double get meanScore => (json['meanScore'] as num).toDouble(); double get standardDeviation => (json['standardDeviation'] as num).toDouble(); int? get minutesWatched => json['minutesWatched'] as int?; int? get episodesWatched => json['episodesWatched'] as int?; int? get chaptersRead => json['chaptersRead'] as int?; int? get volumesRead => json['volumesRead'] as int?; } class AnilistUser { const AnilistUser(this.json); final JsonMap json; int get id => json['id'] as int; String get name => json['name'] as String; String? get about => json['about'] as String?; JsonMap get avatar => json['avatar'] as JsonMap; String? get avatarLarge => avatar['large'] as String?; String? get avatarMedium => avatar['medium'] as String?; String? get bannerImage => json['bannerImage'] as String?; String get siteUrl => json['siteUrl'] as String; JsonMap? get statistics => json['statistics'] as JsonMap?; AnilistUserStatistics? get animeStatistics => statistics?['anime'] != null ? AnilistUserStatistics(statistics!['anime'] as JsonMap) : null; AnilistUserStatistics? get mangaStatistics => statistics?['manga'] != null ? AnilistUserStatistics(statistics!['manga'] as JsonMap) : null; static const String query = ''' { id name about(asHtml: true) avatar { large medium } bannerImage siteUrl statistics { anime { count meanScore standardDeviation minutesWatched episodesWatched chaptersRead volumesRead } manga { count meanScore standardDeviation minutesWatched episodesWatched chaptersRead volumesRead } } } '''; } ================================================ FILE: packages/anilist/lib/utils.dart ================================================ String stripHtmlTags(final String text) => text.replaceAll(RegExp('<[^>]+>'), ''); const Map htmlEntities = { '&': '&', '<': '<', '>': '>', ' ': ' ', '©': '©', '°': '°', '‘': "'", '’': "'", '‚': ',', '“': '"', '”': '"', '™': '™', }; String replaceHtmlEntities(final String text) { String output = text; for (final MapEntry x in htmlEntities.entries) { output = output.replaceAll(x.key, x.value); } return output; } String cleanHtml(final String text) => replaceHtmlEntities(stripHtmlTags(text)); ================================================ FILE: packages/anilist/pubspec.yaml ================================================ name: anilist description: "-" version: 0.0.0 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: shared: path: ../shared utilx: git: url: https://github.com/yukino-org/packages.git ref: dart_utilx dev_dependencies: devx: git: url: https://github.com/yukino-org/packages.git ref: dart_devx ================================================ FILE: packages/anilist/tests/_utils.dart ================================================ import 'package:anilist/anilist.dart'; String stringifyAnilistCharacterEdge(final AnilistCharacterEdge edge) => ''' id: ${edge.id} role: ${edge.role} node: ${padLeftMultilineString(stringifyAnilistCharacter(edge.node))} ''' .trim(); String stringifyAnilistCharacter(final AnilistCharacter character) => ''' id: ${character.id} name: ${character.name} nameFirst: ${character.nameFirst} nameMiddle: ${character.nameMiddle} nameLast: ${character.nameLast} nameFull: ${character.nameFull} nameNative: ${character.nameNative} nameUserPreferred: ${character.nameUserPreferred} image: ${character.image} imageLarge: ${character.imageLarge} imageMedium: ${character.imageMedium} description: ${character.description} gender: ${character.gender} dateOfBirthRaw: ${character.dateOfBirthRaw} dateOfBirth: ${character.dateOfBirth} age: ${character.age} bloodType: ${character.bloodType} ''' .trim(); String stringifyAnilistMedia(final AnilistMedia media) => ''' id: ${media.id} idMal: ${media.idMal} title: ${media.title} titleRomaji: ${media.titleRomaji} titleEnglish: ${media.titleEnglish} titleNative: ${media.titleNative} titleUserPreferred: ${media.titleUserPreferred} type: ${media.type} format: ${media.format} description: ${media.description} startDateRaw: ${media.startDateRaw} startDate: ${media.startDate} endDateRaw: ${media.endDateRaw} endDate: ${media.endDate} season: ${media.season} duration: ${media.duration} chapters: ${media.chapters} volumes: ${media.volumes} episodes: ${media.episodes} coverImage: ${media.coverImage} coverImageMedium: ${media.coverImageMedium} coverImageLarge: ${media.coverImageLarge} coverImageExtraLarge: ${media.coverImageExtraLarge} coverImageColor: ${media.coverImageColor} bannerImage: ${media.bannerImage} genres: ${media.genres} synonyms: ${media.synonyms} tags: ${media.tags} characters: ${media.characters.map((final AnilistCharacterEdge x) => '> ${padLeftMultilineString(stringifyAnilistCharacterEdge(x))}').join('\n')} meanScore: ${media.meanScore} isAdult: ${media.isAdult} siteUrl: ${media.siteUrl} averageScore: ${media.averageScore} popularity: ${media.popularity} status: ${media.status} ''' .trim(); String padLeftMultilineString(final String text, [final int spaces = 1]) => text.split('\n').map((final String x) => ' ' * spaces + x).join('\n'); ================================================ FILE: packages/anilist/tests/search.dart ================================================ import 'package:anilist/anilist.dart'; import '../../../cli/utils/exports.dart'; import '_utils.dart'; const Logger _logger = Logger('anilist_search'); Future main() async { const List terms = [ 'mayo chiki', 'naruto', 'masamune kun 2', ]; for (final String x in terms) { final Stopwatch watch = Stopwatch()..start(); final List results = await AnilistMediaEndpoints.search(x); watch.stop(); _logger.info('Results for "$x" (${watch.elapsedMilliseconds}ms)'); if (results.isEmpty) throw Exception('Query results are empty'); int i = 1; for (final AnilistMedia y in results) { _logger.info('$i.'); _logger.info(padLeftMultilineString(stringifyAnilistMedia(y))); i++; } _logger.println(); } } ================================================ FILE: packages/anilist/tests/trends.dart ================================================ import 'package:anilist/anilist.dart'; import '../../../cli/utils/exports.dart'; import '_utils.dart'; const Logger _logger = Logger('anilist_trending'); typedef _TrendingFn = Future> Function(); Future main() async { final Map fns = { 'Trending Animes': () async => AnilistMediaEndpoints.trendingAnimes(), 'Top Ongoing Animes': () async => AnilistMediaEndpoints.topOngoingAnimes(), 'Most Popular Animes': () async => AnilistMediaEndpoints.mostPopularAnimes(), 'Trending Mangas': () async => AnilistMediaEndpoints.trendingMangas(), 'Top Ongoing Mangas': () async => AnilistMediaEndpoints.topOngoingMangas(), 'Most Popular Mangas': () async => AnilistMediaEndpoints.mostPopularMangas(), }; for (final MapEntry x in fns.entries) { final Stopwatch watch = Stopwatch()..start(); final List results = await x.value(); watch.stop(); _logger.info('Results for "${x.key}" (${watch.elapsedMilliseconds}ms)'); if (results.isEmpty) throw Exception('Query results are empty'); int i = 1; for (final AnilistMedia y in results) { _logger.info('$i.'); _logger.info(padLeftMultilineString(stringifyAnilistMedia(y))); i++; } _logger.println(); } } ================================================ FILE: packages/shared/.gitignore ================================================ # Files and directories created by pub. .dart_tool/ .packages # Conventional directory for build output. build/ ================================================ FILE: packages/shared/.vscode/settings.json ================================================ { "editor.formatOnSave": true } ================================================ FILE: packages/shared/README.md ================================================ A sample command-line application with an entrypoint in `bin/`, library code in `lib/`, and example unit test in `test/`. ================================================ FILE: packages/shared/analysis_options.yaml ================================================ include: package:devx/analysis_options.yaml ================================================ FILE: packages/shared/lib/http.dart ================================================ import 'package:http/http.dart'; export 'package:http/http.dart' hide delete, get, head, patch, post, put, read, readBytes; final Client client = Client(); ================================================ FILE: packages/shared/pubspec.yaml ================================================ name: shared description: "-" version: 0.0.0 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" dependencies: http: ^1.1.0 dev_dependencies: devx: git: url: https://github.com/yukino-org/packages.git ref: dart_devx ================================================ FILE: pubspec.yaml ================================================ name: kazahana description: An extension-based Anime and Manga client. publish_to: none version: 3.0.0 environment: sdk: ">=3.0.0 <4.0.0" dependencies: anilist: path: packages/anilist animations: ^2.0.3 collection: ^1.16.0 encrypt: ^5.0.1 flutter: sdk: flutter json_annotation: ^4.8.1 media_kit: ^1.1.10 media_kit_libs_video: ^1.0.4 media_kit_video: ^1.2.4 path: ^1.8.2 path_provider: ^2.0.11 perks: ^1.0.0 provider: ^6.0.3 shared: path: packages/shared tenka: git: url: https://github.com/yukino-org/packages.git ref: dart_tenka tenka_runtime: git: url: https://github.com/yukino-org/packages.git ref: dart_tenka_runtime uni_links: ^0.5.1 url_launcher: ^6.1.5 utilx: git: url: https://github.com/yukino-org/packages.git ref: dart_utilx dev_dependencies: build_runner: ^2.0.0 devx: git: url: https://github.com/yukino-org/packages.git ref: dart_devx image: ^4.1.3 json_serializable: ^6.3.1 flutter: uses-material-design: true assets: - assets/images/ - assets/translations/ fonts: - family: Inter fonts: - asset: ./assets/fonts/Inter-Regular.ttf - asset: ./assets/fonts/Inter-Medium.ttf weight: 600 - asset: ./assets/fonts/Inter-Bold.ttf weight: 800 - family: GreatVibes fonts: - asset: ./assets/fonts/GreatVibes-Regular.ttf