Implementation chapter · Coverage index
Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.
Pinned baseline for comparison. Use the reviewed listings in the implementation chapters and the reviewed source archive when reconstructing the app. See the architecture review for changes.
vendor/yokan-ext
- Source · gitlink · binary/gitlink lines.
- Manual task: Create this as its own build/repository boundary; follow the dedicated chapter and the pinned revision in snapshot metadata.
This directory is a submodule boundary. Its files are listed separately in this workbook; preserve its standalone build and the revision recorded in the manifest. complete-source-end: #
vendor/yokan-ext/.github/workflows/ci.yml
- Source · configuration / resource · 20 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 6321b44f7148dc851458e2ce4c277f7d59462dc5159866698b8bdcf517ef20ef.
Complete file
name: CI
on:
push:
pull_request:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
- uses: android-actions/setup-android@v3
- name: Install Android SDK 36
run: sdkmanager "platforms;android-36"
- name: Test and assemble
run: ./gradlew desktopTest assembleRelease --no-daemon
vendor/yokan-ext/.gitignore
- Source · configuration / resource · 9 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 92f0d33dcb49b8b811674e13b7089e785be2ac944984f644c865d69d0f50f015.
Complete file
build
.gradle
local.properties
.kotlin
.project
.classpath
.settings/
.idea/
*.iml
vendor/yokan-ext/LICENSE-APACHE-MIHON
- Source · configuration / resource · 176 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 59899c6091b540582ed617e8eeaac4919dc985ccfc35459ee9752b699be5205b.
Complete file
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
vendor/yokan-ext/README.md
- Source · documentation / design asset · 24 lines.
- Manual task: Use as design/history/reference material; reconcile claims with current code and tests before reproducing behavior. Recreate relevant documentation after the implementation is verified.
Exact file bytes / download · SHA-256 9ebf65d8468f91aec58de0c246e471ef92b030078d776e14fe62b52bbd112aea.
Complete file
# yokan-ext
Kotlin Multiplatform extension server library.
## Prerequisites
- JDK 17
- Android SDK Platform 36
Gradle is pinned to 8.13 by the checked-in wrapper.
## Build and test
If Gradle cannot find the Android SDK automatically, copy
`local.properties.example` to `local.properties` and set `sdk.dir` to the
SDK location.
Run the supported local checks:
```sh
./gradlew desktopTest assembleRelease
```
The same command is run in GitHub Actions.
vendor/yokan-ext/build.gradle.kts
- Source · configuration / resource · 66 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 f5418b5bebe35508bc32f1e023fa1d7da1250f897b86e1c423a54ee577263fdb.
Complete file
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
kotlin("multiplatform") version "2.4.21"
kotlin("plugin.serialization") version "2.4.21"
id("com.android.kotlin.multiplatform.library") version "9.4.1"
}
group = "eu.friedcutlet.yokan"
version = "0.1.0-SNAPSHOT"
kotlin {
compilerOptions {
freeCompilerArgs.add("-Xexpect-actual-classes")
}
android {
namespace = "eu.friedcutlet.yokan.ext"
compileSdk = 37
minSdk = 26
compilerOptions.jvmTarget.set(JvmTarget.JVM_17)
withHostTest {}
}
jvm("desktop")
@OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)
wasmJs { browser() }
// JNI headers are vendored beside JvmBridge.h so cinterop does not depend on the JDK running Gradle.
listOf(iosX64(), iosArm64(), iosSimulatorArm64()).forEach { target ->
target.compilations.getByName("main").cinterops.create("JvmBridge") {
definitionFile.set(project.file("src/nativeInterop/cinterop/JvmBridge.def"))
compilerOpts("-I${project.file("src/nativeInterop/cinterop").absolutePath}")
}
}
sourceSets {
commonMain.dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.12.0")
}
iosMain.dependencies {
implementation("com.squareup.okio:okio:3.18.2")
implementation("io.ktor:ktor-client-core:3.6.0")
implementation("io.ktor:ktor-client-darwin:3.6.0")
}
commonTest.dependencies {
implementation(kotlin("test"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0")
}
androidMain.dependencies {
implementation("io.reactivex:rxjava:1.3.8")
implementation("io.reactivex:rxandroid:1.2.1")
implementation("uy.kohesive.injekt:injekt-core:1.16.1")
implementation("com.squareup.okhttp3:logging-interceptor:5.5.1")
implementation("com.squareup.okhttp3:okhttp:5.5.1")
implementation("com.squareup.okio:okio:3.18.2")
implementation("com.squareup.okhttp3:okhttp-brotli:5.5.1")
implementation("androidx.core:core-ktx:1.19.1")
implementation("androidx.preference:preference-ktx:1.2.1")
implementation("org.jsoup:jsoup:1.23.2")
implementation("org.nanohttpd:nanohttpd:2.3.1")
implementation("com.fasterxml.jackson.core:jackson-databind:2.22.4")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.22.4")
}
}
}
vendor/yokan-ext/gradle.properties
- Source · configuration / resource · 4 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 2788882c62796c9cd92932664f5d39bb4ed97f57f9263b020743c437bbc5a896.
Complete file
org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
kotlin.code.style=official
android.useAndroidX=true
kotlin.mpp.enableCInteropCommonization=true
vendor/yokan-ext/gradle/wrapper/gradle-wrapper.jar
- Source · binary resource / tooling · binary/gitlink lines.
- Manual task: Retain or independently recreate this artifact with its expected name, format and dimensions; preserve applicable licenses. Generated wrapper/tool binaries need regeneration, not transcription.
Exact file bytes / download · SHA-256 81a82aaea5abcc8ff68b3dfcb58b3c3c429378efd98e7433460610fecd7ae45f.
Retain this binary at the path above. Binary images, fonts, wrapper JARs and native/tooling assets have no text listing; use the download or the source archive. complete-source-end: #
vendor/yokan-ext/gradle/wrapper/gradle-wrapper.properties
- Source · configuration / resource · 7 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 347db32a65a973a9efe235dfb7275d28b77c6cb85552be26d7bffdf03224730a.
Complete file
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
vendor/yokan-ext/gradlew
- Source · configuration / resource · 251 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 734b3879d3501dce471cf0522d3bcbafe76873d9fc5129345b67fb43bd15e933.
Complete file
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
vendor/yokan-ext/gradlew.bat
- Source · configuration / resource · 94 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 2209f919a22528af59a2af2ad97e8d056cca18e39f7d87aa3fd549a73b180150.
Complete file
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
vendor/yokan-ext/local.properties.example
- Source · configuration / resource · 2 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 7ab87f9f472e200168a21bf429342ec8363cddaed41e791bb41d3ef64d11bac2.
Complete file
# Copy this file to local.properties and set sdk.dir to your Android SDK path.
# sdk.dir=/path/to/android/sdk
vendor/yokan-ext/settings.gradle.kts
- Source · configuration / resource · 17 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 4257cf3300d82502eae169a3b63750028cfab716452cabcf843ad94534b9ffba.
Complete file
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "yokan-ext"
vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/CastBridgeCompatibilityTest.kt
- Source · test / fixture · 99 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
13: class CastBridgeCompatibilityTest {
21: public interface SAnime {
29: public class LegacyAnime implements SAnime {
Exact file bytes / download · SHA-256 b7f069dd48ea1bca33c65e75e22d02cf2b8613a0bf0b6aa9af9e46f534502e24.
Complete file
package eu.friedcutlet.yokan.ext
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import eu.kanade.tachiyomi.animesource.model.Credit
import eu.kanade.tachiyomi.animesource.model.SAnime
import kotlinx.serialization.json.Json
import m_extension_server.model.toJAnime
import java.net.URLClassLoader
import java.nio.file.Files
import javax.tools.ToolProvider
import kotlin.test.*
class CastBridgeCompatibilityTest {
@Test fun classCompiledAgainstAnOlderInterfaceLinksAgainstTheCurrentHost() {
val directory = Files.createTempDirectory("yokan-legacy-anime-api").toFile()
try {
val source = directory.resolve("eu/kanade/tachiyomi/animesource/model").apply { mkdirs() }
// Deliberately compile without the new cast member, then load against the real host.
source.resolve("SAnime.java").writeText("""
package eu.kanade.tachiyomi.animesource.model;
public interface SAnime {
String getUrl(); String getTitle(); String getArtist(); String getAuthor();
String getDescription(); String getGenre(); String getThumbnail_url();
int getStatus(); boolean getInitialized();
}
""".trimIndent())
source.resolve("LegacyAnime.java").writeText("""
package eu.kanade.tachiyomi.animesource.model;
public class LegacyAnime implements SAnime {
public String getUrl() { return "/legacy-binary"; }
public String getTitle() { return "Old binary"; }
public String getArtist() { return null; }
public String getAuthor() { return "Author"; }
public String getDescription() { return null; }
public String getGenre() { return null; }
public String getThumbnail_url() { return null; }
public int getStatus() { return 1; }
public boolean getInitialized() { return true; }
}
""".trimIndent())
val compiler = requireNotNull(ToolProvider.getSystemJavaCompiler()) { "Run bridge unit tests with a JDK" }
assertEquals(0, compiler.run(null, null, null, "-d", directory.path,
source.resolve("SAnime.java").path, source.resolve("LegacyAnime.java").path))
URLClassLoader(arrayOf(directory.toURI().toURL()), SAnime::class.java.classLoader).use { loader ->
val old = loader.loadClass("eu.kanade.tachiyomi.animesource.model.LegacyAnime")
.getDeclaredConstructor().newInstance() as SAnime
assertEquals("Old binary", old.toJAnime().title)
assertNull(old.toJAnime().cast)
assertEquals("Episodes", old.toJAnime().fetch_type)
assertEquals(-1.0, old.toJAnime().season_number)
val copy = SAnime.create().apply { url = old.url; copyFrom(old) }
assertEquals("Author", copy.author)
assertNull(copy.cast)
assertEquals(eu.kanade.tachiyomi.animesource.model.FetchType.Episodes, copy.fetch_type)
}
} finally { directory.deleteRecursively() }
}
@Test fun hostAnimeCreditsSurviveCopyAndBridgeSerialization() {
val credit = Credit("Actor", "Voice actor", "Hero", "https://cdn.example/actor.jpg")
val anime = SAnime.create().apply {
url = "/title"
title = "Title"
status = SAnime.UPCOMING
cast = listOf(credit)
}
val copy = SAnime.create().apply { url = anime.url; copyFrom(anime) }
assertEquals(listOf(credit), copy.cast)
assertEquals(SAnime.UPCOMING, copy.status)
assertEquals(credit, Json.decodeFromString<Credit>(Json.encodeToString(Credit.serializer(), credit)))
val mapper = jacksonObjectMapper()
val json = mapper.readTree(mapper.writeValueAsString(copy.toJAnime()))
assertEquals("Actor", json["cast"][0]["name"].asText())
assertEquals("https://cdn.example/actor.jpg", json["cast"][0]["image_url"].asText())
assertEquals("Hero", json["cast"][0]["character"].asText())
assertEquals(7, json["status"].asInt())
}
@Test fun legacyExtensionWithoutAccessorStillReturnsDetails() {
val base = SAnime.create().apply { url = "/legacy"; title = "Legacy title" }
val oldBinary = object : SAnime by base {
override var cast: List<Credit>?
get() = throw AbstractMethodError("Older APK has no getCast accessor")
set(_) { throw AbstractMethodError("Older APK has no setCast accessor") }
}
assertEquals("Legacy title", oldBinary.toJAnime().title)
assertNull(oldBinary.toJAnime().cast)
val copy = SAnime.create().apply { url = oldBinary.url; copyFrom(oldBinary) }
assertEquals("Legacy title", copy.title)
assertNull(copy.cast)
}
@Test fun explicitEmptyCreditsRemainAnExplicitClear() {
val anime = SAnime.create().apply { url = "/title"; title = "Title"; cast = emptyList() }
val copy = SAnime.create().apply { url = anime.url; cast = listOf(Credit("Old")); copyFrom(anime) }
assertEquals(emptyList(), copy.toJAnime().cast)
}
}
vendor/yokan-ext/src/androidHostTest/kotlin/eu/friedcutlet/yokan/ext/SeasonBridgeTest.kt
- Source · test / fixture · 45 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
12: class SeasonBridgeTest {
20: override suspend fun getSeasonList(anime: SAnime): List<SAnime> {
Exact file bytes / download · SHA-256 4df3e1e12720f178ff26214693a8c97a0c8d614b7cb963d3dc06256dfc99c6b5.
Complete file
package eu.friedcutlet.yokan.ext
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import eu.kanade.tachiyomi.animesource.AnimeSource
import eu.kanade.tachiyomi.animesource.model.FetchType
import eu.kanade.tachiyomi.animesource.model.SAnime
import m_extension_server.impl.MihonInvoker
import m_extension_server.model.AnimeData
import m_extension_server.model.toJAnime
import kotlin.test.*
class SeasonBridgeTest {
private val data = AnimeData("/show", "Show", null, null, null, null, null, null, null)
private val mapper = jacksonObjectMapper()
@Test fun forwardsSeasonEntriesWithFetchTypeAndNumber() {
val source = object : AnimeSource {
override val id = 7L
override val name = "Source"
override suspend fun getSeasonList(anime: SAnime): List<SAnime> {
assertEquals("/show", anime.url)
return listOf(
SAnime.create().apply { url = "/show/s1"; title = "Season 1"; season_number = 1.0 },
SAnime.create().apply { url = "/show/movies"; title = "Movies"; fetch_type = FetchType.Seasons },
)
}
}
val json = mapper.readTree(mapper.writeValueAsString(MihonInvoker.invokeGetSeasonList(source, data)))
assertEquals("/show/s1", json[0]["url"].asText())
assertEquals(1.0, json[0]["season_number"].asDouble())
assertEquals("Episodes", json[0]["fetch_type"].asText())
assertEquals("Seasons", json[1]["fetch_type"].asText())
assertEquals(-1.0, json[1]["season_number"].asDouble())
}
@Test fun olderSourcesListNoSeasonsAndDetailsStayEpisodeLists() {
val source = object : AnimeSource { override val id = 8L; override val name = "Old" }
assertEquals(emptyList(), MihonInvoker.invokeGetSeasonList(source, data))
val parent = SAnime.create().apply { url = "/show"; title = "Show"; fetch_type = FetchType.Seasons }
assertEquals("Seasons", mapper.readTree(mapper.writeValueAsString(parent.toJAnime()))["fetch_type"].asText())
val copy = SAnime.create().apply { url = parent.url; copyFrom(parent) }
assertEquals(FetchType.Seasons, copy.fetch_type)
assertFailsWith<IllegalArgumentException> { MihonInvoker.invokeGetSeasonList(source, null) }
}
}
vendor/yokan-ext/src/androidMain/AndroidManifest.xml
- Source · configuration / resource · 3 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 678647a824ef7ab16066708585790ab265135d32fdf84bcd918a4b050f8891b9.
Complete file
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/BridgeEnvironment.kt
- Source · implementation · 78 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
14: class MExtensionServerPlugin internal constructor(
22: private class ProfileBridgeApplication(base: Application) : Application() {
30: override fun getApplicationContext(): Context = this
32: override fun getSharedPreferences(name: String?, mode: Int): SharedPreferences =
51: fun acquireBridgeEnvironment(owner: Any, context: Context, preferencesPrefix: String) {
76: fun releaseBridgeEnvironment(owner: Any) {
Exact file bytes / download · SHA-256 974410aa2061698f79241fb05ed7c8d0b21ee4b590d5cd1bb3cf78dd47f59983.
Complete file
package com.kodjodevf.m_extension_server
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import androidx.preference.PreferenceManager
import eu.kanade.tachiyomi.AppModule
import eu.kanade.tachiyomi.network.NetworkHelper
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
/** Minimal host environment retained by the Mihon compatibility bridge. */
class MExtensionServerPlugin internal constructor(
val applicationContext: Context,
)
/**
* The Application handed to extensions. Every SharedPreferences name (source_<id>, default
* preferences) is prefixed with the owning profile's [preferencesPrefix]; "" keeps legacy names.
*/
private class ProfileBridgeApplication(base: Application) : Application() {
@Volatile
var preferencesPrefix = ""
init {
attachBaseContext(base)
}
override fun getApplicationContext(): Context = this
override fun getSharedPreferences(name: String?, mode: Int): SharedPreferences =
super.getSharedPreferences(name?.let { preferencesPrefix + it }, mode)
}
var instance: MExtensionServerPlugin? = null
private set
var pm: PackageManager? = null
private set
var preferenceManager: PreferenceManager? = null
private set
private var bridgeApplication: ProfileBridgeApplication? = null
private var bridgeOwner: Any? = null
/**
* Claims the process-wide bridge for [owner]. Extensions share one Injekt graph, so only one
* profile may run the bridge at a time; switching profile clears the shared network state.
*/
@Synchronized
fun acquireBridgeEnvironment(owner: Any, context: Context, preferencesPrefix: String) {
check(bridgeOwner == null || bridgeOwner === owner) {
"The Mihon APK bridge is running for another profile; stop it there before starting it here"
}
val app = bridgeApplication ?: run {
val base = context.applicationContext as? Application
?: throw IllegalArgumentException("Android bridge requires an Application context")
ProfileBridgeApplication(base).also { created ->
bridgeApplication = created
instance = MExtensionServerPlugin(created)
pm = created.packageManager
preferenceManager = PreferenceManager(created)
Injekt.importModule(AppModule(created))
}
}
if (app.preferencesPrefix != preferencesPrefix) {
app.preferencesPrefix = preferencesPrefix
val network = Injekt.get<NetworkHelper>()
network.cookieJar.clear()
network.client.cache?.evictAll()
}
bridgeOwner = owner
}
@Synchronized
fun releaseBridgeEnvironment(owner: Any) {
if (bridgeOwner === owner) bridgeOwner = null
}
vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/controller/DalvikHandler.kt
- Source · implementation · 138 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
17: class DalvikHandler {
20: fun serve(session: NanoHTTPD.IHTTPSession): NanoHTTPD.Response {
Exact file bytes / download · SHA-256 f109abb540e55f4888210ef93720b4e0103fad58af89f56886862265cbbbe231.
Complete file
package com.kodjodevf.m_extension_server.server.controller
import m_extension_server.impl.MExtensionServerLoader
import m_extension_server.impl.MihonInvoker
import m_extension_server.model.DataBody
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import eu.kanade.tachiyomi.network.HttpException
import eu.kanade.tachiyomi.animesource.online.AnimeHttpSource
import eu.kanade.tachiyomi.source.online.HttpSource
import fi.iki.elonen.NanoHTTPD
import okhttp3.Cookie
import okhttp3.HttpUrl
import java.io.File
import java.net.URI
class DalvikHandler {
private val objectMapper = ObjectMapper().registerModule(KotlinModule.Builder().build())
fun serve(session: NanoHTTPD.IHTTPSession): NanoHTTPD.Response {
var tempApkFile: File? = null
try {
// Parse JSON body first to get extension data
val body = mutableMapOf<String, String>()
session.parseBody(body)
val json = body["postData"] ?: throw IllegalArgumentException("No JSON body")
// Deserialize DataBody
val dataBody = objectMapper.readValue(json, DataBody::class.java)
// Load extension and select the requested factory child. Multi-source
// APKs (SourceFactory) expose several sources; the bridge context carries
// the upstream Tachiyomi source ID, and the first source stays the
// default for older clients that do not send one.
val loadedExtension = MExtensionServerLoader.loadSourceFromBase64(dataBody.data)
tempApkFile = loadedExtension.tempApkFile;
val selectedSource = MihonInvoker.selectSource(loadedExtension.sources, dataBody)
// Get domain from source
val domain =
selectedSource.let { source ->
try {
val baseUrl = source.javaClass.getMethod("getBaseUrl").invoke(source) as String
URI(baseUrl).host
} catch (e: Exception) {
null
}
} ?: "localhost"
// Intercept Cookie header and save to global cookie jar
val cookies =
(session.headers["cookie"] ?: session.headers["Cookie"])
?.let { cookieHeader ->
cookieHeader.split(";").map { cookieStr ->
val trimmed = cookieStr.trim()
val parts = trimmed.split("=", limit = 2)
val name = parts[0].trim()
val value = parts[1].trim()
Cookie
.Builder()
.name(name)
.value(value)
.domain(domain.removePrefix("."))
.path("/")
.build()
}
}?.toList()
val network =
selectedSource.let { source ->
when (source) {
is HttpSource -> source.network
is AnimeHttpSource -> source.network
else -> null
}
}
if (cookies != null) {
network?.cookieJar?.addAll(
HttpUrl
.Builder()
.scheme("http")
.host(domain.removePrefix("."))
.build(),
cookies,
)
}
val ua = (session.headers["user-agent"] ?: session.headers["User-Agent"])
if (ua != null) {
network?.setUA(ua)
}
// Invoke method
val result = MihonInvoker.invokeMethod(selectedSource, dataBody)
// Serialize response
val responseJson = objectMapper.writeValueAsString(result)
return NanoHTTPD.newFixedLengthResponse(
NanoHTTPD.Response.Status.OK,
"application/json",
responseJson,
)
} catch (e: Exception) {
val status =
when (e) {
is HttpException -> {
when (e.code) {
400 -> NanoHTTPD.Response.Status.BAD_REQUEST
401 -> NanoHTTPD.Response.Status.UNAUTHORIZED
403 -> NanoHTTPD.Response.Status.FORBIDDEN
404 -> NanoHTTPD.Response.Status.NOT_FOUND
429 -> NanoHTTPD.Response.Status.INTERNAL_ERROR
500 -> NanoHTTPD.Response.Status.INTERNAL_ERROR
else -> NanoHTTPD.Response.Status.INTERNAL_ERROR
}
}
else -> NanoHTTPD.Response.Status.INTERNAL_ERROR
}
val errorResponse =
mapOf(
"error" to (e.message ?: "Unknown error"),
"code" to (if (e is HttpException) e.code else 500),
)
val errorJson = objectMapper.writeValueAsString(errorResponse)
return NanoHTTPD.newFixedLengthResponse(
status,
"application/json",
errorJson,
)
}finally {
// Clean up APK file
if (tempApkFile?.exists() ?: false ) {
tempApkFile.delete()
}
}
}
}
vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/controller/MExtensionServerController.kt
- Source · implementation · 41 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: class MExtensionServerController(
11: fun start(port: Int) {
20: fun stop() {
24: fun isRunning(): Boolean = server?.isAlive == true
31: override fun serve(session: IHTTPSession): Response =
Exact file bytes / download · SHA-256 1188513d38660f8723cb15ae6ad2e93f97e3f9d5068191d52a1f96ef57d0e28c.
Complete file
package m_extension_server.controller
import fi.iki.elonen.NanoHTTPD
import com.kodjodevf.m_extension_server.server.controller.DalvikHandler
import java.io.IOException
class MExtensionServerController(
) {
private var server: WebServer? = null
fun start(port: Int) {
try {
server = WebServer(port?:8080)
server?.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false)
} catch (e: IOException) {
throw e
}
}
fun stop() {
server?.stop()
}
fun isRunning(): Boolean = server?.isAlive == true
private inner class WebServer(
port: Int,
// Loopback-only: the bridge executes arbitrary APK code on behalf of the
// caller, so it must never be reachable from other devices on the network.
) : NanoHTTPD("127.0.0.1", port) {
override fun serve(session: IHTTPSession): Response =
when (session.uri) {
"/dalvik" -> DalvikHandler().serve(session)
"/" -> newFixedLengthResponse("MExtensionServer Server Running")
// No /stop route: Yokan owns the controller in-process
// (AndroidExtensionServer.stop()), so an HTTP kill switch is
// unauthenticated attack surface with no caller.
else -> newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found")
}
}
}
vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/impl/MExtensionServerLoader.kt
- Source · implementation · 101 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
21: object MExtensionServerLoader {
30: data class LoadedExtension(
35: fun getSource(
84: fun loadSourceFromBase64(base64Data: String): LoadedExtension {
97: private fun load(file: File): DexClassLoader {
Exact file bytes / download · SHA-256 dc3c0359544fe3955d5f904290fd1867dd4d6e6186728e4e56ecf7475e793a44.
Complete file
package m_extension_server.impl
import android.annotation.SuppressLint
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import dalvik.system.DexClassLoader
import eu.kanade.tachiyomi.animesource.AnimeSource
import eu.kanade.tachiyomi.animesource.AnimeSourceFactory
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.SourceFactory
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.util.Arrays
import java.util.Base64
import java.util.UUID
import kotlin.jvm.optionals.toList
import com.kodjodevf.m_extension_server.pm
object MExtensionServerLoader {
private var pmm: PackageManager? = null
private const val MANGA_PACKAGE = "tachiyomi.extension"
private const val ANIME_PACKAGE = "tachiyomi.animeextension"
private const val METADATA_SOURCE_CLASS_SUFFIX = ".class"
init {
pmm = pm;
}
data class LoadedExtension(
val sources: List<Any>,
val tempApkFile: File,
)
fun getSource(
classLoader: DexClassLoader?,
file: File,
): List<Any>? {
if (pmm == null) {
return emptyList<Any>();
}
val info: PackageInfo? = pmm!!.getPackageArchiveInfo(
file.absolutePath,
PackageManager.GET_CONFIGURATIONS or PackageManager.GET_META_DATA
)
if (info != null && info.applicationInfo != null) {
println(info.applicationInfo!!.metaData.toString())
val metaData = info.applicationInfo!!.metaData
var metaSourceClass = metaData.getString(MANGA_PACKAGE + METADATA_SOURCE_CLASS_SUFFIX)
if (metaSourceClass == null) {
metaSourceClass = metaData.getString(ANIME_PACKAGE + METADATA_SOURCE_CLASS_SUFFIX)
}
if (metaSourceClass == null) {
throw IllegalArgumentException("No source class found in extension metadata")
}
return Arrays.stream<String>(
metaSourceClass.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
)
.map<String?> { s: String? ->
val sourceClass = s!!.trim { it <= ' ' }
if (sourceClass.startsWith(".")) {
return@map info.packageName + sourceClass
}
sourceClass
}.findFirst().map<List<Any>> { sourceClass->
val obj: Any =
Class.forName(sourceClass!!, false, classLoader).getDeclaredConstructor()
.newInstance()
val sources: List<Any> =
when (obj) {
is Source -> listOf(obj)
is SourceFactory -> obj.createSources()
is AnimeSource -> listOf(obj)
is AnimeSourceFactory -> obj.createSources()
else -> throw RuntimeException("Unknown source class type! ${obj.javaClass}")
}
sources;
}.toList().firstOrNull()
}
return emptyList<Any>();
}
@SuppressLint("SuspiciousIndentation")
fun loadSourceFromBase64(base64Data: String): LoadedExtension {
val apkData = Base64.getDecoder().decode(base64Data)
val tempApkFile = File.createTempFile("ext", ".apk")
tempApkFile.setWritable(true)
// Write APK data to temp file
tempApkFile.writeBytes(apkData)
tempApkFile.setReadOnly()
val loader: DexClassLoader = load(tempApkFile)
val sources = getSource(loader,tempApkFile)
return LoadedExtension(sources.orEmpty(),tempApkFile)
}
private fun load(file: File): DexClassLoader {
return DexClassLoader(file.getAbsolutePath(), null, null, this.javaClass.getClassLoader())
}
}
vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/impl/MihonInvoker.kt
- Source · implementation · 792 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
49: object MihonInvoker {
58: fun selectSource(
75: private fun sourceId(source: Any): String? =
82: fun invokeMethod(
115: internal fun invokeGetRelatedAnimeList(source: AnimeSource, animeData: AnimeData?): Map<String, Any> {
128: internal fun invokeGetSeasonList(source: AnimeSource, animeData: AnimeData?): List<JAnime> {
136: private fun invokeHeadersManga(source: CatalogueSource): List<String> =
149: private fun invokeFiltersManga(source: CatalogueSource): FilterList {
154: private fun invokeSupportLatestManga(source: CatalogueSource): Boolean = source.supportsLatest
156: private fun invokeGetPopularManga(
168: private fun invokeGetLatestManga(
180: private fun invokeGetSearchManga(
195: private fun invokeGetDetailsManga(
226: private fun invokeGetChapterList(
257: private fun invokeGetPageList(
290: private fun invokeHeadersAnime(source: AnimeCatalogueSource): List<String> =
303: private fun invokeFiltersAnime(source: AnimeCatalogueSource): AnimeFilterList {
308: private fun invokeSupportLatestAnime(source: AnimeCatalogueSource): Boolean = source.supportsLatest
310: private fun invokeGetPopularAnime(
322: private fun invokeGetLatestAnime(
334: private fun invokeGetSearchAnime(
349: private fun invokeGetDetailsAnime(
380: private fun invokeGetEpisodeList(
411: private fun invokeGetVideoList(
438: private fun invokePreferencesAnime(source: AnimeCatalogueSource): MutableList<Map<String, Any>> {
453: private fun invokePreferencesManga(source: CatalogueSource): MutableList<Map<String, Any>> {
467: private fun processPreferences(
550: private fun applyPreferences(
611: private fun convertFilterList(
701: private fun convertAnimeFilterList(
Exact file bytes / download · SHA-256 e1fe04b683e607117e63904f706e612a7ae8d5a5e31071ccaec5d03b1b2d5e82.
Complete file
package m_extension_server.impl
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import androidx.core.content.edit
import androidx.preference.CheckBoxPreference
import androidx.preference.EditTextPreference
import androidx.preference.ListPreference
import androidx.preference.MultiSelectListPreference
import androidx.preference.PreferenceManager
import androidx.preference.PreferenceScreen
import androidx.preference.SwitchPreferenceCompat
import androidx.preference.size
import m_extension_server.model.AnimeData
import m_extension_server.model.AnimeResponse
import m_extension_server.model.ChapterData
import m_extension_server.model.DataBody
import m_extension_server.model.EpisodeData
import m_extension_server.model.JAnime
import m_extension_server.model.JFilterList
import m_extension_server.model.JManga
import m_extension_server.model.JPage
import m_extension_server.model.MangaData
import m_extension_server.model.MangaResponse
import m_extension_server.model.toJAnime
import m_extension_server.model.toJManga
import eu.kanade.tachiyomi.animesource.AnimeCatalogueSource
import eu.kanade.tachiyomi.animesource.AnimeSource
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilter
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.animesource.online.AnimeHttpSource
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import kotlinx.coroutines.runBlocking
import com.kodjodevf.m_extension_server.MExtensionServerPlugin
import com.kodjodevf.m_extension_server.instance
import com.kodjodevf.m_extension_server.preferenceManager
object MihonInvoker {
private const val BRIDGE_CONTEXT_KEY = "__mangayomi_bridge_context__"
/**
* Selects the factory child requested through the bridge-context preference entry.
* Multi-source APKs (SourceFactory extensions) expose one source per language/site;
* without an explicit ID every call would route to the first child. Requests without
* a bridge context keep the historical first-source behavior.
*/
fun selectSource(
loadedSources: List<Any>,
data: DataBody,
): Any {
if (loadedSources.isEmpty()) {
throw IllegalArgumentException("No source found in extension")
}
val requestedSourceId =
data.preferences
?.firstOrNull { it["key"] == BRIDGE_CONTEXT_KEY }
?.get("sourceId")
?.toString()
?: return loadedSources.first()
return loadedSources.firstOrNull { sourceId(it) == requestedSourceId }
?: throw IllegalArgumentException("Source $requestedSourceId was not found in extension")
}
private fun sourceId(source: Any): String? =
when (source) {
is eu.kanade.tachiyomi.source.Source -> source.id.toString()
is AnimeSource -> source.id.toString()
else -> null
}
fun invokeMethod(
source: Any,
data: DataBody,
): Any {
applyPreferences(data, source)
return when (data.method) {
"headersManga" -> invokeHeadersManga(source as CatalogueSource)
"filtersManga" -> invokeFiltersManga(source as CatalogueSource)
"supportLatestManga" -> invokeSupportLatestManga(source as CatalogueSource)
"getPopularManga" -> invokeGetPopularManga(source as CatalogueSource, data.page ?: 1)
"getLatestManga" -> invokeGetLatestManga(source as CatalogueSource, data.page ?: 1)
"getSearchManga" -> invokeGetSearchManga(source as CatalogueSource, data.page ?: 1, data.search ?: "", data.filterList)
"getDetailsManga" -> invokeGetDetailsManga(source as CatalogueSource, data.mangaData)
"getChapterList" -> invokeGetChapterList(source as CatalogueSource, data.mangaData)
"getPageList" -> invokeGetPageList(source as CatalogueSource, data.chapterData)
"preferencesManga" -> invokePreferencesManga(source as CatalogueSource)
"headersAnime" -> invokeHeadersAnime(source as AnimeCatalogueSource)
"filtersAnime" -> invokeFiltersAnime(source as AnimeCatalogueSource)
"supportLatestAnime" -> invokeSupportLatestAnime(source as AnimeCatalogueSource)
"getPopularAnime" -> invokeGetPopularAnime(source as AnimeCatalogueSource, data.page ?: 1)
"getLatestAnime" -> invokeGetLatestAnime(source as AnimeCatalogueSource, data.page ?: 1)
"getSearchAnime" -> invokeGetSearchAnime(source as AnimeCatalogueSource, data.page ?: 1, data.search ?: "", data.filterList)
"getDetailsAnime" -> invokeGetDetailsAnime(source as AnimeCatalogueSource, data.animeData)
"getRelatedAnimeList" -> invokeGetRelatedAnimeList(source as AnimeSource, data.animeData)
"getSeasonList" -> invokeGetSeasonList(source as AnimeSource, data.animeData)
"getEpisodeList" -> invokeGetEpisodeList(source as AnimeCatalogueSource, data.animeData)
"getVideoList" -> invokeGetVideoList(source as AnimeCatalogueSource, data.episodeData)
"preferencesAnime" -> invokePreferencesAnime(source as AnimeCatalogueSource)
else -> throw IllegalArgumentException("Unknown method: ${data.method}")
}
}
internal fun invokeGetRelatedAnimeList(source: AnimeSource, animeData: AnimeData?): Map<String, Any> {
requireNotNull(animeData) { "animeData is required for getRelatedAnimeList" }
val supported = try { source.supportsRelatedAnime } catch (_: AbstractMethodError) { false }
if (!supported) return mapOf("supported" to false, "groups" to emptyList<Any>())
val anime = SAnime.create().apply { url = animeData.url.orEmpty(); title = animeData.title.orEmpty() }
val relations = runBlocking { source.getRelatedAnimeList(anime) }
require(relations.size <= 50 && relations.sumOf { it.animes.size.toLong() } <= 1_000L) { "Too many related entries" }
return mapOf("supported" to true, "groups" to relations.map { relation ->
mapOf("name" to relation.name, "animes" to relation.animes.map { it.toJAnime() })
})
}
/** Older APKs lack `getSeasonList`; they never report Seasons, and an empty list is the safe answer. */
internal fun invokeGetSeasonList(source: AnimeSource, animeData: AnimeData?): List<JAnime> {
requireNotNull(animeData) { "animeData is required for getSeasonList" }
val anime = SAnime.create().apply { url = animeData.url.orEmpty(); title = animeData.title.orEmpty() }
val seasons = try { runBlocking { source.getSeasonList(anime) } } catch (_: AbstractMethodError) { emptyList() }
require(seasons.size <= 500) { "Too many seasons" }
return seasons.map { it.toJAnime() }
}
private fun invokeHeadersManga(source: CatalogueSource): List<String> =
if (source is HttpSource) {
val headers =
source.headers.toMultimap().flatMap { (name, values) ->
values.flatMap { value ->
listOf(name.replaceFirstChar { it.uppercase() }, value)
}
}
headers
} else {
emptyList()
}
private fun invokeFiltersManga(source: CatalogueSource): FilterList {
val filterList = source.getFilterList()
return filterList
}
private fun invokeSupportLatestManga(source: CatalogueSource): Boolean = source.supportsLatest
private fun invokeGetPopularManga(
source: CatalogueSource,
page: Int,
): MangaResponse =
runBlocking {
val mangasPage = source.getPopularManga(page)
MangaResponse(
mangas = mangasPage.mangas.map { it.toJManga() },
hasNextPage = mangasPage.hasNextPage,
)
}
private fun invokeGetLatestManga(
source: CatalogueSource,
page: Int,
): MangaResponse =
runBlocking {
val mangasPage = source.getLatestUpdates(page)
MangaResponse(
mangas = mangasPage.mangas.map { it.toJManga() },
hasNextPage = mangasPage.hasNextPage,
)
}
private fun invokeGetSearchManga(
source: CatalogueSource,
page: Int,
search: String,
filterList: List<JFilterList>?,
): MangaResponse =
runBlocking {
val convertedFilters = filterList?.let { convertFilterList(source.getFilterList(), it) } ?: source.getFilterList()
val mangasPage = source.getSearchManga(page, search, convertedFilters)
MangaResponse(
mangas = mangasPage.mangas.map { it.toJManga() },
hasNextPage = mangasPage.hasNextPage,
)
}
private fun invokeGetDetailsManga(
source: CatalogueSource,
mangaData: MangaData?,
): JManga {
if (mangaData == null) {
throw IllegalArgumentException("mangaData is required for getDetailsManga")
}
if (source !is HttpSource) {
throw IllegalArgumentException("Source must be HttpSource for getDetailsManga")
}
val sManga =
SManga.create().apply {
url = mangaData.url ?: ""
title = mangaData.title ?: ""
artist = mangaData.artist
author = mangaData.author
description = mangaData.description
genre = mangaData.genre
status = mangaData.status ?: 0
thumbnail_url = mangaData.thumbnail_url
initialized = mangaData.initialized ?: false
}
return runBlocking {
val detailedManga = source.getMangaDetails(sManga)
detailedManga.toJManga()
}
}
private fun invokeGetChapterList(
source: CatalogueSource,
mangaData: MangaData?,
): List<SChapter> {
if (mangaData == null) {
throw IllegalArgumentException("mangaData is required for getChapterList")
}
if (source !is HttpSource) {
throw IllegalArgumentException("Source must be HttpSource for getChapterList")
}
val sManga =
SManga.create().apply {
url = mangaData.url ?: ""
title = mangaData.title ?: ""
artist = mangaData.artist
author = mangaData.author
description = mangaData.description
genre = mangaData.genre
status = mangaData.status ?: 0
thumbnail_url = mangaData.thumbnail_url
initialized = mangaData.initialized ?: false
}
return runBlocking {
val chapters = source.getChapterList(sManga)
chapters
}
}
private fun invokeGetPageList(
source: CatalogueSource,
chapterData: ChapterData?,
): List<JPage> {
if (chapterData == null) {
throw IllegalArgumentException("chapterData is required for getPageList")
}
if (source !is HttpSource) {
throw IllegalArgumentException("Source must be HttpSource for getPageList")
}
val sChapter =
SChapter.create().apply {
url = chapterData.url ?: ""
name = chapterData.name ?: ""
date_upload = chapterData.date_upload ?: 0L
chapter_number = chapterData.chapter_number ?: 0f
scanlator = chapterData.scanlator
}
return runBlocking {
val pages = source.getPageList(sChapter)
pages.map { page ->
JPage(
index = page.index,
url = page.url,
imageUrl = source.imageRequest(page).url.toString(),
)
}
}
}
private fun invokeHeadersAnime(source: AnimeCatalogueSource): List<String> =
if (source is AnimeHttpSource) {
val headers =
source.headers.toMultimap().flatMap { (name, values) ->
values.flatMap { value ->
listOf(name.replaceFirstChar { it.uppercase() }, value)
}
}
headers
} else {
emptyList()
}
private fun invokeFiltersAnime(source: AnimeCatalogueSource): AnimeFilterList {
val filterList = source.getFilterList()
return filterList
}
private fun invokeSupportLatestAnime(source: AnimeCatalogueSource): Boolean = source.supportsLatest
private fun invokeGetPopularAnime(
source: AnimeCatalogueSource,
page: Int,
): AnimeResponse =
runBlocking {
val animesPage = source.getPopularAnime(page)
AnimeResponse(
animes = animesPage.animes.map { it.toJAnime() },
hasNextPage = animesPage.hasNextPage,
)
}
private fun invokeGetLatestAnime(
source: AnimeCatalogueSource,
page: Int,
): AnimeResponse =
runBlocking {
val animesPage = source.getLatestUpdates(page)
AnimeResponse(
animes = animesPage.animes.map { it.toJAnime() },
hasNextPage = animesPage.hasNextPage,
)
}
private fun invokeGetSearchAnime(
source: AnimeCatalogueSource,
page: Int,
search: String,
filterList: List<JFilterList>?,
): AnimeResponse =
runBlocking {
val convertedFilters = filterList?.let { convertAnimeFilterList(source.getFilterList(), it) } ?: source.getFilterList()
val animePage = source.getSearchAnime(page, search, convertedFilters)
AnimeResponse(
animes = animePage.animes.map { it.toJAnime() },
hasNextPage = animePage.hasNextPage,
)
}
private fun invokeGetDetailsAnime(
source: AnimeCatalogueSource,
animeData: AnimeData?,
): JAnime {
if (animeData == null) {
throw IllegalArgumentException("animeData is required for getDetailsAnime")
}
if (source !is AnimeHttpSource) {
throw IllegalArgumentException("Source must be AnimeHttpSource for getDetailsAnime")
}
val sAnime =
SAnime.create().apply {
url = animeData.url ?: ""
title = animeData.title ?: ""
artist = animeData.artist
author = animeData.author
description = animeData.description
genre = animeData.genre
status = animeData.status ?: 0
thumbnail_url = animeData.thumbnail_url
initialized = animeData.initialized ?: false
}
return runBlocking {
val detailedAnime = source.getAnimeDetails(sAnime)
detailedAnime.toJAnime()
}
}
private fun invokeGetEpisodeList(
source: AnimeCatalogueSource,
animeData: AnimeData?,
): List<SEpisode> {
if (animeData == null) {
throw IllegalArgumentException("animeData is required for getEpisodeList")
}
if (source !is AnimeHttpSource) {
throw IllegalArgumentException("Source must be AnimeHttpSource for getEpisodeList")
}
val sAnime =
SAnime.create().apply {
url = animeData.url ?: ""
title = animeData.title ?: ""
artist = animeData.artist
author = animeData.author
description = animeData.description
genre = animeData.genre
status = animeData.status ?: 0
thumbnail_url = animeData.thumbnail_url
initialized = animeData.initialized ?: false
}
return runBlocking {
val episodes = source.getEpisodeList(sAnime)
episodes
}
}
private fun invokeGetVideoList(
source: AnimeCatalogueSource,
episodeData: EpisodeData?,
): List<Video> {
if (episodeData == null) {
throw IllegalArgumentException("episodeData is required for getVideoList")
}
if (source !is AnimeHttpSource) {
throw IllegalArgumentException("Source must be AnimeHttpSource for getVideoList")
}
val sEpisode =
SEpisode.create().apply {
url = episodeData.url ?: ""
name = episodeData.name ?: ""
date_upload = episodeData.date_upload ?: 0L
episode_number = episodeData.episode_number ?: 0f
scanlator = episodeData.scanlator
}
return runBlocking {
val videos = source.getVideoList(sEpisode)
videos
}
}
private fun invokePreferencesAnime(source: AnimeCatalogueSource): MutableList<Map<String, Any>> {
val preferences = mutableListOf<Map<String, Any>>()
if (source !is ConfigurableAnimeSource) {
return preferences
}
val preferenceManager: PreferenceManager? = preferenceManager
val instance: MExtensionServerPlugin? = instance
val screen = preferenceManager!!.createPreferenceScreen(instance!!.applicationContext!!)
(source as ConfigurableSource).setupPreferenceScreen(screen)
processPreferences(screen, preferences)
return preferences
}
private fun invokePreferencesManga(source: CatalogueSource): MutableList<Map<String, Any>> {
val preferences = mutableListOf<Map<String, Any>>()
if (source !is ConfigurableSource) {
return preferences
}
val preferenceManager: PreferenceManager? = preferenceManager
val instance: MExtensionServerPlugin? = instance
val screen = preferenceManager!!.createPreferenceScreen(instance!!.applicationContext!!)
(source as ConfigurableSource).setupPreferenceScreen(screen)
processPreferences(screen, preferences)
return preferences
}
private fun processPreferences(
screen: PreferenceScreen,
preferences: MutableList<Map<String, Any>>,
) {
for (i in 0 until screen.size) {
val preference = screen.getPreference(i)
when (preference) {
is CheckBoxPreference -> {
preferences.add(
mapOf(
"key" to preference.key,
"checkBoxPreference" to
mapOf(
"title" to preference.title,
"summary" to (preference.summary ?: ""),
"value" to preference.isChecked,
),
),
)
}
is SwitchPreferenceCompat -> {
preferences.add(
mapOf(
"key" to preference.key,
"switchPreferenceCompat" to
mapOf(
"title" to preference.title,
"summary" to (preference.summary ?: ""),
"value" to preference.isChecked,
),
),
)
}
is EditTextPreference -> {
preferences.add(
mapOf(
"key" to preference.key,
"editTextPreference" to
mapOf(
"title" to preference.title,
"summary" to (preference.summary ?: ""),
"value" to preference.text,
"text" to preference.text,
"dialogMessage" to preference.getDialogMessage(),
"dialogTitle" to preference.getDialogTitle(),
),
),
)
}
is ListPreference -> {
preferences.add(
mapOf(
"key" to preference.key,
"listPreference" to
mapOf(
"title" to preference.title,
"summary" to (preference.summary ?: ""),
"valueIndex" to preference.entryValues.indexOf(preference.value),
"entries" to preference.entries,
"entryValues" to preference.entryValues,
),
),
)
}
is MultiSelectListPreference -> {
preferences.add(
mapOf(
"key" to preference.key,
"multiSelectListPreference" to
mapOf(
"title" to preference.title,
"summary" to (preference.summary ?: ""),
"values" to preference.values,
"entries" to preference.entries,
"entryValues" to preference.entryValues,
),
),
)
}
}
}
}
private fun applyPreferences(
data: DataBody,
source: Any,
) {
val preferences = data.preferences ?: return
val sourceId =
when (source) {
is CatalogueSource -> source.id
is AnimeSource -> source.id
else -> throw IllegalArgumentException("Unknown source type: ${source.javaClass}")
}
val context: Context = instance!!.applicationContext!!
val prefs = context.getSharedPreferences("source_$sourceId", 0x0000)
prefs.edit {
for (prefMap in preferences) {
val key = prefMap["key"] as? String ?: continue
when {
prefMap.containsKey("checkBoxPreference") -> {
val checkBox = prefMap["checkBoxPreference"] as? Map<*, *>
val value = checkBox?.get("value") as? Boolean
if (value != null) {
putBoolean(key, value)
}
}
prefMap.containsKey("switchPreferenceCompat") -> {
val switch = prefMap["switchPreferenceCompat"] as? Map<*, *>
val value = switch?.get("value") as? Boolean
if (value != null) {
putBoolean(key, value)
}
}
prefMap.containsKey("editTextPreference") -> {
val editText = prefMap["editTextPreference"] as? Map<*, *>
val value = editText?.get("value") as? String
if (value != null) {
putString(key, value)
}
}
prefMap.containsKey("listPreference") -> {
val list = prefMap["listPreference"] as? Map<*, *>
val valueIndex = list?.get("valueIndex") as? Int
val entryValues = list?.get("entryValues") as? List<String>
if (valueIndex != null && entryValues != null && valueIndex in entryValues.indices) {
putString(key, entryValues[valueIndex])
}
}
prefMap.containsKey("multiSelectListPreference") -> {
val multiList = prefMap["multiSelectListPreference"] as? Map<*, *>
val values = multiList?.get("values") as? List<String>
if (values != null) {
putStringSet(key, values.toSet())
}
}
}
}
}
}
private fun convertFilterList(
originalFilters: FilterList,
jFilters: List<JFilterList>,
): FilterList {
// Apply the filter values from jFilters to the original filters
val convertedFilters =
originalFilters.map { filter ->
when (filter) {
is Filter.Select<*> -> {
val jFilter = jFilters.find { it.name == filter.name }
if (jFilter != null) {
val state = jFilter.stateInt
if (state != null) {
filter.state = state
}
}
filter
}
is Filter.CheckBox -> {
val jFilter = jFilters.find { it.name == filter.name }
if (jFilter != null &&
jFilter.stateList != null &&
jFilter.stateList.isNotEmpty() &&
jFilter.stateList[0].stateBoolean is Boolean
) {
filter.state = jFilter.stateList[0].stateBoolean as Boolean
}
filter
}
is Filter.TriState -> {
val jFilter = jFilters.find { it.name == filter.name }
if (jFilter != null && jFilter.stateInt is Int) {
filter.state = jFilter.stateInt
}
filter
}
is Filter.Text -> {
val jFilter = jFilters.find { it.name == filter.name }
if (jFilter != null && jFilter.stateString is String) {
filter.state = jFilter.stateString
}
filter
}
is Filter.Group<*> -> {
val groupFilter = filter as Filter.Group<Filter<*>>
val jGroup = jFilters.find { it.name == groupFilter.name }
if (jGroup != null) {
val subJFilters = jGroup.stateList
for (state in groupFilter.state) {
val jSubFilter = subJFilters?.find { it.name == state.name }
val dataGroup = jSubFilter
if (dataGroup == null) {
continue
}
if (state is Filter.CheckBox) {
val checkBox = state
checkBox.state = dataGroup.stateBoolean ?: false
}
if (state is Filter.TriState) {
val checkBox = state
checkBox.state = dataGroup.stateInt ?: 0
}
if (state is Filter.Select<*>) {
val select = state
select.state = dataGroup.stateInt ?: 0
}
if (state is Filter.Text) {
val text = state
text.state = dataGroup.name ?: ""
}
}
}
filter
}
is Filter.Sort -> {
val jSort = jFilters.find { it.name == filter.name }
if (jSort != null) {
val dataSort = jSort.stateSort
if (dataSort != null && dataSort.index != null && dataSort.ascending != null) {
filter.state = Filter.Sort.Selection(dataSort.index, dataSort.ascending)
}
}
filter
}
else -> filter
}
}
return FilterList(convertedFilters)
}
private fun convertAnimeFilterList(
originalFilters: AnimeFilterList,
jFilters: List<JFilterList>,
): AnimeFilterList {
// Apply the filter values from jFilters to the original filters
val convertedFilters =
originalFilters.map { filter ->
when (filter) {
is AnimeFilter.Select<*> -> {
val jFilter = jFilters.find { it.name == filter.name }
if (jFilter != null) {
val state = jFilter.stateInt as? Int
if (state != null) {
filter.state = state
}
}
filter
}
is AnimeFilter.CheckBox -> {
val jFilter = jFilters.find { it.name == filter.name }
if (jFilter != null &&
jFilter.stateList != null &&
jFilter.stateList.isNotEmpty() &&
jFilter.stateList[0].stateBoolean is Boolean
) {
filter.state = jFilter.stateList[0].stateBoolean as Boolean
}
filter
}
is AnimeFilter.TriState -> {
val jFilter = jFilters.find { it.name == filter.name }
if (jFilter != null && jFilter.stateInt is Int) {
filter.state = jFilter.stateInt as Int
}
filter
}
is AnimeFilter.Text -> {
val jFilter = jFilters.find { it.name == filter.name }
if (jFilter != null && jFilter.stateString is String) {
filter.state = jFilter.stateString
}
filter
}
is AnimeFilter.Group<*> -> {
val groupFilter = filter as AnimeFilter.Group<AnimeFilter<*>>
val jGroup = jFilters.find { it.name == groupFilter.name }
if (jGroup != null) {
val subJFilters = jGroup.stateList
for (state in groupFilter.state) {
val jSubFilter = subJFilters?.find { it.name == state.name }
val dataGroup = jSubFilter
if (dataGroup == null) {
continue
}
if (state is AnimeFilter.CheckBox) {
val checkBox = state
checkBox.state = dataGroup.stateBoolean ?: false
}
if (state is AnimeFilter.TriState) {
val checkBox = state
checkBox.state = dataGroup.stateInt ?: 0
}
if (state is AnimeFilter.Select<*>) {
val select = state
select.state = dataGroup.stateInt ?: 0
}
if (state is AnimeFilter.Text) {
val text = state
text.state = dataGroup.name ?: ""
}
}
}
filter
}
is AnimeFilter.Sort -> {
val jSort = jFilters.find { it.name == filter.name }
if (jSort != null) {
val dataSort = jSort.stateSort
if (dataSort != null && dataSort.index != null && dataSort.ascending != null) {
filter.state =
AnimeFilter.Sort
.Selection(dataSort.index, dataSort.ascending)
}
}
filter
}
else -> filter
}
}
return AnimeFilterList(convertedFilters)
}
}
vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/model/DataBody.kt
- Source · implementation · 75 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: data class DataBody(
16: data class MangaData(
28: data class ChapterData(
36: data class AnimeData(
48: data class EpisodeData(
56: data class JFilterList(
65: data class JGroupFilter(
72: data class JSortFilter(
Exact file bytes / download · SHA-256 27b9a5eca40b1a5773a58f66aedbb0a4dbf0f395967d22a89bc35f8359fe8d84.
Complete file
package m_extension_server.model
data class DataBody(
val data: String, // Base64 encoded APK data
val method: String,
val page: Int? = null,
val search: String? = null,
val filterList: List<JFilterList>? = null,
val mangaData: MangaData? = null,
val chapterData: ChapterData? = null,
val animeData: AnimeData? = null,
val episodeData: EpisodeData? = null,
val preferences: MutableList<Map<String, Any>>? = null,
)
data class MangaData(
val url: String?,
val title: String?,
val artist: String?,
val author: String?,
val description: String?,
val genre: String?,
val status: Int?,
val thumbnail_url: String?,
val initialized: Boolean?,
)
data class ChapterData(
val url: String?,
val name: String?,
val date_upload: Long?,
val chapter_number: Float?,
val scanlator: String?,
)
data class AnimeData(
val url: String?,
val title: String?,
val artist: String?,
val author: String?,
val description: String?,
val genre: String?,
val status: Int?,
val thumbnail_url: String?,
val initialized: Boolean?,
)
data class EpisodeData(
val url: String?,
val name: String?,
val date_upload: Long?,
val episode_number: Float?,
val scanlator: String?,
)
data class JFilterList(
val name: String?,
val type: String?,
val stateString: String?,
val stateInt: Int?,
val stateList: List<JGroupFilter>?,
val stateSort: JSortFilter?,
)
data class JGroupFilter(
val name: String?,
val type: String?,
val stateBoolean: Boolean?,
val stateInt: Int?,
)
data class JSortFilter(
val ascending: Boolean?,
val index: Int?,
)
vendor/yokan-ext/src/androidMain/kotlin/com/kodjodevf/m_extension_server/server/model/ResponseModels.kt
- Source · implementation · 137 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: data class MangaResponse(
17: data class AnimeResponse(
22: data class PageResponse(
26: data class FiltersResponse(
30: data class AnimeFiltersResponse(
34: data class PreferencesResponse(
38: data class JManga(
50: data class JAnime(
65: data class JChapter(
73: data class JEpisode(
81: data class JPage(
87: data class JPreference(
92: fun SManga.toJManga(): JManga =
105: fun SChapter.toJChapter(): JChapter =
114: fun SAnime.toJAnime(): JAnime =
130: fun SEpisode.toJEpisode(): JEpisode =
Exact file bytes / download · SHA-256 1b9493a5c3f1fa5283bcf1ef7e2e1142be4501145fd47ad67643a0f7cc220df1.
Complete file
package m_extension_server.model
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.Credit
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
// Response models matching MExtensionServer format
data class MangaResponse(
val mangas: List<JManga>? = null,
val hasNextPage: Boolean? = null,
)
data class AnimeResponse(
val animes: List<JAnime>? = null,
val hasNextPage: Boolean? = null,
)
data class PageResponse(
val pageList: List<JPage>? = null,
)
data class FiltersResponse(
val filterList: FilterList? = null,
)
data class AnimeFiltersResponse(
val filterList: AnimeFilterList? = null,
)
data class PreferencesResponse(
val preferences: List<JPreference>? = null,
)
data class JManga(
val url: String,
val title: String,
val artist: String?,
val author: String?,
val description: String?,
val genre: String?,
val status: Int,
val thumbnail_url: String?,
val initialized: Boolean,
)
data class JAnime(
val url: String,
val title: String,
val artist: String?,
val author: String?,
val description: String?,
val genre: String?,
val status: Int,
val thumbnail_url: String?,
val initialized: Boolean,
val cast: List<Credit>? = null,
val fetch_type: String = "Episodes",
val season_number: Double = -1.0,
)
data class JChapter(
val url: String,
val name: String,
val date_upload: Long,
val chapter_number: Float,
val scanlator: String?,
)
data class JEpisode(
val url: String,
val name: String,
val date_upload: Long,
val episode_number: Float,
val scanlator: String?,
)
data class JPage(
val index: Int,
val url: String,
val imageUrl: String?,
)
data class JPreference(
val type: String,
val props: Map<String, Any>,
)
fun SManga.toJManga(): JManga =
JManga(
url = runCatching { this.url }.getOrDefault(""),
title = runCatching { this.title }.getOrDefault(""),
artist = runCatching { this.artist }.getOrNull(),
author = runCatching { this.author }.getOrNull(),
description = runCatching { this.description }.getOrNull(),
genre = runCatching { this.genre }.getOrNull(),
status = runCatching { this.status }.getOrDefault(0),
thumbnail_url = runCatching { this.thumbnail_url }.getOrNull(),
initialized = runCatching { this.initialized }.getOrDefault(false),
)
fun SChapter.toJChapter(): JChapter =
JChapter(
url = runCatching { this.url }.getOrDefault(""),
name = runCatching { this.name }.getOrDefault(""),
date_upload = runCatching { this.date_upload }.getOrDefault(0L),
chapter_number = runCatching { this.chapter_number }.getOrDefault(0f),
scanlator = runCatching { this.scanlator }.getOrNull(),
)
fun SAnime.toJAnime(): JAnime =
JAnime(
url = runCatching { this.url }.getOrDefault(""),
title = runCatching { this.title }.getOrDefault(""),
artist = runCatching { this.artist }.getOrNull(),
author = runCatching { this.author }.getOrNull(),
description = runCatching { this.description }.getOrNull(),
genre = runCatching { this.genre }.getOrNull(),
status = runCatching { this.status }.getOrDefault(0),
thumbnail_url = runCatching { this.thumbnail_url }.getOrNull(),
initialized = runCatching { this.initialized }.getOrDefault(false),
cast = try { this.cast } catch (_: AbstractMethodError) { null },
fetch_type = try { this.fetch_type.name } catch (_: AbstractMethodError) { "Episodes" },
season_number = try { this.season_number } catch (_: AbstractMethodError) { -1.0 },
)
fun SEpisode.toJEpisode(): JEpisode =
JEpisode(
url = runCatching { this.url }.getOrDefault(""),
name = runCatching { this.name }.getOrDefault(""),
date_upload = runCatching { this.date_upload }.getOrDefault(0L),
episode_number = runCatching { this.episode_number }.getOrDefault(0f),
scanlator = runCatching { this.scanlator }.getOrNull(),
)
vendor/yokan-ext/src/androidMain/kotlin/eu/friedcutlet/yokan/ext/AndroidExtensionServer.kt
- Source · implementation · 59 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
15: class AndroidExtensionServer(
27: override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock {
47: override suspend fun stop(): ExtensionServerStatus = lock.withLock { stopLocked() }
49: private suspend fun stopLocked(): ExtensionServerStatus {
Exact file bytes / download · SHA-256 5f3afdc26ee08050f0d43c7701fdb674006481c4bf0d4b9e5e57865c4c7dd03a.
Complete file
package eu.friedcutlet.yokan.ext
import android.content.Context
import com.kodjodevf.m_extension_server.acquireBridgeEnvironment
import com.kodjodevf.m_extension_server.releaseBridgeEnvironment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import m_extension_server.controller.MExtensionServerController
/** [preferencesPrefix] namespaces the extensions' SharedPreferences; "" keeps the legacy names. */
class AndroidExtensionServer(
context: Context,
private val preferencesPrefix: String = "",
) : ExtensionServer {
private val appContext = context.applicationContext
private val lock = Mutex()
private val mutableStatus = MutableStateFlow(ExtensionServerStatus.Stopped)
private var controller: MExtensionServerController? = null
private var activeConfig: ExtensionServerConfig? = null
override val status: StateFlow<ExtensionServerStatus> = mutableStatus
override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock {
if (controller?.isRunning() == true && activeConfig == config) return mutableStatus.value
stopLocked()
mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Starting, config.port, "Starting Android APK bridge")
try {
acquireBridgeEnvironment(this, appContext, preferencesPrefix)
val created = MExtensionServerController()
withContext(Dispatchers.IO) { created.start(config.port) }
controller = created
activeConfig = config
ExtensionServerStatus(ExtensionServerPhase.Running, config.port, "APK bridge started on port ${config.port}")
.also { mutableStatus.value = it }
} catch (error: Throwable) {
releaseBridgeEnvironment(this)
val message = "Failed to start Android APK bridge: ${error.message.orEmpty()}"
mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Failed, config.port, message)
throw ExtensionServerException("START_ERROR", message, error)
}
}
override suspend fun stop(): ExtensionServerStatus = lock.withLock { stopLocked() }
private suspend fun stopLocked(): ExtensionServerStatus {
val current = controller
if (current == null) return ExtensionServerStatus.Stopped.also { mutableStatus.value = it }
mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Stopping, activeConfig?.port, "Stopping Android APK bridge")
withContext(Dispatchers.IO) { current.stop() }
controller = null
activeConfig = null
releaseBridgeEnvironment(this)
return ExtensionServerStatus.Stopped.copy(message = "APK bridge stopped").also { mutableStatus.value = it }
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/App.kt
- Source · implementation · 19 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
9: open class App : Application() {
10: override fun onCreate() {
16: override fun attachBaseContext(base: Context) {
Exact file bytes / download · SHA-256 37ec659214f671fd6d5600564e2f89a63b4c79ef8d3bf1799d5d39a54bfd326e.
Complete file
package eu.kanade.tachiyomi
import android.app.Application
import android.content.Context
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.InjektScope
import uy.kohesive.injekt.registry.default.DefaultRegistrar
open class App : Application() {
override fun onCreate() {
super.onCreate()
Injekt = InjektScope(DefaultRegistrar())
Injekt.importModule(AppModule(this))
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/AppInfo.kt
- Source · implementation · 14 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: object AppInfo {
11: fun getVersionCode() = BuildConfig.VERSION_CODE
13: fun getVersionName() = BuildConfig.VERSION_NAME
Exact file bytes / download · SHA-256 bd6e0448a08e6ca04e0eb9afa660dd3bbf7fbc2d2b5ca728f8efc1c1b0ba73f8.
Complete file
package eu.kanade.tachiyomi
import rx.android.BuildConfig
/**
* Used by extensions.
*
* @since extension-lib 1.3
*/
object AppInfo {
fun getVersionCode() = BuildConfig.VERSION_CODE
fun getVersionName() = BuildConfig.VERSION_NAME
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/AppModule.kt
- Source · implementation · 21 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: class AppModule(
14: override fun InjektRegistrar.registerInjectables() {
Exact file bytes / download · SHA-256 226e4bbedb7defa44165b597a6d10879e8b175e6fd3f51e3aac9cfbafc0e8429.
Complete file
package eu.kanade.tachiyomi
import android.app.Application
import eu.kanade.tachiyomi.network.NetworkHelper
import kotlinx.serialization.json.Json
import uy.kohesive.injekt.api.InjektModule
import uy.kohesive.injekt.api.InjektRegistrar
import uy.kohesive.injekt.api.addSingleton
import uy.kohesive.injekt.api.addSingletonFactory
class AppModule(
val app: Application,
) : InjektModule {
override fun InjektRegistrar.registerInjectables() {
addSingleton(app)
addSingletonFactory { NetworkHelper(app) }
addSingletonFactory { Json { ignoreUnknownKeys = true } }
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeCatalogueSource.kt
- Source · implementation · 81 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: interface AnimeCatalogueSource : AnimeSource {
26: suspend fun getPopularAnime(page: Int): AnimesPage = fetchPopularAnime(page).awaitSingle()
37: suspend fun getSearchAnime(
50: suspend fun getLatestUpdates(page: Int): AnimesPage = fetchLatestUpdates(page).awaitSingle()
55: fun getFilterList(): AnimeFilterList
62: fun fetchPopularAnime(page: Int): Observable<AnimesPage>
69: fun fetchSearchAnime(
80: fun fetchLatestUpdates(page: Int): Observable<AnimesPage>
Exact file bytes / download · SHA-256 ea19341b7ffc4b104485164c455ebb1917f23485fb3760ee0a796a487c83d2ed.
Complete file
package eu.kanade.tachiyomi.animesource
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.AnimesPage
import eu.kanade.tachiyomi.util.lang.awaitSingle
import rx.Observable
interface AnimeCatalogueSource : AnimeSource {
/**
* An ISO 639-1 compliant language code (two letters in lower case).
*/
override val lang: String
/**
* Whether the source has support for latest updates.
*/
val supportsLatest: Boolean
/**
* Get a page with a list of anime.
*
* @since extensions-lib 1.5
* @param page the page number to retrieve.
*/
@Suppress("DEPRECATION")
suspend fun getPopularAnime(page: Int): AnimesPage = fetchPopularAnime(page).awaitSingle()
/**
* Get a page with a list of anime.
*
* @since extensions-lib 1.5
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
@Suppress("DEPRECATION")
suspend fun getSearchAnime(
page: Int,
query: String,
filters: AnimeFilterList,
): AnimesPage = fetchSearchAnime(page, query, filters).awaitSingle()
/**
* Get a page with a list of latest anime updates.
*
* @since extensions-lib 1.5
* @param page the page number to retrieve.
*/
@Suppress("DEPRECATION")
suspend fun getLatestUpdates(page: Int): AnimesPage = fetchLatestUpdates(page).awaitSingle()
/**
* Returns the list of filters for the source.
*/
fun getFilterList(): AnimeFilterList
// Should be replaced as soon as Anime Extension reach 1.5
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getPopularAnime"),
)
fun fetchPopularAnime(page: Int): Observable<AnimesPage>
// Should be replaced as soon as Anime Extension reach 1.5
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getSearchAnime"),
)
fun fetchSearchAnime(
page: Int,
query: String,
filters: AnimeFilterList,
): Observable<AnimesPage>
// Should be replaced as soon as Anime Extension reach 1.5
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getLatestUpdates"),
)
fun fetchLatestUpdates(page: Int): Observable<AnimesPage>
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeSource.kt
- Source · implementation · 87 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: interface AnimeSource {
30: suspend fun getRelatedAnimeList(anime: SAnime): List<AnimeRelation> = emptyList()
37: suspend fun getSeasonList(anime: SAnime): List<SAnime> = emptyList()
47: suspend fun getAnimeDetails(anime: SAnime): SAnime = fetchAnimeDetails(anime).awaitSingle()
57: suspend fun getEpisodeList(anime: SAnime): List<SEpisode> = fetchEpisodeList(anime).awaitSingle()
68: suspend fun getVideoList(episode: SEpisode): List<Video> = fetchVideoList(episode).awaitSingle()
74: fun fetchAnimeDetails(anime: SAnime): Observable<SAnime> = throw IllegalStateException("Not used")
80: fun fetchEpisodeList(anime: SAnime): Observable<List<SEpisode>> = throw IllegalStateException("Not used")
86: fun fetchVideoList(episode: SEpisode): Observable<List<Video>> = throw IllegalStateException("Not used")
Exact file bytes / download · SHA-256 9c29e6852eedf29136130b7af24853d89e3c219664910ebfb7eeec32c11bf466.
Complete file
package eu.kanade.tachiyomi.animesource
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.AnimeRelation
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.util.lang.awaitSingle
import rx.Observable
/**
* A basic interface for creating a source. It could be an online source, a local source, etc.
*/
interface AnimeSource {
/**
* ID for the source. Must be unique.
*/
val id: Long
/**
* Name of the source.
*/
val name: String
val lang: String
get() = ""
val supportsRelatedAnime: Boolean
get() = false
suspend fun getRelatedAnimeList(anime: SAnime): List<AnimeRelation> = emptyList()
/**
* Seasons of a [eu.kanade.tachiyomi.animesource.model.FetchType.Seasons] anime; each is its own anime.
*
* @since extensions-lib 16
*/
suspend fun getSeasonList(anime: SAnime): List<SAnime> = emptyList()
/**
* Get the updated details for a anime.
*
* @since extensions-lib 1.5
* @param anime the anime to update.
* @return the updated anime.
*/
@Suppress("DEPRECATION")
suspend fun getAnimeDetails(anime: SAnime): SAnime = fetchAnimeDetails(anime).awaitSingle()
/**
* Get all the available episodes for a anime.
*
* @since extensions-lib 1.5
* @param anime the anime to update.
* @return the episodes for the anime.
*/
@Suppress("DEPRECATION")
suspend fun getEpisodeList(anime: SAnime): List<SEpisode> = fetchEpisodeList(anime).awaitSingle()
/**
* Get the list of videos a episode has. Pages should be returned
* in the expected order; the index is ignored.
*
* @since extensions-lib 1.5
* @param episode the episode.
* @return the videos for the episode.
*/
@Suppress("DEPRECATION")
suspend fun getVideoList(episode: SEpisode): List<Video> = fetchVideoList(episode).awaitSingle()
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getAnimeDetails"),
)
fun fetchAnimeDetails(anime: SAnime): Observable<SAnime> = throw IllegalStateException("Not used")
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getEpisodeList"),
)
fun fetchEpisodeList(anime: SAnime): Observable<List<SEpisode>> = throw IllegalStateException("Not used")
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getVideoList"),
)
fun fetchVideoList(episode: SEpisode): Observable<List<Video>> = throw IllegalStateException("Not used")
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/AnimeSourceFactory.kt
- Source · implementation · 12 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: interface AnimeSourceFactory {
11: fun createSources(): List<AnimeSource>
Exact file bytes / download · SHA-256 650fad9f153e9656d704a6d2d738072776f47959f7bcd879344d5bc6f7c35dee.
Complete file
package eu.kanade.tachiyomi.animesource
/**
* A factory for creating sources at runtime.
*/
interface AnimeSourceFactory {
/**
* Create a new copy of the sources
* @return The created sources
*/
fun createSources(): List<AnimeSource>
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/ConfigurableAnimeSource.kt
- Source · implementation · 21 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: interface ConfigurableAnimeSource : AnimeSource {
16: fun getSourcePreferences(): SharedPreferences = Injekt.get<Application>().getSharedPreferences(preferenceKey(), Context.MODE_PRIVATE)
18: fun setupPreferenceScreen(screen: PreferenceScreen)
21: private fun ConfigurableAnimeSource.preferenceKey(): String = "source_$id"
Exact file bytes / download · SHA-256 9cd490b20560d00f858adedfeea94a267c01f0040076476e5b5e8aa1f2cb85e6.
Complete file
package eu.kanade.tachiyomi.animesource
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import androidx.preference.PreferenceScreen
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
interface ConfigurableAnimeSource : AnimeSource {
/**
* Gets instance of [SharedPreferences] scoped to the specific source.
*
* @since extensions-lib 14
*/
fun getSourcePreferences(): SharedPreferences = Injekt.get<Application>().getSharedPreferences(preferenceKey(), Context.MODE_PRIVATE)
fun setupPreferenceScreen(screen: PreferenceScreen)
}
private fun ConfigurableAnimeSource.preferenceKey(): String = "source_$id"
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/UnmeteredSource.kt
- Source · implementation · 8 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: interface UnmeteredSource
Exact file bytes / download · SHA-256 3d871e249f779ae9eeeaca1f5e12718208810f385dd4bd49c7f24618adf89b10.
Complete file
package eu.kanade.tachiyomi.animesource
/**
* A source that explicitly doesn't require traffic considerations.
*
* This typically applies for self-hosted sources.
*/
interface UnmeteredSource
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeFilter.kt
- Source · implementation · 77 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
4: sealed class AnimeFilter<T>(
8: open class Header(
12: open class Separator(
16: abstract class Select<V>(
22: abstract class Text(
27: abstract class CheckBox(
32: abstract class TriState(
36: fun isIgnored() = state == STATE_IGNORE
38: fun isIncluded() = state == STATE_INCLUDE
40: fun isExcluded() = state == STATE_EXCLUDE
49: abstract class Group<V>(
54: abstract class Sort(
59: data class Selection(
65: override fun equals(other: Any?): Boolean {
72: override fun hashCode(): Int {
Exact file bytes / download · SHA-256 1277354a6025051a6b362bd86ce15fa1054e96341d58607ea79f88dc70b71bd7.
Complete file
package eu.kanade.tachiyomi.animesource.model
@Suppress("UnnecessaryAbstractClass")
sealed class AnimeFilter<T>(
val name: String,
var state: T,
) {
open class Header(
name: String,
) : AnimeFilter<Any>(name, 0)
open class Separator(
name: String = "",
) : AnimeFilter<Any>(name, 0)
abstract class Select<V>(
name: String,
val values: Array<V>,
state: Int = 0,
) : AnimeFilter<Int>(name, state)
abstract class Text(
name: String,
state: String = "",
) : AnimeFilter<String>(name, state)
abstract class CheckBox(
name: String,
state: Boolean = false,
) : AnimeFilter<Boolean>(name, state)
abstract class TriState(
name: String,
state: Int = STATE_IGNORE,
) : AnimeFilter<Int>(name, state) {
fun isIgnored() = state == STATE_IGNORE
fun isIncluded() = state == STATE_INCLUDE
fun isExcluded() = state == STATE_EXCLUDE
companion object {
const val STATE_IGNORE = 0
const val STATE_INCLUDE = 1
const val STATE_EXCLUDE = 2
}
}
abstract class Group<V>(
name: String,
state: List<V>,
) : AnimeFilter<List<V>>(name, state)
abstract class Sort(
name: String,
val values: Array<String>,
state: Selection? = null,
) : AnimeFilter<Sort.Selection?>(name, state) {
data class Selection(
val index: Int,
val ascending: Boolean,
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AnimeFilter<*>) return false
return name == other.name && state == other.state
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + (state?.hashCode() ?: 0)
return result
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeFilterList.kt
- Source · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: data class AnimeFilterList(
Exact file bytes / download · SHA-256 e5dec43bdb1e055810d22b721d23a987b31d6ec9f15caed577d92ac35e412169.
Complete file
package eu.kanade.tachiyomi.animesource.model
data class AnimeFilterList(
val list: List<AnimeFilter<*>>,
) : List<AnimeFilter<*>> by list {
constructor(vararg fs: AnimeFilter<*>) : this(if (fs.isNotEmpty()) fs.asList() else emptyList())
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeRelation.kt
- Source · implementation · 3 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: data class AnimeRelation(val name: String, val animes: List<SAnime>)
Exact file bytes / download · SHA-256 0ea736ef6accdf917d1e6baec2d749ca5f022509bdbb6da2071b7c1f0bc2296d.
Complete file
package eu.kanade.tachiyomi.animesource.model
data class AnimeRelation(val name: String, val animes: List<SAnime>)
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimeUpdateStrategy.kt
- Source · test / fixture · 6 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
3: enum class AnimeUpdateStrategy {
Exact file bytes / download · SHA-256 3491749c7c97fcb50ef31eb1f922ee6dfdd5747b09f091b8cd6b1a57fde4ca24.
Complete file
package eu.kanade.tachiyomi.animesource.model
enum class AnimeUpdateStrategy {
ALWAYS_UPDATE,
ONLY_FETCH_ONCE,
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/AnimesPage.kt
- Source · implementation · 6 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: data class AnimesPage(
Exact file bytes / download · SHA-256 66e79a084eeb1b3a4502d802bc984e93a1382a8d43f5f68abfab4746cc4bac80.
Complete file
package eu.kanade.tachiyomi.animesource.model
data class AnimesPage(
val animes: List<SAnime>,
val hasNextPage: Boolean,
)
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/Credit.kt
- Source · implementation · 12 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: data class Credit(
Exact file bytes / download · SHA-256 8a4848890e230c048df8229777b52cebb1770f2dd3de2273aa99546281f5048b.
Complete file
package eu.kanade.tachiyomi.animesource.model
import kotlinx.serialization.Serializable
/** Optional Animetail-compatible source credit, also used by the JSON bridge. */
@Serializable
data class Credit(
val name: String,
val role: String? = null,
val character: String? = null,
val image_url: String? = null,
)
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/FetchType.kt
- Source · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
4: enum class FetchType {
Exact file bytes / download · SHA-256 adfaa22d2db54113f1c950fb18642ee686e340cf67ab329945b27a8561ddb414.
Complete file
package eu.kanade.tachiyomi.animesource.model
/** Extensions-lib 16: a [SAnime] lists either seasons (`getSeasonList`) or episodes (`getEpisodeList`). */
enum class FetchType {
Seasons,
Episodes,
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SAnime.kt
- Source · implementation · 99 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: interface SAnime : Serializable {
43: fun copyFrom(other: SAnime) {
97: fun create(): SAnime = SAnimeImpl()
Exact file bytes / download · SHA-256 5b8a7340484d5ebdc9d1d7fad7820d5265b5de65a27a009e17f646128ecb772c.
Complete file
@file:Suppress("ktlint:standard:property-naming")
package eu.kanade.tachiyomi.animesource.model
import java.io.Serializable
interface SAnime : Serializable {
var url: String
var title: String
var artist: String?
var author: String?
var description: String?
var genre: String?
var status: Int
var thumbnail_url: String?
var update_strategy: AnimeUpdateStrategy
var initialized: Boolean
/** Older extension implementations need not provide optional credits. */
var cast: List<Credit>?
get() = null
set(_) = Unit
/** Older extension implementations are episode lists. */
var fetch_type: FetchType
get() = FetchType.Episodes
set(_) = Unit
/** -1 is unknown, as upstream. */
var season_number: Double
get() = -1.0
set(_) = Unit
fun copyFrom(other: SAnime) {
title = other.title
if (other.author != null) {
author = other.author
}
if (other.artist != null) {
artist = other.artist
}
if (other.description != null) {
description = other.description
}
if (other.genre != null) {
genre = other.genre
}
if (other.thumbnail_url != null) {
thumbnail_url = other.thumbnail_url
}
status = other.status
// APKs may implement the older interface themselves rather than use SAnime.create().
try {
other.cast?.let { cast = it }
} catch (_: AbstractMethodError) {
// No credits accessor in that binary; its existing metadata remains usable.
}
try {
fetch_type = other.fetch_type
season_number = other.season_number
} catch (_: AbstractMethodError) {
// Pre-season binary: it stays an episode list.
}
if (!initialized) {
initialized = other.initialized
}
}
companion object {
const val UNKNOWN = 0
const val ONGOING = 1
const val COMPLETED = 2
const val LICENSED = 3
const val PUBLISHING_FINISHED = 4
const val CANCELLED = 5
const val ON_HIATUS = 6
const val UPCOMING = 7
fun create(): SAnime = SAnimeImpl()
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SAnimeImpl.kt
- Source · implementation · 31 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: class SAnimeImpl : SAnime {
Exact file bytes / download · SHA-256 0d10c429296b3865212f80b92dbe42e59219de041a7da6518a9da0c3da48bb35.
Complete file
@file:Suppress("ktlint:standard:property-naming")
package eu.kanade.tachiyomi.animesource.model
class SAnimeImpl : SAnime {
override lateinit var url: String
override lateinit var title: String
override var artist: String? = null
override var author: String? = null
override var description: String? = null
override var genre: String? = null
override var status: Int = 0
override var thumbnail_url: String? = null
override var update_strategy: AnimeUpdateStrategy = AnimeUpdateStrategy.ALWAYS_UPDATE
override var initialized: Boolean = false
override var cast: List<Credit>? = null
override var fetch_type: FetchType = FetchType.Episodes
override var season_number: Double = -1.0
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SEpisode.kt
- Source · implementation · 29 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: interface SEpisode : Serializable {
18: fun copyFrom(other: SEpisode) {
27: fun create(): SEpisode = SEpisodeImpl()
Exact file bytes / download · SHA-256 4dcb7615b8c1db16352272beb8b4c01df0ca080333755d0aca71dc877ade2f3a.
Complete file
@file:Suppress("ktlint:standard:property-naming")
package eu.kanade.tachiyomi.animesource.model
import java.io.Serializable
interface SEpisode : Serializable {
var url: String
var name: String
var date_upload: Long
var episode_number: Float
var scanlator: String?
fun copyFrom(other: SEpisode) {
name = other.name
url = other.url
date_upload = other.date_upload
episode_number = other.episode_number
scanlator = other.scanlator
}
companion object {
fun create(): SEpisode = SEpisodeImpl()
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/SEpisodeImpl.kt
- Source · implementation · 15 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: class SEpisodeImpl : SEpisode {
Exact file bytes / download · SHA-256 180c01dc83d94d5e71c781c56e7080dd8b0de9aa8a58bbb17ac858e886b7dfc7.
Complete file
@file:Suppress("ktlint:standard:property-naming")
package eu.kanade.tachiyomi.animesource.model
class SEpisodeImpl : SEpisode {
override lateinit var url: String
override lateinit var name: String
override var date_upload: Long = 0
override var episode_number: Float = -1f
override var scanlator: String? = null
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/model/Video.kt
- Source · implementation · 117 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: data class Track(
13: open class Video(
80: override fun update(
98: fun setStatusSubject(subject: Subject<Int, Int>?) {
102: fun setProgressSubject(subject: Subject<Int, Int>?) {
106: fun setStatusCallback(f: ((Video) -> Unit)?) {
Exact file bytes / download · SHA-256 5abc1e9e2f74e78903f7fc897bcac5175447579afa5213b9e1193cd15e6acfa7.
Complete file
package eu.kanade.tachiyomi.animesource.model
import android.net.Uri
import eu.kanade.tachiyomi.network.ProgressListener
import okhttp3.Headers
import rx.subjects.Subject
data class Track(
val url: String,
val lang: String,
)
open class Video(
val url: String = "",
val quality: String = "",
var videoUrl: String? = null,
val headers: Headers? = null,
// "url", "language-label-2", "url2", "language-label-2"
val subtitleTracks: List<Track> = emptyList(),
val audioTracks: List<Track> = emptyList(),
) : ProgressListener {
@Suppress("UNUSED_PARAMETER")
constructor(
url: String,
quality: String,
videoUrl: String?,
uri: Uri? = null,
headers: Headers? = null,
) : this(url, quality, videoUrl, headers)
@Transient
@Volatile
var status: Int = 0
set(value) {
field = value
statusSubject?.onNext(value)
statusCallback?.invoke(this)
}
@Transient
@Volatile
var progress: Int = 0
set(value) {
progressSubject?.onNext(value)
field = value
statusCallback?.invoke(this)
}
@Transient
@Volatile
var totalBytesDownloaded: Long = 0L
@Transient
@Volatile
var totalContentLength: Long = 0L
@Transient
@Volatile
var bytesDownloaded: Long = 0L
set(value) {
totalBytesDownloaded +=
if (value < field) {
value
} else {
value - field
}
field = value
statusCallback?.invoke(this)
}
@Transient
private var statusSubject: Subject<Int, Int>? = null
@Transient
private var progressSubject: Subject<Int, Int>? = null
@Transient
private var statusCallback: ((Video) -> Unit)? = null
override fun update(
bytesRead: Long,
contentLength: Long,
done: Boolean,
) {
bytesDownloaded = bytesRead
if (contentLength > totalContentLength) {
totalContentLength = contentLength
}
val newProgress =
if (totalContentLength > 0) {
(100 * totalBytesDownloaded / totalContentLength).toInt()
} else {
-1
}
if (progress != newProgress) progress = newProgress
}
fun setStatusSubject(subject: Subject<Int, Int>?) {
this.statusSubject = subject
}
fun setProgressSubject(subject: Subject<Int, Int>?) {
this.progressSubject = subject
}
fun setStatusCallback(f: ((Video) -> Unit)?) {
statusCallback = f
}
companion object {
const val QUEUE = 0
const val LOAD_VIDEO = 1
const val DOWNLOAD_IMAGE = 2
const val READY = 3
const val ERROR = 4
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/AnimeHttpSource.kt
- Source · implementation · 479 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
29: abstract class AnimeHttpSource : AnimeCatalogueSource {
86: protected fun generateId(
99: protected open fun headersBuilder() =
107: override fun toString() = "$name (${lang.uppercase()})"
119: override fun fetchPopularAnime(page: Int): Observable<AnimesPage> =
130: protected abstract fun popularAnimeRequest(page: Int): Request
137: protected abstract fun popularAnimeParse(response: Response): AnimesPage
151: override fun fetchSearchAnime(
174: protected abstract fun searchAnimeRequest(
185: protected abstract fun searchAnimeParse(response: Response): AnimesPage
196: override fun fetchLatestUpdates(page: Int): Observable<AnimesPage> =
207: protected abstract fun latestUpdatesRequest(page: Int): Request
214: protected abstract fun latestUpdatesParse(response: Response): AnimesPage
224: override suspend fun getAnimeDetails(anime: SAnime): SAnime = fetchAnimeDetails(anime).awaitSingle()
227: override fun fetchAnimeDetails(anime: SAnime): Observable<SAnime> =
241: open fun animeDetailsRequest(anime: SAnime): Request = GET(baseUrl + anime.url, headers)
248: protected abstract fun animeDetailsParse(response: Response): SAnime
259: override suspend fun getEpisodeList(anime: SAnime): List<SEpisode> {
268: override fun fetchEpisodeList(anime: SAnime): Observable<List<SEpisode>> =
284: protected open fun episodeListRequest(anime: SAnime): Request = GET(baseUrl + anime.url, headers)
291: protected abstract fun episodeListParse(response: Response): List<SEpisode>
298: protected abstract fun episodeVideoParse(response: Response): SEpisode
308: override suspend fun getVideoList(episode: SEpisode): List<Video> = fetchVideoList(episode).awaitSingle()
311: override fun fetchVideoList(episode: SEpisode): Observable<List<Video>> =
325: protected open fun videoListRequest(episode: SEpisode): Request = GET(baseUrl + episode.url, headers)
332: protected abstract fun videoListParse(response: Response): List<Video>
337: protected open fun List<Video>.sort(): List<Video> = this
347: open suspend fun getVideoUrl(video: Video): String = fetchVideoUrl(video).awaitSingle()
350: open fun fetchVideoUrl(video: Video): Observable<String> =
362: protected open fun videoUrlRequest(video: Video): Request = GET(video.url, headers)
369: protected abstract fun videoUrlParse(response: Response): String
378: open suspend fun getVideo(video: Video): Response =
389: protected open fun videoRequest(
409: fun SEpisode.setUrlWithoutDomain(url: String) {
419: fun SAnime.setUrlWithoutDomain(url: String) {
428: private fun getUrlWithoutDomain(orig: String): String =
450: open fun getAnimeUrl(anime: SAnime): String = animeDetailsRequest(anime).url.toString()
459: open fun getEpisodeUrl(episode: SEpisode): String = episode.url.toString()
468: open fun prepareNewEpisode(
476: override fun getFilterList() = AnimeFilterList()
479: class LicensedEntryItemsException : Exception("Licensed - No items to show")
Exact file bytes / download · SHA-256 4b0510d2bcfc43b57c8e5b79c6f0ad28cca31db1bda7410c0cfc8facc1cfd035.
Complete file
package eu.kanade.tachiyomi.animesource.online
import eu.kanade.tachiyomi.animesource.AnimeCatalogueSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.AnimesPage
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.network.awaitSuccess
import eu.kanade.tachiyomi.network.newCachelessCallWithProgress
import eu.kanade.tachiyomi.util.lang.awaitSingle
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.net.URI
import java.net.URISyntaxException
import java.security.MessageDigest
/**
* A simple implementation for sources from a website.
*/
@Suppress("unused")
abstract class AnimeHttpSource : AnimeCatalogueSource {
/**
* Network service.
*/
val network: NetworkHelper by injectLazy()
/**
* Base url of the website without the trailing slash, like: http://mysite.com
*/
abstract val baseUrl: String
/**
* Version id used to generate the source id. If the site completely changes and urls are
* incompatible, you may increase this value and it'll be considered as a new source.
*/
open val versionId = 1
/**
* ID of the source. By default it uses a generated id using the first 16 characters (64 bits)
* of the MD5 of the string `"${name.lowercase()}/$lang/$versionId"`.
*
* The ID is generated by the [generateId] function, which can be reused if needed
* to generate outdated IDs for cases where the source name or language needs to
* be changed but migrations can be avoided.
*
* Note: the generated ID sets the sign bit to `0`.
*/
override val id by lazy { generateId(name, lang, versionId) }
/**
* Headers used for requests.
*/
val headers: Headers by lazy { headersBuilder().build() }
/**
* Default network client for doing requests.
*/
open val client: OkHttpClient
get() = network.client
/**
* Generates a unique ID for the source based on the provided [name], [lang] and
* [versionId]. It will use the first 16 characters (64 bits) of the MD5 of the string
* `"${name.lowercase()}/$lang/$versionId"`.
*
* Note: the generated ID sets the sign bit to `0`.
*
* Can be used to generate outdated IDs, such as when the source name or language
* needs to be changed but migrations can be avoided.
*
* @since extensions-lib 15
* @param name [String] the name of the source
* @param lang [String] the language of the source
* @param versionId [Int] the version ID of the source
* @return a unique ID for the source
*/
@Suppress("MemberVisibilityCanBePrivate")
protected fun generateId(
name: String,
lang: String,
versionId: Int,
): Long {
val key = "${name.lowercase()}/$lang/$versionId"
val bytes = MessageDigest.getInstance("MD5").digest(key.toByteArray())
return (0..7).map { bytes[it].toLong() and 0xff shl 8 * (7 - it) }.reduce(Long::or) and Long.MAX_VALUE
}
/**
* Headers builder for requests. Implementations can override this method for custom headers.
*/
protected open fun headersBuilder() =
Headers.Builder().apply {
add("User-Agent", network.defaultUserAgentProvider())
}
/**
* Visible name of the source.
*/
override fun toString() = "$name (${lang.uppercase()})"
/**
* Returns an observable containing a page with a list of anime. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
*/
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getPopularAnime"),
)
override fun fetchPopularAnime(page: Int): Observable<AnimesPage> =
client
.newCall(popularAnimeRequest(page))
.asObservableSuccess()
.map(::popularAnimeParse)
/**
* Returns the request for the popular anime given the page.
*
* @param page the page number to retrieve.
*/
protected abstract fun popularAnimeRequest(page: Int): Request
/**
* Parses the response from the site and returns a [AnimesPage] object.
*
* @param response the response from the site.
*/
protected abstract fun popularAnimeParse(response: Response): AnimesPage
/**
* Returns an observable containing a page with a list of anime. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getSearchAnime"),
)
override fun fetchSearchAnime(
page: Int,
query: String,
filters: AnimeFilterList,
): Observable<AnimesPage> =
Observable
.defer {
try {
client.newCall(searchAnimeRequest(page, query, filters)).asObservableSuccess()
} catch (e: NoClassDefFoundError) {
// RxJava doesn't handle Errors, which tends to happen during global searches
// if an old extension using non-existent classes is still around
throw RuntimeException(e)
}
}.map(::searchAnimeParse)
/**
* Returns the request for the search anime given the page.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
protected abstract fun searchAnimeRequest(
page: Int,
query: String,
filters: AnimeFilterList,
): Request
/**
* Parses the response from the site and returns a [AnimesPage] object.
*
* @param response the response from the site.
*/
protected abstract fun searchAnimeParse(response: Response): AnimesPage
/**
* Returns an observable containing a page with a list of latest anime updates.
*
* @param page the page number to retrieve.
*/
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getLatestUpdates"),
)
override fun fetchLatestUpdates(page: Int): Observable<AnimesPage> =
client
.newCall(latestUpdatesRequest(page))
.asObservableSuccess()
.map(::latestUpdatesParse)
/**
* Returns the request for latest anime given the page.
*
* @param page the page number to retrieve.
*/
protected abstract fun latestUpdatesRequest(page: Int): Request
/**
* Parses the response from the site and returns a [AnimesPage] object.
*
* @param response the response from the site.
*/
protected abstract fun latestUpdatesParse(response: Response): AnimesPage
/**
* Get the updated details for a anime.
* Normally it's not needed to override this method.
*
* @param anime the anime to be updated.
* @return the updated anime.
*/
@Suppress("DEPRECATION")
override suspend fun getAnimeDetails(anime: SAnime): SAnime = fetchAnimeDetails(anime).awaitSingle()
@Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getAnimeDetails"))
override fun fetchAnimeDetails(anime: SAnime): Observable<SAnime> =
client
.newCall(animeDetailsRequest(anime))
.asObservableSuccess()
.map { response ->
animeDetailsParse(response).apply { initialized = true }
}
/**
* Returns the request for the details of an anime. Override only if it's needed to change the
* url, send different headers or request method like POST.
*
* @param anime the anime to be updated.
*/
open fun animeDetailsRequest(anime: SAnime): Request = GET(baseUrl + anime.url, headers)
/**
* Parses the response from the site and returns the details of an anime.
*
* @param response the response from the site.
*/
protected abstract fun animeDetailsParse(response: Response): SAnime
/**
* Get all the available episodes for an anime.
* Normally it's not needed to override this method.
*
* @param anime the anime to update.
* @return the chapters for the manga.
* @throws LicensedEntryItemsException if a anime is licensed and therefore no episodes are available.
*/
@Suppress("DEPRECATION")
override suspend fun getEpisodeList(anime: SAnime): List<SEpisode> {
if (anime.status == SAnime.LICENSED) {
throw LicensedEntryItemsException()
}
return fetchEpisodeList(anime).awaitSingle()
}
@Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getEpisodeList"))
override fun fetchEpisodeList(anime: SAnime): Observable<List<SEpisode>> =
if (anime.status != SAnime.LICENSED) {
client
.newCall(episodeListRequest(anime))
.asObservableSuccess()
.map(::episodeListParse)
} else {
Observable.error(Exception(LicensedEntryItemsException()))
}
/**
* Returns the request for updating the episode list. Override only if it's needed to override
* the url, send different headers or request method like POST.
*
* @param anime the anime to look for episodes.
*/
protected open fun episodeListRequest(anime: SAnime): Request = GET(baseUrl + anime.url, headers)
/**
* Parses the response from the site and returns a list of episodes.
*
* @param response the response from the site.
*/
protected abstract fun episodeListParse(response: Response): List<SEpisode>
/**
* Parses the response from the site and returns a SEpisode Object.
*
* @param response the response from the site.
*/
protected abstract fun episodeVideoParse(response: Response): SEpisode
/**
* Get the list of videos a episode has. Videos should be returned
* in the expected order; the index is ignored.
*
* @param episode the episode.
* @return the videos for the episode.
*/
@Suppress("DEPRECATION")
override suspend fun getVideoList(episode: SEpisode): List<Video> = fetchVideoList(episode).awaitSingle()
@Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getVideoList"))
override fun fetchVideoList(episode: SEpisode): Observable<List<Video>> =
client
.newCall(videoListRequest(episode))
.asObservableSuccess()
.map { response ->
videoListParse(response).sort()
}
/**
* Returns the request for getting the episode link. Override only if it's needed to override
* the url, send different headers or request method like POST.
*
* @param episode the episode to look for links.
*/
protected open fun videoListRequest(episode: SEpisode): Request = GET(baseUrl + episode.url, headers)
/**
* Parses the response from the site and returns a list of pages.
*
* @param response the response from the site.
*/
protected abstract fun videoListParse(response: Response): List<Video>
/**
* Sorts the video list. Override this according to the user's preference.
*/
protected open fun List<Video>.sort(): List<Video> = this
/**
* Returns an observable with the page containing the source url of the image. If there's any
* error, it will return null instead of throwing an exception.
*
* @since extensions-lib 15
* @param video the video whose source image has to be fetched.
*/
@Suppress("DEPRECATION")
open suspend fun getVideoUrl(video: Video): String = fetchVideoUrl(video).awaitSingle()
@Deprecated("Use the non-RxJava API instead", replaceWith = ReplaceWith("getVideoUrl"))
open fun fetchVideoUrl(video: Video): Observable<String> =
client
.newCall(videoUrlRequest(video))
.asObservableSuccess()
.map(::videoUrlParse)
/**
* Returns the request for getting the url to the source image. Override only if it's needed to
* override the url, send different headers or request method like POST.
*
* @param video the chapter whose page list has to be fetched
*/
protected open fun videoUrlRequest(video: Video): Request = GET(video.url, headers)
/**
* Parses the response from the site and returns the absolute url to the source image.
*
* @param response the response from the site.
*/
protected abstract fun videoUrlParse(response: Response): String
/**
* Returns the response of the source video.
* Typically does not need to be overridden.
*
* @since extensions-lib 15
* @param video the video whose source video has to be downloaded.
*/
open suspend fun getVideo(video: Video): Response =
client
.newCachelessCallWithProgress(videoRequest(video), video)
.awaitSuccess()
/**
* Returns the request for getting the source image. Override only if it's needed to override
* the url, send different headers or request method like POST.
*
* @param video the video whose link has to be fetched
*/
protected open fun videoRequest(
video: Video,
bytes: Long = 0L,
): Request {
val headers = video.headers ?: headers
val newHeaders =
if (bytes > 0L) {
headers.newBuilder().add("Range", "bytes=$bytes-").build()
} else {
headers
}
return GET(video.videoUrl ?: video.url, newHeaders)
}
/**
* Assigns the url of the episode without the scheme and domain. It saves some redundancy from
* database and the urls could still work after a domain change.
*
* @param url the full url to the episode.
*/
fun SEpisode.setUrlWithoutDomain(url: String) {
this.url = getUrlWithoutDomain(url)
}
/**
* Assigns the url of the anime without the scheme and domain. It saves some redundancy from
* database and the urls could still work after a domain change.
*
* @param url the full url to the anime.
*/
fun SAnime.setUrlWithoutDomain(url: String) {
this.url = getUrlWithoutDomain(url)
}
/**
* Returns the url of the given string without the scheme and domain.
*
* @param orig the full url.
*/
private fun getUrlWithoutDomain(orig: String): String =
try {
val uri = URI(orig)
var out = uri.path
if (uri.query != null) {
out += "?" + uri.query
}
if (uri.fragment != null) {
out += "#" + uri.fragment
}
out
} catch (e: URISyntaxException) {
orig
}
/**
* Returns the url of the provided anime
*
* @since extensions-lib 14
* @param anime the anime
* @return url of the anime
*/
open fun getAnimeUrl(anime: SAnime): String = animeDetailsRequest(anime).url.toString()
/**
* Returns the url of the provided episode
*
* @since extensions-lib 14
* @param episode the episode
* @return url of the episode
*/
open fun getEpisodeUrl(episode: SEpisode): String = episode.url.toString()
/**
* Called before inserting a new episode into database. Use it if you need to override episode
* fields, like the title or the episode number. Do not change anything to [anime].
*
* @param episode the episode to be added.
* @param anime the anime of the episode.
*/
open fun prepareNewEpisode(
episode: SEpisode,
anime: SAnime,
) {}
/**
* Returns the list of filters for the source.
*/
override fun getFilterList() = AnimeFilterList()
}
class LicensedEntryItemsException : Exception("Licensed - No items to show")
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/ParsedAnimeHttpSource.kt
- Source · implementation · 204 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
15: abstract class ParsedAnimeHttpSource : AnimeHttpSource() {
21: override fun popularAnimeParse(response: Response): AnimesPage {
39: protected abstract fun popularAnimeSelector(): String
47: protected abstract fun popularAnimeFromElement(element: Element): SAnime
53: protected abstract fun popularAnimeNextPageSelector(): String?
60: override fun searchAnimeParse(response: Response): AnimesPage {
78: protected abstract fun searchAnimeSelector(): String
86: protected abstract fun searchAnimeFromElement(element: Element): SAnime
92: protected abstract fun searchAnimeNextPageSelector(): String?
99: override fun latestUpdatesParse(response: Response): AnimesPage {
117: protected abstract fun latestUpdatesSelector(): String
125: protected abstract fun latestUpdatesFromElement(element: Element): SAnime
131: protected abstract fun latestUpdatesNextPageSelector(): String?
138: override fun animeDetailsParse(response: Response): SAnime = animeDetailsParse(response.asJsoup())
145: protected abstract fun animeDetailsParse(document: Document): SAnime
152: override fun episodeListParse(response: Response): List<SEpisode> {
160: protected abstract fun episodeListSelector(): String
167: protected abstract fun episodeFromElement(element: Element): SEpisode
174: override fun videoListParse(response: Response): List<Video> {
182: protected abstract fun videoListSelector(): String
189: protected abstract fun videoFromElement(element: Element): Video
196: override fun videoUrlParse(response: Response): String = videoUrlParse(response.asJsoup())
203: protected abstract fun videoUrlParse(document: Document): String
Exact file bytes / download · SHA-256 ecf1372132981c82803581c110682a90fc0ba41b7e3c8f6df739d9f374e8ab65.
Complete file
package eu.kanade.tachiyomi.animesource.online
import eu.kanade.tachiyomi.animesource.model.AnimesPage
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
/**
* A simple implementation for sources from a website using Jsoup, an HTML parser.
*/
abstract class ParsedAnimeHttpSource : AnimeHttpSource() {
/**
* Parses the response from the site and returns a [AnimesPage] object.
*
* @param response the response from the site.
*/
override fun popularAnimeParse(response: Response): AnimesPage {
val document = response.asJsoup()
val animes =
document
.select(popularAnimeSelector())
.map(::popularAnimeFromElement)
val hasNextPage =
popularAnimeNextPageSelector()
?.let(document::selectFirst) != null
return AnimesPage(animes, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each anime.
*/
protected abstract fun popularAnimeSelector(): String
/**
* Returns a anime from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [popularAnimeSelector].
*/
protected abstract fun popularAnimeFromElement(element: Element): SAnime
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
protected abstract fun popularAnimeNextPageSelector(): String?
/**
* Parses the response from the site and returns a [AnimesPage] object.
*
* @param response the response from the site.
*/
override fun searchAnimeParse(response: Response): AnimesPage {
val document = response.asJsoup()
val animes =
document
.select(searchAnimeSelector())
.map(::searchAnimeFromElement)
val hasNextPage =
searchAnimeNextPageSelector()
?.let(document::selectFirst) != null
return AnimesPage(animes, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each anime.
*/
protected abstract fun searchAnimeSelector(): String
/**
* Returns a anime from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [searchAnimeSelector].
*/
protected abstract fun searchAnimeFromElement(element: Element): SAnime
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
protected abstract fun searchAnimeNextPageSelector(): String?
/**
* Parses the response from the site and returns a [AnimesPage] object.
*
* @param response the response from the site.
*/
override fun latestUpdatesParse(response: Response): AnimesPage {
val document = response.asJsoup()
val animes =
document
.select(latestUpdatesSelector())
.map(::latestUpdatesFromElement)
val hasNextPage =
latestUpdatesNextPageSelector()
?.let(document::selectFirst) != null
return AnimesPage(animes, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each anime.
*/
protected abstract fun latestUpdatesSelector(): String
/**
* Returns a anime from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [latestUpdatesSelector].
*/
protected abstract fun latestUpdatesFromElement(element: Element): SAnime
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
protected abstract fun latestUpdatesNextPageSelector(): String?
/**
* Parses the response from the site and returns the details of a anime.
*
* @param response the response from the site.
*/
override fun animeDetailsParse(response: Response): SAnime = animeDetailsParse(response.asJsoup())
/**
* Returns the details of the anime from the given [document].
*
* @param document the parsed document.
*/
protected abstract fun animeDetailsParse(document: Document): SAnime
/**
* Parses the response from the site and returns a list of episodes.
*
* @param response the response from the site.
*/
override fun episodeListParse(response: Response): List<SEpisode> {
val document = response.asJsoup()
return document.select(episodeListSelector()).map(::episodeFromElement)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each episode.
*/
protected abstract fun episodeListSelector(): String
/**
* Returns a episode from the given element.
*
* @param element an element obtained from [episodeListSelector].
*/
protected abstract fun episodeFromElement(element: Element): SEpisode
/**
* Parses the response from the site and returns the page list.
*
* @param response the response from the site.
*/
override fun videoListParse(response: Response): List<Video> {
val document = response.asJsoup()
return document.select(videoListSelector()).map(::videoFromElement)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each video.
*/
protected abstract fun videoListSelector(): String
/**
* Returns a video from the given element.
*
* @param element an element obtained from [videoListSelector].
*/
protected abstract fun videoFromElement(element: Element): Video
/**
* Parse the response from the site and returns the absolute url to the source video.
*
* @param response the response from the site.
*/
override fun videoUrlParse(response: Response): String = videoUrlParse(response.asJsoup())
/**
* Returns the absolute url to the source image from the document.
*
* @param document the parsed document.
*/
protected abstract fun videoUrlParse(document: Document): String
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/animesource/online/ResolvableAnimeSource.kt
- Source · implementation · 44 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: interface ResolvableAnimeSource : AnimeSource {
19: fun getUriType(uri: String): UriType
27: suspend fun getAnime(uri: String): SAnime?
35: suspend fun getEpisode(uri: String): SEpisode?
38: sealed interface UriType {
39: data object Anime : UriType
41: data object Episode : UriType
43: data object Unknown : UriType
Exact file bytes / download · SHA-256 e2ccae4f1efc278f9f1eb9d723994ab43c61617501b66a25665dcbd8233a30c8.
Complete file
package eu.kanade.tachiyomi.animesource.online
import eu.kanade.tachiyomi.animesource.AnimeSource
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
/**
* A source that may handle opening an SAnime or SEpisode for a given URI.
*
* @since extensions-lib 14
*/
interface ResolvableAnimeSource : AnimeSource {
/**
* Returns what the given URI may open.
* Returns [UriType.Unknown] if the source is not able to resolve the URI.
*
* @since extensions-lib 14
*/
fun getUriType(uri: String): UriType
/**
* Called if [getUriType] is [UriType.Anime].
* Returns the corresponding SAnime, if possible.
*
* @since extensions-lib 14
*/
suspend fun getAnime(uri: String): SAnime?
/**
* Called if [getUriType] is [UriType.Episode].
* Returns the corresponding SEpisode, if possible.
*
* @since extensions-lib 14
*/
suspend fun getEpisode(uri: String): SEpisode?
}
sealed interface UriType {
data object Anime : UriType
data object Episode : UriType
data object Unknown : UriType
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/MemoryCookieJar.kt
- Source · implementation · 92 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: class MemoryCookieJar : CookieJar {
11: override fun loadForRequest(url: HttpUrl): List<Cookie> {
29: override fun saveFromResponse(
40: fun clear() {
45: fun addCookie(cookie: Cookie) {
52: fun addAll(
60: class WrappedCookie private constructor(
63: fun unwrap() = cookie
65: fun isExpired() = cookie.expiresAt < System.currentTimeMillis()
67: fun matches(url: HttpUrl) = cookie.matches(url)
69: override fun equals(other: Any?): Boolean {
79: override fun hashCode(): Int {
90: fun wrap(cookie: Cookie) = WrappedCookie(cookie)
Exact file bytes / download · SHA-256 0c313e9e4ef6420b9fdc90202dab9c868a3186f1a3f9dd89b93e9b71cd9bb8e1.
Complete file
package eu.kanade.tachiyomi.network
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
class MemoryCookieJar : CookieJar {
private val cache = mutableSetOf<WrappedCookie>()
@Synchronized
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val cookiesToRemove = mutableSetOf<WrappedCookie>()
val validCookies = mutableSetOf<WrappedCookie>()
cache.forEach { cookie ->
if (cookie.isExpired()) {
cookiesToRemove.add(cookie)
} else if (cookie.matches(url)) {
validCookies.add(cookie)
}
}
cache.removeAll(cookiesToRemove)
return validCookies.toList().map(WrappedCookie::unwrap)
}
@Synchronized
override fun saveFromResponse(
url: HttpUrl,
cookies: List<Cookie>,
) {
val cookiesToAdd = cookies.map { WrappedCookie.wrap(it) }
cache.removeAll(cookiesToAdd)
cache.addAll(cookiesToAdd)
}
@Synchronized
fun clear() {
cache.clear()
}
@Synchronized
fun addCookie(cookie: Cookie) {
val wrapped = WrappedCookie.wrap(cookie)
cache.remove(wrapped)
cache.add(wrapped)
}
@Synchronized
fun addAll(
url: HttpUrl,
cookies: List<Cookie>,
) {
cookies.forEach { addCookie(it) }
}
}
class WrappedCookie private constructor(
val cookie: Cookie,
) {
fun unwrap() = cookie
fun isExpired() = cookie.expiresAt < System.currentTimeMillis()
fun matches(url: HttpUrl) = cookie.matches(url)
override fun equals(other: Any?): Boolean {
if (other !is WrappedCookie) return false
return other.cookie.name == cookie.name &&
other.cookie.domain == cookie.domain &&
other.cookie.path == cookie.path &&
other.cookie.secure == cookie.secure &&
other.cookie.hostOnly == cookie.hostOnly
}
override fun hashCode(): Int {
var hash = 17
hash = 31 * hash + cookie.name.hashCode()
hash = 31 * hash + cookie.domain.hashCode()
hash = 31 * hash + cookie.path.hashCode()
hash = 31 * hash + if (cookie.secure) 0 else 1
hash = 31 * hash + if (cookie.hostOnly) 0 else 1
return hash
}
companion object {
fun wrap(cookie: Cookie) = WrappedCookie(cookie)
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/NetworkHelper.kt
- Source · implementation · 52 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: class NetworkHelper(
47: fun setUA(ua: String) {
51: fun defaultUserAgentProvider() = defaultUserAgent
Exact file bytes / download · SHA-256 493631ab7c8128433e787dbbffb83d9cf7b885ba4dc24d709ea8fed9a583e86a.
Complete file
package eu.kanade.tachiyomi.network
import android.content.Context
import eu.kanade.tachiyomi.network.interceptor.CloudflareInterceptor
import eu.kanade.tachiyomi.network.interceptor.IgnoreGzipInterceptor
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.brotli.BrotliInterceptor
import okhttp3.logging.HttpLoggingInterceptor
import java.nio.file.Files
import java.util.concurrent.TimeUnit
class NetworkHelper(
val context: Context,
) {
val cookieJar = MemoryCookieJar()
val client by lazy {
val builder =
OkHttpClient
.Builder()
.cookieJar(cookieJar)
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.addNetworkInterceptor(IgnoreGzipInterceptor())
.addNetworkInterceptor(BrotliInterceptor)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.callTimeout(2, TimeUnit.MINUTES)
.cache(
Cache(
directory = Files.createTempDirectory("m_network_cache").toFile(),
maxSize = 5L * 1024 * 1024, // 5 MiB
),
)
builder.build()
}
val cloudflareClient by lazy {
client
.newBuilder()
.addInterceptor(CloudflareInterceptor())
.build()
}
private var defaultUserAgent: String = System.getProperty("http.agent").orEmpty()
fun setUA(ua: String) {
defaultUserAgent = ua
}
fun defaultUserAgentProvider() = defaultUserAgent
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/OkHttpExtensions.kt
- Source · implementation · 174 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
22: private suspend fun Call.await(callStack: Array<StackTraceElement>): Response {
25: object : Callback {
26: override fun onResponse(
35: override fun onFailure(
58: suspend fun Call.await(): Response {
66: suspend fun Call.awaitSuccess(): Response {
77: fun OkHttpClient.newCachelessCallWithProgress(
89: fun Call.asObservable(): Observable<Response> {
96: object : AtomicBoolean(), Producer, Subscription {
97: override fun request(n: Long) {
113: override fun unsubscribe() {
117: override fun isUnsubscribed(): Boolean = call.isCanceled()
125: fun Call.asObservableSuccess(): Observable<Response> =
133: fun OkHttpClient.newCallWithProgress(
144: class HttpException(
148: fun Cookie.toHttpCookie(url: HttpUrl): HttpCookie {
160: fun HttpCookie.toCookie(url: HttpUrl): Cookie {
Exact file bytes / download · SHA-256 d9c7bc28a8755e3b028135e5f5a2e0cbe40414c66a73cb04f312c6e9c4052538.
Complete file
package eu.kanade.tachiyomi.network
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Cookie
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import rx.Producer
import rx.Subscription
import java.io.IOException
import java.net.HttpCookie
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.resumeWithException
// Based on https://github.com/gildor/kotlin-coroutines-okhttp
@OptIn(ExperimentalCoroutinesApi::class)
private suspend fun Call.await(callStack: Array<StackTraceElement>): Response {
return suspendCancellableCoroutine { continuation ->
val callback =
object : Callback {
override fun onResponse(
call: Call,
response: Response,
) {
continuation.resume(response) { cause, value, context ->
value.body.close()
}
}
override fun onFailure(
call: Call,
e: IOException,
) {
// Don't bother with resuming the continuation if it is already cancelled.
if (continuation.isCancelled) return
val exception = IOException(e.message, e).apply { stackTrace = callStack }
continuation.resumeWithException(exception)
}
}
enqueue(callback)
continuation.invokeOnCancellation {
try {
cancel()
} catch (ex: Throwable) {
// Ignore cancel exception
}
}
}
}
suspend fun Call.await(): Response {
val callStack = Exception().stackTrace.run { copyOfRange(1, size) }
return await(callStack)
}
/**
* @since extensions-lib 15
*/
suspend fun Call.awaitSuccess(): Response {
val callStack = Exception().stackTrace.run { copyOfRange(1, size) }
val response = await(callStack)
if (!response.isSuccessful) {
response.close()
throw HttpException(response.code).apply { stackTrace = callStack }
}
return response
}
@Suppress("unused_parameter", "UnusedParameter")
fun OkHttpClient.newCachelessCallWithProgress(
request: Request,
listener: ProgressListener,
): Call {
val progressClient =
newBuilder()
.cache(null)
.build()
return progressClient.newCall(request)
}
fun Call.asObservable(): Observable<Response> {
return Observable.unsafeCreate { subscriber ->
// Since Call is a one-shot type, clone it for each new subscriber.
val call = clone()
// Wrap the call in a helper which handles both unsubscription and backpressure.
val requestArbiter =
object : AtomicBoolean(), Producer, Subscription {
override fun request(n: Long) {
if (n == 0L || !compareAndSet(false, true)) return
try {
val response = call.execute()
if (!subscriber.isUnsubscribed) {
subscriber.onNext(response)
subscriber.onCompleted()
}
} catch (e: Exception) {
if (!subscriber.isUnsubscribed) {
subscriber.onError(e)
}
}
}
override fun unsubscribe() {
call.cancel()
}
override fun isUnsubscribed(): Boolean = call.isCanceled()
}
subscriber.add(requestArbiter)
subscriber.setProducer(requestArbiter)
}
}
fun Call.asObservableSuccess(): Observable<Response> =
asObservable().doOnNext { response ->
if (!response.isSuccessful) {
response.close()
throw HttpException(response.code)
}
}
fun OkHttpClient.newCallWithProgress(
request: Request,
listener: ProgressListener,
): Call {
val progressClient =
newBuilder()
.build()
return progressClient.newCall(request)
}
class HttpException(
val code: Int,
) : IllegalStateException("HTTP error $code")
fun Cookie.toHttpCookie(url: HttpUrl): HttpCookie {
val httpCookie = HttpCookie(name, value)
httpCookie.domain = domain
httpCookie.path = path
httpCookie.secure = secure
// httpCookie.httpOnly = httpOnly // private field
if (expiresAt != Long.MAX_VALUE) {
httpCookie.maxAge = (expiresAt - System.currentTimeMillis()) / 1000
}
return httpCookie
}
fun HttpCookie.toCookie(url: HttpUrl): Cookie {
val builder =
Cookie
.Builder()
.name(name)
.value(value)
if (domain != null) builder.domain(domain)
if (path != null) builder.path(path)
if (secure) builder.secure()
// if (httpOnly) builder.httpOnly() // private field
if (maxAge > 0) {
builder.expiresAt(System.currentTimeMillis() + maxAge * 1000)
}
return builder.build()
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/ProgressListener.kt
- Source · implementation · 9 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: interface ProgressListener {
4: fun update(
Exact file bytes / download · SHA-256 245c66d3dfce4755a8acfeda958bb9ba546115daac434766bc48ea79b806ddad.
Complete file
package eu.kanade.tachiyomi.network
interface ProgressListener {
fun update(
bytesRead: Long,
contentLength: Long,
done: Boolean,
)
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/Requests.kt
- Source · implementation · 56 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
17: fun GET(
32: fun GET(
44: fun POST(
Exact file bytes / download · SHA-256 b7fcfed232d59dd0d9652f7b350664eb77cc522a6eb9f6bd92fd2ed55bda70d6.
Complete file
@file:Suppress("ktlint:standard:function-naming")
package eu.kanade.tachiyomi.network
import okhttp3.CacheControl
import okhttp3.FormBody
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.Request
import okhttp3.RequestBody
import java.util.concurrent.TimeUnit.MINUTES
private val DEFAULT_CACHE_CONTROL = CacheControl.Builder().maxAge(10, MINUTES).build()
private val DEFAULT_HEADERS = Headers.Builder().build()
private val DEFAULT_BODY: RequestBody = FormBody.Builder().build()
fun GET(
url: String,
headers: Headers = DEFAULT_HEADERS,
cache: CacheControl = DEFAULT_CACHE_CONTROL,
): Request =
Request
.Builder()
.url(url)
.headers(headers)
.cacheControl(cache)
.build()
/**
* @since extensions-lib 1.4
*/
fun GET(
url: HttpUrl,
headers: Headers = DEFAULT_HEADERS,
cache: CacheControl = DEFAULT_CACHE_CONTROL,
): Request =
Request
.Builder()
.url(url)
.headers(headers)
.cacheControl(cache)
.build()
fun POST(
url: String,
headers: Headers = DEFAULT_HEADERS,
body: RequestBody = DEFAULT_BODY,
cache: CacheControl = DEFAULT_CACHE_CONTROL,
): Request =
Request
.Builder()
.url(url)
.post(body)
.headers(headers)
.cacheControl(cache)
.build()
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/CloudflareInterceptor.kt
- Source · implementation · 12 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: class CloudflareInterceptor : Interceptor {
8: override fun intercept(chain: Interceptor.Chain): Response {
Exact file bytes / download · SHA-256 690a5bdd89c26711fdab7f05a84f53a4b4ca4f22946f1024e6826ed2f1c156b6.
Complete file
package eu.kanade.tachiyomi.network.interceptor
import okhttp3.Interceptor
import okhttp3.Response
class CloudflareInterceptor : Interceptor {
@Synchronized
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
return chain.proceed(originalRequest)
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/IgnoreGzipInterceptor.kt
- Source · implementation · 21 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: class IgnoreGzipInterceptor : Interceptor {
14: override fun intercept(chain: Interceptor.Chain): Response {
Exact file bytes / download · SHA-256 35e6e629180505b236ac7c61dcd68b764bd7537ab47c28347e8487a4017d1f35.
Complete file
package eu.kanade.tachiyomi.network.interceptor
import okhttp3.Interceptor
import okhttp3.Response
/**
* To use [okhttp3.brotli.BrotliInterceptor] as a network interceptor,
* add [IgnoreGzipInterceptor] right before it.
*
* This nullifies the transparent gzip of [okhttp3.internal.http.BridgeInterceptor]
* so gzip and Brotli are explicitly handled by the [okhttp3.brotli.BrotliInterceptor].
*/
class IgnoreGzipInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
if (request.header("Accept-Encoding") == "gzip") {
request = request.newBuilder().removeHeader("Accept-Encoding").build()
}
return chain.proceed(request)
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/RateLimitInterceptor.kt
- Source · implementation · 67 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
23: fun OkHttpClient.Builder.rateLimit(
29: private class RateLimitInterceptor(
37: override fun intercept(chain: Interceptor.Chain): Response {
Exact file bytes / download · SHA-256 d6218d22932389dfe524ca3b8a3c64971a9e0e469c02e1374624555ab71a0ee8.
Complete file
package eu.kanade.tachiyomi.network.interceptor
import android.os.SystemClock
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import java.util.concurrent.TimeUnit
/**
* An OkHttp interceptor that handles rate limiting.
*
* Examples:
*
* permits = 5, period = 1, unit = seconds => 5 requests per second
* permits = 10, period = 2, unit = minutes => 10 requests per 2 minutes
*
* @since extension-lib 1.3
*
* @param permits {Int} Number of requests allowed within a period of units.
* @param period {Long} The limiting duration. Defaults to 1.
* @param unit {TimeUnit} The unit of time for the period. Defaults to seconds.
*/
fun OkHttpClient.Builder.rateLimit(
permits: Int,
period: Long = 1,
unit: TimeUnit = TimeUnit.SECONDS,
) = addInterceptor(RateLimitInterceptor(permits, period, unit))
private class RateLimitInterceptor(
private val permits: Int,
period: Long,
unit: TimeUnit,
) : Interceptor {
private val requestQueue = ArrayList<Long>(permits)
private val rateLimitMillis = unit.toMillis(period)
override fun intercept(chain: Interceptor.Chain): Response {
synchronized(requestQueue) {
val now = SystemClock.elapsedRealtime()
val waitTime =
if (requestQueue.size < permits) {
0
} else {
val oldestReq = requestQueue[0]
val newestReq = requestQueue[permits - 1]
if (newestReq - oldestReq > rateLimitMillis) {
0
} else {
oldestReq + rateLimitMillis - now // Remaining time
}
}
if (requestQueue.size == permits) {
requestQueue.removeAt(0)
}
if (waitTime > 0) {
requestQueue.add(now + waitTime)
Thread.sleep(waitTime) // Sleep inside synchronized to pause queued requests
} else {
requestQueue.add(now)
}
}
return chain.proceed(chain.request())
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/network/interceptor/SpecificHostRateLimitInterceptor.kt
- Source · implementation · 75 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
25: fun OkHttpClient.Builder.rateLimitHost(
32: class SpecificHostRateLimitInterceptor(
42: override fun intercept(chain: Interceptor.Chain): Response {
Exact file bytes / download · SHA-256 bd849dcd23a7098abc4072e5d20b1829ebf254d01b8d6ca243f1bc61e8521423.
Complete file
package eu.kanade.tachiyomi.network.interceptor
import android.os.SystemClock
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import java.util.concurrent.TimeUnit
/**
* An OkHttp interceptor that handles given url host's rate limiting.
*
* Examples:
*
* httpUrl = "api.manga.com".toHttpUrlOrNull(), permits = 5, period = 1, unit = seconds => 5 requests per second to api.manga.com
* httpUrl = "imagecdn.manga.com".toHttpUrlOrNull(), permits = 10, period = 2, unit = minutes => 10 requests per 2 minutes to imagecdn.manga.com
*
* @since extension-lib 1.3
*
* @param httpUrl {HttpUrl} The url host that this interceptor should handle. Will get url's host by using HttpUrl.host()
* @param permits {Int} Number of requests allowed within a period of units.
* @param period {Long} The limiting duration. Defaults to 1.
* @param unit {TimeUnit} The unit of time for the period. Defaults to seconds.
*/
fun OkHttpClient.Builder.rateLimitHost(
httpUrl: HttpUrl,
permits: Int,
period: Long = 1,
unit: TimeUnit = TimeUnit.SECONDS,
) = addInterceptor(SpecificHostRateLimitInterceptor(httpUrl, permits, period, unit))
class SpecificHostRateLimitInterceptor(
httpUrl: HttpUrl,
private val permits: Int,
period: Long,
unit: TimeUnit,
) : Interceptor {
private val requestQueue = ArrayList<Long>(permits)
private val rateLimitMillis = unit.toMillis(period)
private val host = httpUrl.host
override fun intercept(chain: Interceptor.Chain): Response {
if (chain.request().url.host != host) {
return chain.proceed(chain.request())
}
synchronized(requestQueue) {
val now = SystemClock.elapsedRealtime()
val waitTime =
if (requestQueue.size < permits) {
0
} else {
val oldestReq = requestQueue[0]
val newestReq = requestQueue[permits - 1]
if (newestReq - oldestReq > rateLimitMillis) {
0
} else {
oldestReq + rateLimitMillis - now // Remaining time
}
}
if (requestQueue.size == permits) {
requestQueue.removeAt(0)
}
if (waitTime > 0) {
requestQueue.add(now + waitTime)
Thread.sleep(waitTime) // Sleep inside synchronized to pause queued requests
} else {
requestQueue.add(now)
}
}
return chain.proceed(chain.request())
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/CatalogueSource.kt
- Source · implementation · 78 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: interface CatalogueSource : Source {
26: suspend fun getPopularManga(page: Int): MangasPage = fetchPopularManga(page).awaitSingle()
37: suspend fun getSearchManga(
50: suspend fun getLatestUpdates(page: Int): MangasPage = fetchLatestUpdates(page).awaitSingle()
55: fun getFilterList(): FilterList
61: fun fetchPopularManga(page: Int): Observable<MangasPage> = throw IllegalStateException("Not used")
67: fun fetchSearchManga(
77: fun fetchLatestUpdates(page: Int): Observable<MangasPage> = throw IllegalStateException("Not used")
Exact file bytes / download · SHA-256 9f19cc11ea8d7f9231f08d2befa0fc3019a0d0d0e7aeda02e995a33ea72c87d3.
Complete file
package eu.kanade.tachiyomi.source
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.util.lang.awaitSingle
import rx.Observable
interface CatalogueSource : Source {
/**
* An ISO 639-1 compliant language code (two letters in lower case).
*/
override val lang: String
/**
* Whether the source has support for latest updates.
*/
val supportsLatest: Boolean
/**
* Get a page with a list of manga.
*
* @since extensions-lib 1.5
* @param page the page number to retrieve.
*/
@Suppress("DEPRECATION")
suspend fun getPopularManga(page: Int): MangasPage = fetchPopularManga(page).awaitSingle()
/**
* Get a page with a list of manga.
*
* @since extensions-lib 1.5
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
@Suppress("DEPRECATION")
suspend fun getSearchManga(
page: Int,
query: String,
filters: FilterList,
): MangasPage = fetchSearchManga(page, query, filters).awaitSingle()
/**
* Get a page with a list of latest manga updates.
*
* @since extensions-lib 1.5
* @param page the page number to retrieve.
*/
@Suppress("DEPRECATION")
suspend fun getLatestUpdates(page: Int): MangasPage = fetchLatestUpdates(page).awaitSingle()
/**
* Returns the list of filters for the source.
*/
fun getFilterList(): FilterList
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getPopularManga"),
)
fun fetchPopularManga(page: Int): Observable<MangasPage> = throw IllegalStateException("Not used")
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getSearchManga"),
)
fun fetchSearchManga(
page: Int,
query: String,
filters: FilterList,
): Observable<MangasPage> = throw IllegalStateException("Not used")
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getLatestUpdates"),
)
fun fetchLatestUpdates(page: Int): Observable<MangasPage> = throw IllegalStateException("Not used")
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/ConfigurableSource.kt
- Source · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: interface ConfigurableSource : Source {
6: fun setupPreferenceScreen(screen: PreferenceScreen)
Exact file bytes / download · SHA-256 77ed8870c6ba79a7839150c3c03d18314a79bfa8c16b56ebed1a150c8a18e550.
Complete file
package eu.kanade.tachiyomi.source
import androidx.preference.PreferenceScreen
interface ConfigurableSource : Source {
fun setupPreferenceScreen(screen: PreferenceScreen)
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/LocalSource.kt
- Source · implementation · 54 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: class LocalSource(
23: override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
27: override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
31: override fun fetchPageList(chapter: SChapter): Observable<List<Page>> {
35: override fun fetchPopularManga(page: Int): Observable<MangasPage> {
39: override fun fetchSearchManga(
47: override fun fetchLatestUpdates(page: Int): Observable<MangasPage> {
51: override fun getFilterList(): FilterList {
Exact file bytes / download · SHA-256 b9a20d3090b966dd1815de33465b3e3b4576a8c8b808fa7616e8eaaa463dca5e.
Complete file
package eu.kanade.tachiyomi.source
import android.content.Context
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import rx.Observable
class LocalSource(
private val context: Context,
) : CatalogueSource {
companion object {
const val ID = 0L
}
override val id = ID
override val name = "Local source"
override val lang = ""
override val supportsLatest = true
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
TODO("Not yet implemented")
}
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
TODO("Not yet implemented")
}
override fun fetchPageList(chapter: SChapter): Observable<List<Page>> {
TODO("Not yet implemented")
}
override fun fetchPopularManga(page: Int): Observable<MangasPage> {
TODO("Not yet implemented")
}
override fun fetchSearchManga(
page: Int,
query: String,
filters: FilterList,
): Observable<MangasPage> {
TODO("Not yet implemented")
}
override fun fetchLatestUpdates(page: Int): Observable<MangasPage> {
TODO("Not yet implemented")
}
override fun getFilterList(): FilterList {
TODO("Not yet implemented")
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/Source.kt
- Source · implementation · 76 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: interface Source {
34: suspend fun getMangaDetails(manga: SManga): SManga = fetchMangaDetails(manga).awaitSingle()
44: suspend fun getChapterList(manga: SManga): List<SChapter> = fetchChapterList(manga).awaitSingle()
55: suspend fun getPageList(chapter: SChapter): List<Page> = fetchPageList(chapter).awaitSingle()
61: fun fetchMangaDetails(manga: SManga): Observable<SManga> = throw IllegalStateException("Not used")
67: fun fetchChapterList(manga: SManga): Observable<List<SChapter>> = throw IllegalStateException("Not used")
73: fun fetchPageList(chapter: SChapter): Observable<List<Page>> = throw IllegalStateException("Not used")
Exact file bytes / download · SHA-256 f4b43ef756e759bf6bb88c0667ffadffeb154ad6d547d508ba498b1634ae76c8.
Complete file
package eu.kanade.tachiyomi.source
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.util.lang.awaitSingle
import rx.Observable
/**
* A basic interface for creating a source. It could be an online source, a local source, etc.
*/
interface Source {
/**
* ID for the source. Must be unique.
*/
val id: Long
/**
* Name of the source.
*/
val name: String
val lang: String
get() = ""
/**
* Get the updated details for a manga.
*
* @since extensions-lib 1.5
* @param manga the manga to update.
* @return the updated manga.
*/
@Suppress("DEPRECATION")
suspend fun getMangaDetails(manga: SManga): SManga = fetchMangaDetails(manga).awaitSingle()
/**
* Get all the available chapters for a manga.
*
* @since extensions-lib 1.5
* @param manga the manga to update.
* @return the chapters for the manga.
*/
@Suppress("DEPRECATION")
suspend fun getChapterList(manga: SManga): List<SChapter> = fetchChapterList(manga).awaitSingle()
/**
* Get the list of pages a chapter has. Pages should be returned
* in the expected order; the index is ignored.
*
* @since extensions-lib 1.5
* @param chapter the chapter.
* @return the pages for the chapter.
*/
@Suppress("DEPRECATION")
suspend fun getPageList(chapter: SChapter): List<Page> = fetchPageList(chapter).awaitSingle()
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getMangaDetails"),
)
fun fetchMangaDetails(manga: SManga): Observable<SManga> = throw IllegalStateException("Not used")
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getChapterList"),
)
fun fetchChapterList(manga: SManga): Observable<List<SChapter>> = throw IllegalStateException("Not used")
@Deprecated(
"Use the non-RxJava API instead",
ReplaceWith("getPageList"),
)
fun fetchPageList(chapter: SChapter): Observable<List<Page>> = throw IllegalStateException("Not used")
}
// fun Source.icon(): Drawable? = Injekt.get<ExtensionManager>().getAppIconForSource(this)
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/SourceFactory.kt
- Source · implementation · 12 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: interface SourceFactory {
11: fun createSources(): List<Source>
Exact file bytes / download · SHA-256 4ff3f8e591d8d059dc665735f0cb1a7fd478c00db73e7b3928b95407c383bc44.
Complete file
package eu.kanade.tachiyomi.source
/**
* A factory for creating sources at runtime.
*/
interface SourceFactory {
/**
* Create a new copy of the sources
* @return The created sources
*/
fun createSources(): List<Source>
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/SourceManager.kt
- Source · implementation · 69 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: open class SourceManager(
21: open fun get(sourceKey: Long): Source? = sourcesMap[sourceKey]
23: fun getOrStub(sourceKey: Long): Source =
28: fun getOnlineSources() = sourcesMap.values.filterIsInstance<HttpSource>()
30: fun getCatalogueSources() = sourcesMap.values.filterIsInstance<CatalogueSource>()
32: internal fun registerSource(
44: internal fun unregisterSource(source: Source) {
48: private fun createInternalSources(): List<Source> =
59: override fun fetchMangaDetails(manga: SManga): Observable<SManga> = Observable.error(getSourceNotInstalledException())
61: override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> = Observable.error(getSourceNotInstalledException())
63: override fun fetchPageList(chapter: SChapter): Observable<List<Page>> = Observable.error(getSourceNotInstalledException())
65: override fun toString(): String = name
67: private fun getSourceNotInstalledException(): Exception = Exception("source not found")
Exact file bytes / download · SHA-256 3348db6df8f5806c4174b42716b8f581c35c53182556c9df37cfaad7ed4be4f3.
Complete file
package eu.kanade.tachiyomi.source
import android.content.Context
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import rx.Observable
open class SourceManager(
private val context: Context,
) {
private val sourcesMap = mutableMapOf<Long, Source>()
private val stubSourcesMap = mutableMapOf<Long, StubSource>()
init {
createInternalSources().forEach { registerSource(it) }
}
open fun get(sourceKey: Long): Source? = sourcesMap[sourceKey]
fun getOrStub(sourceKey: Long): Source =
sourcesMap[sourceKey] ?: stubSourcesMap.getOrPut(sourceKey) {
StubSource(sourceKey)
}
fun getOnlineSources() = sourcesMap.values.filterIsInstance<HttpSource>()
fun getCatalogueSources() = sourcesMap.values.filterIsInstance<CatalogueSource>()
internal fun registerSource(
source: Source,
overwrite: Boolean = false,
) {
if (overwrite || !sourcesMap.containsKey(source.id)) {
sourcesMap[source.id] = source
}
if (overwrite || !stubSourcesMap.containsKey(source.id)) {
stubSourcesMap[source.id] = StubSource(source.id)
}
}
internal fun unregisterSource(source: Source) {
sourcesMap.remove(source.id)
}
private fun createInternalSources(): List<Source> =
listOf(
// LocalSource(context)
)
private inner class StubSource(
override val id: Long,
) : Source {
override val name: String
get() = id.toString()
override fun fetchMangaDetails(manga: SManga): Observable<SManga> = Observable.error(getSourceNotInstalledException())
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> = Observable.error(getSourceNotInstalledException())
override fun fetchPageList(chapter: SChapter): Observable<List<Page>> = Observable.error(getSourceNotInstalledException())
override fun toString(): String = name
private fun getSourceNotInstalledException(): Exception = Exception("source not found")
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/UnmeteredSource.kt
- Source · implementation · 8 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: interface UnmeteredSource
Exact file bytes / download · SHA-256 82a01676da96d2386e6d4441ff97521a9eb1d8da8f1302beb871bd1cd7a72636.
Complete file
package eu.kanade.tachiyomi.source
/**
* A source that explicitly doesn't require traffic considerations.
*
* This typically applies for self-hosted sources.
*/
interface UnmeteredSource
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/Filter.kt
- Source · implementation · 76 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: sealed class Filter<T>(
7: open class Header(
11: open class Separator(
15: abstract class Select<V>(
21: abstract class Text(
26: abstract class CheckBox(
31: abstract class TriState(
35: fun isIgnored() = state == STATE_IGNORE
37: fun isIncluded() = state == STATE_INCLUDE
39: fun isExcluded() = state == STATE_EXCLUDE
48: abstract class Group<V>(
53: abstract class Sort(
58: data class Selection(
64: override fun equals(other: Any?): Boolean {
71: override fun hashCode(): Int {
Exact file bytes / download · SHA-256 14a9e18c52b62143a4ef90a4984bf4372713f8f9f1170faa5521c5d016d5a90b.
Complete file
package eu.kanade.tachiyomi.source.model
sealed class Filter<T>(
val name: String,
var state: T,
) {
open class Header(
name: String,
) : Filter<Any>(name, 0)
open class Separator(
name: String = "",
) : Filter<Any>(name, 0)
abstract class Select<V>(
name: String,
val values: Array<V>,
state: Int = 0,
) : Filter<Int>(name, state)
abstract class Text(
name: String,
state: String = "",
) : Filter<String>(name, state)
abstract class CheckBox(
name: String,
state: Boolean = false,
) : Filter<Boolean>(name, state)
abstract class TriState(
name: String,
state: Int = STATE_IGNORE,
) : Filter<Int>(name, state) {
fun isIgnored() = state == STATE_IGNORE
fun isIncluded() = state == STATE_INCLUDE
fun isExcluded() = state == STATE_EXCLUDE
companion object {
const val STATE_IGNORE = 0
const val STATE_INCLUDE = 1
const val STATE_EXCLUDE = 2
}
}
abstract class Group<V>(
name: String,
state: List<V>,
) : Filter<List<V>>(name, state)
abstract class Sort(
name: String,
val values: Array<String>,
state: Selection? = null,
) : Filter<Sort.Selection?>(name, state) {
data class Selection(
val index: Int,
val ascending: Boolean,
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Filter<*>) return false
return name == other.name && state == other.state
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + (state?.hashCode() ?: 0)
return result
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/FilterList.kt
- Source · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: data class FilterList(
Exact file bytes / download · SHA-256 acfdb0dcb860a67b53a40755d97c1f0df153b9a0bb50e327f3282620581ed876.
Complete file
package eu.kanade.tachiyomi.source.model
data class FilterList(
val list: List<Filter<*>>,
) : List<Filter<*>> by list {
constructor(vararg fs: Filter<*>) : this(if (fs.isNotEmpty()) fs.asList() else emptyList())
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/MangasPage.kt
- Source · implementation · 6 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: data class MangasPage(
Exact file bytes / download · SHA-256 4013fd28e85cc7e59665363fe6706f6e3ffcad153186324c50798bdce741e2b9.
Complete file
package eu.kanade.tachiyomi.source.model
data class MangasPage(
val mangas: List<SManga>,
val hasNextPage: Boolean,
)
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/Page.kt
- Source · implementation · 67 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: open class Page(
39: override fun update(
52: fun setStatusSubject(subject: Subject<Int, Int>?) {
56: fun setStatusCallback(f: ((Page) -> Unit)?) {
Exact file bytes / download · SHA-256 a3d4a528aeae6b9647a43dc5e765115d5954583dfd5a6f580cc6e44b80c2992e.
Complete file
package eu.kanade.tachiyomi.source.model
import android.net.Uri
import eu.kanade.tachiyomi.network.ProgressListener
import rx.subjects.Subject
open class Page(
val index: Int,
val url: String = "",
var imageUrl: String? = null,
@Transient var uri: Uri? = null, // Deprecated but can't be deleted due to extensions
) : ProgressListener {
val number: Int
get() = index + 1
@Transient
@Volatile
var status: Int = 0
set(value) {
field = value
statusSubject?.onNext(value)
statusCallback?.invoke(this)
}
@Transient
@Volatile
var progress: Int = 0
set(value) {
field = value
statusCallback?.invoke(this)
}
@Transient
private var statusSubject: Subject<Int, Int>? = null
@Transient
private var statusCallback: ((Page) -> Unit)? = null
override fun update(
bytesRead: Long,
contentLength: Long,
done: Boolean,
) {
progress =
if (contentLength > 0) {
(100 * bytesRead / contentLength).toInt()
} else {
-1
}
}
fun setStatusSubject(subject: Subject<Int, Int>?) {
this.statusSubject = subject
}
fun setStatusCallback(f: ((Page) -> Unit)?) {
statusCallback = f
}
companion object {
const val QUEUE = 0
const val LOAD_PAGE = 1
const val DOWNLOAD_IMAGE = 2
const val READY = 3
const val ERROR = 4
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SChapter.kt
- Source · implementation · 29 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: interface SChapter : Serializable {
18: fun copyFrom(other: SChapter) {
27: fun create(): SChapter = SChapterImpl()
Exact file bytes / download · SHA-256 412197322ae8d96a0c60ad36cbfcc95635d6224919aab7ebe1eb84a8f68ea45e.
Complete file
@file:Suppress("ktlint:standard:property-naming")
package eu.kanade.tachiyomi.source.model
import java.io.Serializable
interface SChapter : Serializable {
var url: String
var name: String
var date_upload: Long
var chapter_number: Float
var scanlator: String?
fun copyFrom(other: SChapter) {
name = other.name
url = other.url
date_upload = other.date_upload
chapter_number = other.chapter_number
scanlator = other.scanlator
}
companion object {
fun create(): SChapter = SChapterImpl()
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SChapterImpl.kt
- Source · implementation · 15 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: class SChapterImpl : SChapter {
Exact file bytes / download · SHA-256 552dffe42b4b0ab2a86fdbecb85464603684cd36619cb3441379626ee899f93b.
Complete file
@file:Suppress("ktlint:standard:property-naming")
package eu.kanade.tachiyomi.source.model
class SChapterImpl : SChapter {
override lateinit var url: String
override lateinit var name: String
override var date_upload: Long = 0
override var chapter_number: Float = -1f
override var scanlator: String? = null
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SManga.kt
- Source · implementation · 67 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: interface SManga : Serializable {
28: fun copyFrom(other: SManga) {
65: fun create(): SManga = SMangaImpl()
Exact file bytes / download · SHA-256 7e48b73d5705f2ede9221ee981d54511fc60bac481e767eea63183e910f4ee0a.
Complete file
@file:Suppress("ktlint:standard:property-naming")
package eu.kanade.tachiyomi.source.model
import java.io.Serializable
interface SManga : Serializable {
var url: String
var title: String
var artist: String?
var author: String?
var description: String?
var genre: String?
var status: Int
var thumbnail_url: String?
var update_strategy: UpdateStrategy
var initialized: Boolean
fun copyFrom(other: SManga) {
if (other.author != null) {
author = other.author
}
if (other.artist != null) {
artist = other.artist
}
if (other.description != null) {
description = other.description
}
if (other.genre != null) {
genre = other.genre
}
if (other.thumbnail_url != null) {
thumbnail_url = other.thumbnail_url
}
status = other.status
if (!initialized) {
initialized = other.initialized
}
}
companion object {
const val UNKNOWN = 0
const val ONGOING = 1
const val COMPLETED = 2
const val LICENSED = 3
const val PUBLISHING_FINISHED = 4
const val CANCELLED = 5
const val ON_HIATUS = 6
fun create(): SManga = SMangaImpl()
}
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/SMangaImpl.kt
- Source · implementation · 25 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
5: class SMangaImpl : SManga {
Exact file bytes / download · SHA-256 52cc1f96f6a53b9abdd82fd548cd551c33a091bc9afa7a05c8ec32cf788df03d.
Complete file
@file:Suppress("ktlint:standard:property-naming")
package eu.kanade.tachiyomi.source.model
class SMangaImpl : SManga {
override lateinit var url: String
override lateinit var title: String
override var artist: String? = null
override var author: String? = null
override var description: String? = null
override var genre: String? = null
override var status: Int = 0
override var thumbnail_url: String? = null
override var update_strategy: UpdateStrategy = UpdateStrategy.ALWAYS_UPDATE
override var initialized: Boolean = false
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/model/UpdateStrategy.kt
- Source · test / fixture · 6 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
3: enum class UpdateStrategy {
Exact file bytes / download · SHA-256 dbe9479f3daba20ea4f578fd8de20b7922ea2657dfebc4f23fd25570a6515ad3.
Complete file
package eu.kanade.tachiyomi.source.model
enum class UpdateStrategy {
ALWAYS_UPDATE,
ONLY_FETCH_ONCE,
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/HttpSource.kt
- Source · implementation · 391 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
26: abstract class HttpSource : CatalogueSource {
77: protected open fun headersBuilder() =
85: override fun toString() = "$name (${lang.uppercase()})"
93: override fun fetchPopularManga(page: Int): Observable<MangasPage> =
106: protected abstract fun popularMangaRequest(page: Int): Request
113: protected abstract fun popularMangaParse(response: Response): MangasPage
123: override fun fetchSearchManga(
142: protected abstract fun searchMangaRequest(
153: protected abstract fun searchMangaParse(response: Response): MangasPage
160: override fun fetchLatestUpdates(page: Int): Observable<MangasPage> =
173: protected abstract fun latestUpdatesRequest(page: Int): Request
180: protected abstract fun latestUpdatesParse(response: Response): MangasPage
188: override fun fetchMangaDetails(manga: SManga): Observable<SManga> =
202: open fun mangaDetailsRequest(manga: SManga): Request = GET(baseUrl + manga.url, headers)
209: protected abstract fun mangaDetailsParse(response: Response): SManga
217: override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> =
235: protected open fun chapterListRequest(manga: SManga): Request = GET(baseUrl + manga.url, headers)
242: protected abstract fun chapterListParse(response: Response): List<SChapter>
249: override fun fetchPageList(chapter: SChapter): Observable<List<Page>> =
263: protected open fun pageListRequest(chapter: SChapter): Request = GET(baseUrl + chapter.url, headers)
270: protected abstract fun pageListParse(response: Response): List<Page>
278: open fun fetchImageUrl(page: Page): Observable<String> =
290: protected open fun imageUrlRequest(page: Page): Request = GET(page.url, headers)
297: protected abstract fun imageUrlParse(response: Response): String
304: fun fetchImage(page: Page): Observable<Response> =
315: open fun imageRequest(page: Page): Request = GET(page.imageUrl!!, headers)
323: fun SChapter.setUrlWithoutDomain(url: String) {
333: fun SManga.setUrlWithoutDomain(url: String) {
342: private fun getUrlWithoutDomain(orig: String): String =
364: open fun getMangaUrl(manga: SManga): String = mangaDetailsRequest(manga).url.toString()
373: open fun getChapterUrl(chapter: SChapter): String = pageListRequest(chapter).url.toString()
382: open fun prepareNewChapter(
390: override fun getFilterList() = FilterList()
Exact file bytes / download · SHA-256 65d34324a54dc0264593bb1bc9951bd8cd53755c48c4b14602b35efc89ef9037.
Complete file
package eu.kanade.tachiyomi.source.online
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.network.newCallWithProgress
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.net.URI
import java.net.URISyntaxException
import java.security.MessageDigest
/**
* A simple implementation for sources from a website.
*/
abstract class HttpSource : CatalogueSource {
/**
* Network service.
*/
val network: NetworkHelper by injectLazy()
// /**
// * Preferences that a source may need.
// */
// val preferences: SharedPreferences by lazy {
// Injekt.get<Application>().getSharedPreferences(source.getPreferenceKey(), Context.MODE_PRIVATE)
// }
/**
* Base url of the website without the trailing slash, like: http://mysite.com
*/
abstract val baseUrl: String
/**
* Version id used to generate the source id. If the site completely changes and urls are
* incompatible, you may increase this value and it'll be considered as a new source.
*/
open val versionId = 1
/**
* Id of the source. By default it uses a generated id using the first 16 characters (64 bits)
* of the MD5 of the string: sourcename/language/versionId
* Note the generated id sets the sign bit to 0.
*/
override val id by lazy {
val key = "${name.lowercase()}/$lang/$versionId"
val bytes = MessageDigest.getInstance("MD5").digest(key.toByteArray())
(0..7)
.map { bytes[it].toLong() and 0xff shl 8 * (7 - it) }
.reduce(Long::or) and Long.MAX_VALUE
}
/**
* Headers used for requests.
*/
val headers: Headers by lazy { headersBuilder().build() }
/**
* Default network client for doing requests.
*/
open val client: OkHttpClient
get() = network.client
/**
* Headers builder for requests. Implementations can override this method for custom headers.
*/
protected open fun headersBuilder() =
Headers.Builder().apply {
add("User-Agent", network.defaultUserAgentProvider())
}
/**
* Visible name of the source.
*/
override fun toString() = "$name (${lang.uppercase()})"
/**
* Returns an observable containing a page with a list of manga. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
*/
override fun fetchPopularManga(page: Int): Observable<MangasPage> =
client
.newCall(popularMangaRequest(page))
.asObservableSuccess()
.map { response ->
popularMangaParse(response)
}
/**
* Returns the request for the popular manga given the page.
*
* @param page the page number to retrieve.
*/
protected abstract fun popularMangaRequest(page: Int): Request
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
protected abstract fun popularMangaParse(response: Response): MangasPage
/**
* Returns an observable containing a page with a list of manga. Normally it's not needed to
* override this method.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
override fun fetchSearchManga(
page: Int,
query: String,
filters: FilterList,
): Observable<MangasPage> =
client
.newCall(searchMangaRequest(page, query, filters))
.asObservableSuccess()
.map { response ->
searchMangaParse(response)
}
/**
* Returns the request for the search manga given the page.
*
* @param page the page number to retrieve.
* @param query the search query.
* @param filters the list of filters to apply.
*/
protected abstract fun searchMangaRequest(
page: Int,
query: String,
filters: FilterList,
): Request
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
protected abstract fun searchMangaParse(response: Response): MangasPage
/**
* Returns an observable containing a page with a list of latest manga updates.
*
* @param page the page number to retrieve.
*/
override fun fetchLatestUpdates(page: Int): Observable<MangasPage> =
client
.newCall(latestUpdatesRequest(page))
.asObservableSuccess()
.map { response ->
latestUpdatesParse(response)
}
/**
* Returns the request for latest manga given the page.
*
* @param page the page number to retrieve.
*/
protected abstract fun latestUpdatesRequest(page: Int): Request
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
protected abstract fun latestUpdatesParse(response: Response): MangasPage
/**
* Returns an observable with the updated details for a manga. Normally it's not needed to
* override this method.
*
* @param manga the manga to be updated.
*/
override fun fetchMangaDetails(manga: SManga): Observable<SManga> =
client
.newCall(mangaDetailsRequest(manga))
.asObservableSuccess()
.map { response ->
mangaDetailsParse(response).apply { initialized = true }
}
/**
* Returns the request for the details of a manga. Override only if it's needed to change the
* url, send different headers or request method like POST.
*
* @param manga the manga to be updated.
*/
open fun mangaDetailsRequest(manga: SManga): Request = GET(baseUrl + manga.url, headers)
/**
* Parses the response from the site and returns the details of a manga.
*
* @param response the response from the site.
*/
protected abstract fun mangaDetailsParse(response: Response): SManga
/**
* Returns an observable with the updated chapter list for a manga. Normally it's not needed to
* override this method. If a manga is licensed an empty chapter list observable is returned
*
* @param manga the manga to look for chapters.
*/
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> =
if (manga.status != SManga.LICENSED) {
client
.newCall(chapterListRequest(manga))
.asObservableSuccess()
.map { response ->
chapterListParse(response)
}
} else {
Observable.error(Exception("Licensed - No chapters to show"))
}
/**
* Returns the request for updating the chapter list. Override only if it's needed to override
* the url, send different headers or request method like POST.
*
* @param manga the manga to look for chapters.
*/
protected open fun chapterListRequest(manga: SManga): Request = GET(baseUrl + manga.url, headers)
/**
* Parses the response from the site and returns a list of chapters.
*
* @param response the response from the site.
*/
protected abstract fun chapterListParse(response: Response): List<SChapter>
/**
* Returns an observable with the page list for a chapter.
*
* @param chapter the chapter whose page list has to be fetched.
*/
override fun fetchPageList(chapter: SChapter): Observable<List<Page>> =
client
.newCall(pageListRequest(chapter))
.asObservableSuccess()
.map { response ->
pageListParse(response)
}
/**
* Returns the request for getting the page list. Override only if it's needed to override the
* url, send different headers or request method like POST.
*
* @param chapter the chapter whose page list has to be fetched.
*/
protected open fun pageListRequest(chapter: SChapter): Request = GET(baseUrl + chapter.url, headers)
/**
* Parses the response from the site and returns a list of pages.
*
* @param response the response from the site.
*/
protected abstract fun pageListParse(response: Response): List<Page>
/**
* Returns an observable with the page containing the source url of the image. If there's any
* error, it will return null instead of throwing an exception.
*
* @param page the page whose source image has to be fetched.
*/
open fun fetchImageUrl(page: Page): Observable<String> =
client
.newCall(imageUrlRequest(page))
.asObservableSuccess()
.map { imageUrlParse(it) }
/**
* Returns the request for getting the url to the source image. Override only if it's needed to
* override the url, send different headers or request method like POST.
*
* @param page the chapter whose page list has to be fetched
*/
protected open fun imageUrlRequest(page: Page): Request = GET(page.url, headers)
/**
* Parses the response from the site and returns the absolute url to the source image.
*
* @param response the response from the site.
*/
protected abstract fun imageUrlParse(response: Response): String
/**
* Returns an observable with the response of the source image.
*
* @param page the page whose source image has to be downloaded.
*/
fun fetchImage(page: Page): Observable<Response> =
client
.newCallWithProgress(imageRequest(page), page)
.asObservableSuccess()
/**
* Returns the request for getting the source image. Override only if it's needed to override
* the url, send different headers or request method like POST.
*
* @param page the chapter whose page list has to be fetched
*/
open fun imageRequest(page: Page): Request = GET(page.imageUrl!!, headers)
/**
* Assigns the url of the chapter without the scheme and domain. It saves some redundancy from
* database and the urls could still work after a domain change.
*
* @param url the full url to the chapter.
*/
fun SChapter.setUrlWithoutDomain(url: String) {
this.url = getUrlWithoutDomain(url)
}
/**
* Assigns the url of the manga without the scheme and domain. It saves some redundancy from
* database and the urls could still work after a domain change.
*
* @param url the full url to the manga.
*/
fun SManga.setUrlWithoutDomain(url: String) {
this.url = getUrlWithoutDomain(url)
}
/**
* Returns the url of the given string without the scheme and domain.
*
* @param orig the full url.
*/
private fun getUrlWithoutDomain(orig: String): String =
try {
val uri = URI(orig)
var out = uri.path
if (uri.query != null) {
out += "?" + uri.query
}
if (uri.fragment != null) {
out += "#" + uri.fragment
}
out
} catch (e: URISyntaxException) {
orig
}
/**
* Returns the url of the provided manga
*
* @since extensions-lib 1.4
* @param manga the manga
* @return url of the manga
*/
open fun getMangaUrl(manga: SManga): String = mangaDetailsRequest(manga).url.toString()
/**
* Returns the url of the provided chapter
*
* @since extensions-lib 1.4
* @param chapter the chapter
* @return url of the chapter
*/
open fun getChapterUrl(chapter: SChapter): String = pageListRequest(chapter).url.toString()
/**
* Called before inserting a new chapter into database. Use it if you need to override chapter
* fields, like the title or the chapter number. Do not change anything to [manga].
*
* @param chapter the chapter to be added.
* @param manga the manga of the chapter.
*/
open fun prepareNewChapter(
chapter: SChapter,
manga: SManga,
) {}
/**
* Returns the list of filters for the source.
*/
override fun getFilterList() = FilterList()
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/HttpSourceFetcher.kt
- Source · implementation · 25 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: fun HttpSource.getImageUrl(page: Page): Observable<Page> {
15: fun HttpSource.fetchAllImageUrlsFromPageList(pages: List<Page>): Observable<Page> =
21: fun HttpSource.fetchRemainingImageUrlsFromPageList(pages: List<Page>): Observable<Page> =
Exact file bytes / download · SHA-256 d1aa57e0cf7b48aa74fe72a4a3f4af73ded6cb2a01139987f0bee19bb9092ff5.
Complete file
package eu.kanade.tachiyomi.source.online
import eu.kanade.tachiyomi.source.model.Page
import rx.Observable
fun HttpSource.getImageUrl(page: Page): Observable<Page> {
page.status = Page.LOAD_PAGE
return fetchImageUrl(page)
.doOnError { page.status = Page.ERROR }
.onErrorReturn { null }
.doOnNext { page.imageUrl = it }
.map { page }
}
fun HttpSource.fetchAllImageUrlsFromPageList(pages: List<Page>): Observable<Page> =
Observable
.from(pages)
.filter { !it.imageUrl.isNullOrEmpty() }
.mergeWith(fetchRemainingImageUrlsFromPageList(pages))
fun HttpSource.fetchRemainingImageUrlsFromPageList(pages: List<Page>): Observable<Page> =
Observable
.from(pages)
.filter { it.imageUrl.isNullOrEmpty() }
.concatMap { getImageUrl(it) }
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/source/online/ParsedHttpSource.kt
- Source · implementation · 199 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
15: abstract class ParsedHttpSource : HttpSource() {
21: override fun popularMangaParse(response: Response): MangasPage {
40: protected abstract fun popularMangaSelector(): String
48: protected abstract fun popularMangaFromElement(element: Element): SManga
54: protected abstract fun popularMangaNextPageSelector(): String?
61: override fun searchMangaParse(response: Response): MangasPage {
80: protected abstract fun searchMangaSelector(): String
88: protected abstract fun searchMangaFromElement(element: Element): SManga
94: protected abstract fun searchMangaNextPageSelector(): String?
101: override fun latestUpdatesParse(response: Response): MangasPage {
120: protected abstract fun latestUpdatesSelector(): String
128: protected abstract fun latestUpdatesFromElement(element: Element): SManga
134: protected abstract fun latestUpdatesNextPageSelector(): String?
141: override fun mangaDetailsParse(response: Response): SManga = mangaDetailsParse(response.asJsoup())
148: protected abstract fun mangaDetailsParse(document: Document): SManga
155: override fun chapterListParse(response: Response): List<SChapter> {
163: protected abstract fun chapterListSelector(): String
170: protected abstract fun chapterFromElement(element: Element): SChapter
177: override fun pageListParse(response: Response): List<Page> = pageListParse(response.asJsoup())
184: protected abstract fun pageListParse(document: Document): List<Page>
191: override fun imageUrlParse(response: Response): String = imageUrlParse(response.asJsoup())
198: protected abstract fun imageUrlParse(document: Document): String
Exact file bytes / download · SHA-256 2f2a7654828318f43e0d512f6b285094e86ad8579385b104442eb56c9dda1d03.
Complete file
package eu.kanade.tachiyomi.source.online
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
/**
* A simple implementation for sources from a website using Jsoup, an HTML parser.
*/
abstract class ParsedHttpSource : HttpSource() {
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun popularMangaParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas =
document.select(popularMangaSelector()).map { element ->
popularMangaFromElement(element)
}
val hasNextPage =
popularMangaNextPageSelector()?.let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
*/
protected abstract fun popularMangaSelector(): String
/**
* Returns a manga from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [popularMangaSelector].
*/
protected abstract fun popularMangaFromElement(element: Element): SManga
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
protected abstract fun popularMangaNextPageSelector(): String?
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun searchMangaParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas =
document.select(searchMangaSelector()).map { element ->
searchMangaFromElement(element)
}
val hasNextPage =
searchMangaNextPageSelector()?.let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
*/
protected abstract fun searchMangaSelector(): String
/**
* Returns a manga from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [searchMangaSelector].
*/
protected abstract fun searchMangaFromElement(element: Element): SManga
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
protected abstract fun searchMangaNextPageSelector(): String?
/**
* Parses the response from the site and returns a [MangasPage] object.
*
* @param response the response from the site.
*/
override fun latestUpdatesParse(response: Response): MangasPage {
val document = response.asJsoup()
val mangas =
document.select(latestUpdatesSelector()).map { element ->
latestUpdatesFromElement(element)
}
val hasNextPage =
latestUpdatesNextPageSelector()?.let { selector ->
document.select(selector).first()
} != null
return MangasPage(mangas, hasNextPage)
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each manga.
*/
protected abstract fun latestUpdatesSelector(): String
/**
* Returns a manga from the given [element]. Most sites only show the title and the url, it's
* totally fine to fill only those two values.
*
* @param element an element obtained from [latestUpdatesSelector].
*/
protected abstract fun latestUpdatesFromElement(element: Element): SManga
/**
* Returns the Jsoup selector that returns the <a> tag linking to the next page, or null if
* there's no next page.
*/
protected abstract fun latestUpdatesNextPageSelector(): String?
/**
* Parses the response from the site and returns the details of a manga.
*
* @param response the response from the site.
*/
override fun mangaDetailsParse(response: Response): SManga = mangaDetailsParse(response.asJsoup())
/**
* Returns the details of the manga from the given [document].
*
* @param document the parsed document.
*/
protected abstract fun mangaDetailsParse(document: Document): SManga
/**
* Parses the response from the site and returns a list of chapters.
*
* @param response the response from the site.
*/
override fun chapterListParse(response: Response): List<SChapter> {
val document = response.asJsoup()
return document.select(chapterListSelector()).map { chapterFromElement(it) }
}
/**
* Returns the Jsoup selector that returns a list of [Element] corresponding to each chapter.
*/
protected abstract fun chapterListSelector(): String
/**
* Returns a chapter from the given element.
*
* @param element an element obtained from [chapterListSelector].
*/
protected abstract fun chapterFromElement(element: Element): SChapter
/**
* Parses the response from the site and returns the page list.
*
* @param response the response from the site.
*/
override fun pageListParse(response: Response): List<Page> = pageListParse(response.asJsoup())
/**
* Returns a page list from the given document.
*
* @param document the parsed document.
*/
protected abstract fun pageListParse(document: Document): List<Page>
/**
* Parse the response from the site and returns the absolute url to the source image.
*
* @param response the response from the site.
*/
override fun imageUrlParse(response: Response): String = imageUrlParse(response.asJsoup())
/**
* Returns the absolute url to the source image from the document.
*
* @param document the parsed document.
*/
protected abstract fun imageUrlParse(document: Document): String
}
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/util/JsoupExtensions.kt
- Source · implementation · 24 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: fun Element.selectText(
13: fun Element.selectInt(
18: fun Element.attrOrText(css: String): String = if (css != "text") attr(css) else text()
24: fun Response.asJsoup(html: String? = null): Document = Jsoup.parse(html ?: body.string(), request.url.toString())
Exact file bytes / download · SHA-256 770eea6f3effe8d635de8af53766fcbe24c0d21184ba1fce5509e925b8cbb304.
Complete file
package eu.kanade.tachiyomi.util
import okhttp3.Response
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
fun Element.selectText(
css: String,
defaultValue: String? = null,
): String? = select(css).first()?.text() ?: defaultValue
fun Element.selectInt(
css: String,
defaultValue: Int = 0,
): Int = select(css).first()?.text()?.toInt() ?: defaultValue
fun Element.attrOrText(css: String): String = if (css != "text") attr(css) else text()
/**
* Returns a Jsoup document for this response.
* @param html the body of the response. Use only if the body was read before calling this method.
*/
fun Response.asJsoup(html: String? = null): Document = Jsoup.parse(html ?: body.string(), request.url.toString())
vendor/yokan-ext/src/androidMain/kotlin/eu/kanade/tachiyomi/util/lang/CoroutinesExtensions.kt
- Source · implementation · 63 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
19: suspend fun <T> Observable<T>.awaitSingle(): T = single().awaitOne()
22: private suspend fun <T> Observable<T>.awaitOne(): T =
26: object : Subscriber<T>() {
27: override fun onStart() {
31: override fun onNext(t: T) {
35: override fun onCompleted() {
45: override fun onError(e: Throwable) {
61: private fun <T> CancellableContinuation<T>.unsubscribeOnCancellation(sub: Subscription) = invokeOnCancellation { sub.unsubscribe() }
63: suspend fun <T> withIOContext(block: suspend CoroutineScope.() -> T) = withContext(Dispatchers.IO, block)
Exact file bytes / download · SHA-256 cf6c986b60fda735b04db4251184cc49fa5ab0860c92fffd3c6bc8b5a4410ac9.
Complete file
package eu.kanade.tachiyomi.util.lang
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import rx.Observable
import rx.Subscriber
import rx.Subscription
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/*
* Util functions for bridging RxJava and coroutines. Taken from TachiyomiEH/SY.
*/
suspend fun <T> Observable<T>.awaitSingle(): T = single().awaitOne()
@OptIn(InternalCoroutinesApi::class)
private suspend fun <T> Observable<T>.awaitOne(): T =
suspendCancellableCoroutine { cont ->
cont.unsubscribeOnCancellation(
subscribe(
object : Subscriber<T>() {
override fun onStart() {
request(1)
}
override fun onNext(t: T) {
cont.resume(t)
}
override fun onCompleted() {
if (cont.isActive) {
cont.resumeWithException(
IllegalStateException(
"Should have invoked onNext",
),
)
}
}
override fun onError(e: Throwable) {
/*
* Rx1 observable throws NoSuchElementException if cancellation happened before
* element emission. To mitigate this we try to atomically resume continuation with exception:
* if resume failed, then we know that continuation successfully cancelled itself
*/
val token = cont.tryResumeWithException(e)
if (token != null) {
cont.completeResume(token)
}
}
},
),
)
}
private fun <T> CancellableContinuation<T>.unsubscribeOnCancellation(sub: Subscription) = invokeOnCancellation { sub.unsubscribe() }
suspend fun <T> withIOContext(block: suspend CoroutineScope.() -> T) = withContext(Dispatchers.IO, block)
vendor/yokan-ext/src/commonMain/kotlin/eu/friedcutlet/yokan/ext/ExtensionServer.kt
- Source · implementation · 51 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: interface ExtensionServer {
9: suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus
11: suspend fun stop(): ExtensionServerStatus
14: data class ExtensionServerConfig(
26: enum class ExtensionServerPhase {
34: data class ExtensionServerStatus(
47: class ExtensionServerException(
Exact file bytes / download · SHA-256 1f9403b319462a11a04b6d74576d960b20b3cd9ce3029942de182edd37adfed9.
Complete file
package eu.friedcutlet.yokan.ext
import kotlinx.coroutines.flow.StateFlow
/** Lifecycle shared by the embedded Android bridge and JVM-backed desktop/iOS servers. */
interface ExtensionServer {
val status: StateFlow<ExtensionServerStatus>
suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus
suspend fun stop(): ExtensionServerStatus
}
data class ExtensionServerConfig(
val port: Int,
val jvmPath: String? = null,
val serverJarPath: String? = null,
) {
init {
require(port in 1..65535) { "Port must be between 1 and 65535" }
}
val baseUrl: String get() = "http://127.0.0.1:$port"
}
enum class ExtensionServerPhase {
Stopped,
Starting,
Running,
Stopping,
Failed,
}
data class ExtensionServerStatus(
val phase: ExtensionServerPhase,
val port: Int? = null,
val message: String = "",
) {
val isRunning: Boolean get() = phase == ExtensionServerPhase.Running
val baseUrl: String? get() = port?.let { "http://127.0.0.1:$it" }
companion object {
val Stopped = ExtensionServerStatus(ExtensionServerPhase.Stopped)
}
}
class ExtensionServerException(
val code: String,
message: String,
cause: Throwable? = null,
) : IllegalStateException(message, cause)
vendor/yokan-ext/src/commonMain/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerRelease.kt
- Source · implementation · 118 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
11: data class ExtensionServerRelease(
17: data class ExtensionServerReleaseAsset(
24: data class InstalledExtensionServerBundle(
31: enum class ExtensionServerHostOs { Windows, MacOs, Linux, Ios }
32: enum class ExtensionServerHostArch { X64, Arm64 }
34: data class ExtensionServerHost(
39: fun parseExtensionServerRelease(json: String): ExtensionServerRelease {
56: fun ExtensionServerRelease.selectBundle(host: ExtensionServerHost): ExtensionServerReleaseAsset {
78: fun ExtensionServerRelease.trustedSha256(asset: ExtensionServerReleaseAsset): String {
98: private fun unsupported(host: ExtensionServerHost): Nothing = throw ExtensionServerException(
106: private data class GitHubReleasePayload(
113: private data class GitHubReleaseAssetPayload(
Exact file bytes / download · SHA-256 7caca626f3fff8c359034e1c355c085d05b65611b6df977df1e833abd4888c81.
Complete file
package eu.friedcutlet.yokan.ext
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
const val ExtensionServerLatestReleaseUrl =
"https://api.github.com/repos/kodjodevf/M-Extension-Server/releases/latest"
@Serializable
data class ExtensionServerRelease(
val version: String,
val assets: List<ExtensionServerReleaseAsset>,
)
@Serializable
data class ExtensionServerReleaseAsset(
val name: String,
val downloadUrl: String,
val size: Long,
val sha256: String?,
)
data class InstalledExtensionServerBundle(
val version: String,
val rootPath: String,
val jvmPath: String,
val serverJarPath: String,
)
enum class ExtensionServerHostOs { Windows, MacOs, Linux, Ios }
enum class ExtensionServerHostArch { X64, Arm64 }
data class ExtensionServerHost(
val os: ExtensionServerHostOs,
val arch: ExtensionServerHostArch,
)
fun parseExtensionServerRelease(json: String): ExtensionServerRelease {
val payload = releaseJson.decodeFromString<GitHubReleasePayload>(json)
val version = payload.tagName.ifBlank { payload.name.orEmpty() }.removePrefix("v")
require(version.isNotBlank()) { "GitHub release has no version" }
return ExtensionServerRelease(
version = version,
assets = payload.assets.map { asset ->
ExtensionServerReleaseAsset(
name = asset.name,
downloadUrl = asset.browserDownloadUrl,
size = asset.size,
sha256 = asset.digest?.removePrefix("sha256:")?.lowercase()?.takeIf { it.length == 64 },
)
},
)
}
fun ExtensionServerRelease.selectBundle(host: ExtensionServerHost): ExtensionServerReleaseAsset {
val expected = when (host.os) {
ExtensionServerHostOs.Windows -> when (host.arch) {
ExtensionServerHostArch.X64 -> "windows-x64-bundle.zip"
ExtensionServerHostArch.Arm64 -> unsupported(host)
}
ExtensionServerHostOs.MacOs -> when (host.arch) {
ExtensionServerHostArch.X64 -> "macOS-x64-bundle.zip"
ExtensionServerHostArch.Arm64 -> "macOS-arm64-bundle.zip"
}
ExtensionServerHostOs.Linux -> when (host.arch) {
ExtensionServerHostArch.X64 -> "linux-x64-bundle.zip"
ExtensionServerHostArch.Arm64 -> unsupported(host)
}
// The upstream server has no iOS build. Sideloaded iOS embeds its own
// signed runtime and uses the architecture-independent JAR from this bundle.
ExtensionServerHostOs.Ios -> "macOS-arm64-bundle.zip"
}
return assets.firstOrNull { it.name.equals(expected, ignoreCase = true) }
?: throw ExtensionServerException("ASSET_MISSING", "Release $version has no $expected asset")
}
fun ExtensionServerRelease.trustedSha256(asset: ExtensionServerReleaseAsset): String {
val key = "${version.removePrefix("v")}/${asset.name.lowercase()}"
return trustedExtensionServerDigests[key]
?: throw ExtensionServerException(
"UNTRUSTED_RELEASE",
"Extension server ${version}/${asset.name} is not trusted by this Yokan build; update Yokan before installing it",
)
}
private val trustedExtensionServerDigests = mapOf(
"1.0.4/linux-x64-bundle.zip" to "cb0076ebab3dd3cd42c7fcb0f15f8b34655cade7f6f3d5e547c3ea015dd491a8",
"1.0.4/macos-arm64-bundle.zip" to "30a3f039b213c9e1075572e6e2d3eba533888f6b393ba8633a0128e43187c326",
"1.0.4/macos-x64-bundle.zip" to "5fd0c4bb91ecd3fbdbd0f5d2145aa2cfe8162633be5dfa597a6791e5120d2be4",
"1.0.4/windows-x64-bundle.zip" to "4bdd8e068914a769b4ff132080210d2a8be806e9c401a577dd700cb662a302ee",
"1.0.5/linux-x64-bundle.zip" to "1e46a75576776c8c71ff83326238bea779fcfd1f31626557d291c141310b96fe",
"1.0.5/macos-arm64-bundle.zip" to "2fc07c86d1d9598bb8e15835bfd1b39db5948c2048c83e05f2d1171f267eeb5f",
"1.0.5/macos-x64-bundle.zip" to "32319f151b9a9ebae418b2df175c656746e32c8fc04efade40bf41094c83d398",
"1.0.5/windows-x64-bundle.zip" to "dd00a09b4fc23db23ab1a1f629e2d1d363f1bb67cd34c48e8505d82b2417b210",
)
private fun unsupported(host: ExtensionServerHost): Nothing = throw ExtensionServerException(
"UNSUPPORTED_PLATFORM",
"No extension server bundle is published for ${host.os}/${host.arch}",
)
private val releaseJson = Json { ignoreUnknownKeys = true }
@Serializable
private data class GitHubReleasePayload(
@SerialName("tag_name") val tagName: String = "",
val name: String? = null,
val assets: List<GitHubReleaseAssetPayload> = emptyList(),
)
@Serializable
private data class GitHubReleaseAssetPayload(
val name: String,
@SerialName("browser_download_url") val browserDownloadUrl: String,
val size: Long = 0,
val digest: String? = null,
)
vendor/yokan-ext/src/commonTest/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerContractTest.kt
- Source · test / fixture · 25 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class ExtensionServerContractTest {
9: fun configBuildsLoopbackUrl() {
14: fun configRejectsInvalidPorts() {
20: fun runningStatusExposesLoopbackUrl() {
Exact file bytes / download · SHA-256 77292e00d11288cb16b616f79e4e7d6dd9f74b8c17993180df168af43eb1267d.
Complete file
package eu.friedcutlet.yokan.ext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class ExtensionServerContractTest {
@Test
fun configBuildsLoopbackUrl() {
assertEquals("http://127.0.0.1:8080", ExtensionServerConfig(8080).baseUrl)
}
@Test
fun configRejectsInvalidPorts() {
assertFailsWith<IllegalArgumentException> { ExtensionServerConfig(0) }
assertFailsWith<IllegalArgumentException> { ExtensionServerConfig(65536) }
}
@Test
fun runningStatusExposesLoopbackUrl() {
val status = ExtensionServerStatus(ExtensionServerPhase.Running, 43123)
assertEquals(true, status.isRunning)
assertEquals("http://127.0.0.1:43123", status.baseUrl)
}
}
vendor/yokan-ext/src/commonTest/kotlin/eu/friedcutlet/yokan/ext/ExtensionServerReleaseTest.kt
- Source · test / fixture · 73 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class ExtensionServerReleaseTest {
19: fun parsesVersionDigestAndAssetMetadata() {
26: fun resolvesDigestFromBuildTrustedAllowlist() {
41: fun rejectsReleaseMissingFromBuildTrustedAllowlist() {
49: fun selectsExactHostAsset() {
54: fun selectsArchitectureIndependentJarBundleForIos() {
61: fun rejectsUnavailableHostAsset() {
68: fun rejectsUnsupportedArchitecture() {
Exact file bytes / download · SHA-256 78334eedd5dad33300ea51fd4785edd6ff0415b9b08c444bf0901deecae8160c.
Complete file
package eu.friedcutlet.yokan.ext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class ExtensionServerReleaseTest {
private val release = parseExtensionServerRelease(
"""{
"tag_name":"v1.2.3",
"assets":[
{"name":"macOS-arm64-bundle.zip","browser_download_url":"https://example.test/mac.zip","size":12,"digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"name":"windows-x64-bundle.zip","browser_download_url":"https://example.test/win.zip","size":20,"digest":"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}
]
}""",
)
@Test
fun parsesVersionDigestAndAssetMetadata() {
assertEquals("1.2.3", release.version)
assertEquals(12, release.assets.first().size)
assertEquals("a".repeat(64), release.assets.first().sha256)
}
@Test
fun resolvesDigestFromBuildTrustedAllowlist() {
val asset = ExtensionServerReleaseAsset(
name = "macOS-arm64-bundle.zip",
downloadUrl = "https://example.test/attacker-controlled.zip",
size = 1,
sha256 = "0".repeat(64),
)
assertEquals(
"2fc07c86d1d9598bb8e15835bfd1b39db5948c2048c83e05f2d1171f267eeb5f",
ExtensionServerRelease("1.0.5", listOf(asset)).trustedSha256(asset),
)
}
@Test
fun rejectsReleaseMissingFromBuildTrustedAllowlist() {
val asset = release.assets.first()
val error = assertFailsWith<ExtensionServerException> { release.trustedSha256(asset) }
assertEquals("UNTRUSTED_RELEASE", error.code)
}
@Test
fun selectsExactHostAsset() {
val selected = release.selectBundle(ExtensionServerHost(ExtensionServerHostOs.MacOs, ExtensionServerHostArch.Arm64))
assertEquals("macOS-arm64-bundle.zip", selected.name)
}
@Test
fun selectsArchitectureIndependentJarBundleForIos() {
val selected = release.selectBundle(ExtensionServerHost(ExtensionServerHostOs.Ios, ExtensionServerHostArch.Arm64))
assertEquals("macOS-arm64-bundle.zip", selected.name)
}
@Test
fun rejectsUnavailableHostAsset() {
assertFailsWith<ExtensionServerException> {
release.selectBundle(ExtensionServerHost(ExtensionServerHostOs.Linux, ExtensionServerHostArch.X64))
}
}
@Test
fun rejectsUnsupportedArchitecture() {
assertFailsWith<ExtensionServerException> {
release.selectBundle(ExtensionServerHost(ExtensionServerHostOs.Windows, ExtensionServerHostArch.Arm64))
}
}
}
vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServer.kt
- Source · implementation · 115 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
16: class DesktopExtensionServer(private val dataDir: File? = null) : ExtensionServer {
24: override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock {
61: override suspend fun stop(): ExtensionServerStatus = lock.withLock { stopLocked() }
63: private suspend fun stopLocked(): ExtensionServerStatus {
83: internal fun resolveJavaExecutable(rawPath: String?): String {
99: private fun javaBinaryName(): String = if (System.getProperty("os.name").contains("win", ignoreCase = true)) "java.exe" else "java"
101: private fun fail(code: String, message: String, cause: Throwable? = null): ExtensionServerException {
107: internal fun desktopExtensionServerCommand(java: String, jar: File, port: Int, dataDir: File?): List<String> =
Exact file bytes / download · SHA-256 394140a48e7cf1d73f3f22253ec949afd9215bf6eb513b831e81dc522108831c.
Complete file
package eu.friedcutlet.yokan.ext
import java.io.File
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
/**
* [dataDir] confines the server JVM's home, temp and working directories (the server keeps
* source preferences and caches there); null keeps the inherited legacy locations.
*/
class DesktopExtensionServer(private val dataDir: File? = null) : ExtensionServer {
private val lock = Mutex()
private val mutableStatus = MutableStateFlow(ExtensionServerStatus.Stopped)
private var process: Process? = null
private var activeConfig: ExtensionServerConfig? = null
override val status: StateFlow<ExtensionServerStatus> = mutableStatus
override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock {
val running = process?.isAlive == true
if (running && activeConfig == config) return mutableStatus.value
stopLocked()
val jar = config.serverJarPath?.takeIf { it.isNotBlank() }?.let(::File)
?: throw fail("MISSING_JAR", "An extension server JAR is required on desktop")
if (!jar.isFile) throw fail("MISSING_JAR", "Extension server JAR does not exist: ${jar.path}")
val java = resolveJavaExecutable(config.jvmPath)
mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Starting, config.port, "Starting local extension server")
val launched = withContext(Dispatchers.IO) {
runCatching {
dataDir?.let { File(it, "tmp").mkdirs() }
ProcessBuilder(desktopExtensionServerCommand(java, jar, config.port, dataDir))
.directory(dataDir)
.redirectInput(ProcessBuilder.Redirect.PIPE)
.redirectOutput(ProcessBuilder.Redirect.DISCARD)
.redirectError(ProcessBuilder.Redirect.DISCARD)
.start()
}
}.getOrElse { error ->
throw fail("START_ERROR", "Failed to launch extension server with $java: ${error.message.orEmpty()}", error)
}
process = launched
activeConfig = config
mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Running, config.port, "Server started on port ${config.port}")
launched.onExit().thenRun {
if (process === launched) {
process = null
activeConfig = null
mutableStatus.value = ExtensionServerStatus.Stopped.copy(message = "Extension server exited")
}
}
mutableStatus.value
}
override suspend fun stop(): ExtensionServerStatus = lock.withLock { stopLocked() }
private suspend fun stopLocked(): ExtensionServerStatus {
val current = process
if (current == null || !current.isAlive) {
process = null
activeConfig = null
return ExtensionServerStatus.Stopped.also { mutableStatus.value = it }
}
mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Stopping, activeConfig?.port, "Stopping extension server")
withContext(Dispatchers.IO) {
current.destroy()
if (!current.waitFor(5, TimeUnit.SECONDS)) {
current.destroyForcibly()
current.waitFor(5, TimeUnit.SECONDS)
}
}
process = null
activeConfig = null
return ExtensionServerStatus.Stopped.copy(message = "Server stopped").also { mutableStatus.value = it }
}
internal fun resolveJavaExecutable(rawPath: String?): String {
val explicit = rawPath?.trim()?.takeIf { it.isNotEmpty() }
if (explicit != null) {
val path = File(explicit)
val executable = if (path.isDirectory) File(path, "bin/${javaBinaryName()}") else path
if (!executable.isFile) throw fail("MISSING_JAVA", "Java executable does not exist: ${executable.path}")
return executable.absolutePath
}
val javaHome = System.getenv("JAVA_HOME")?.takeIf { it.isNotBlank() }
if (javaHome != null) {
val executable = File(javaHome, "bin/${javaBinaryName()}")
if (executable.isFile) return executable.absolutePath
}
return javaBinaryName()
}
private fun javaBinaryName(): String = if (System.getProperty("os.name").contains("win", ignoreCase = true)) "java.exe" else "java"
private fun fail(code: String, message: String, cause: Throwable? = null): ExtensionServerException {
mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Failed, activeConfig?.port, message)
return ExtensionServerException(code, message, cause)
}
}
internal fun desktopExtensionServerCommand(java: String, jar: File, port: Int, dataDir: File?): List<String> =
listOfNotNull(
java,
dataDir?.let { "-Duser.home=${it.absolutePath}" },
dataDir?.let { "-Djava.io.tmpdir=${File(it, "tmp").absolutePath}" },
"-jar",
jar.absolutePath,
port.toString(),
)
vendor/yokan-ext/src/desktopMain/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerInstaller.kt
- Source · implementation · 205 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
19: class DesktopExtensionServerInstaller(
26: suspend fun discoverLatest(): ExtensionServerRelease = withContext(Dispatchers.IO) {
42: suspend fun installLatest(
49: suspend fun install(
78: fun installedBundle(version: String): InstalledExtensionServerBundle? {
84: fun detectBundle(directory: Path): InstalledExtensionServerBundle {
90: private fun download(
123: private fun verifySha256(path: Path, expected: String?) {
140: private fun extractZip(archive: Path, destination: Path) {
159: private fun resolveBundle(root: Path, version: String): InstalledExtensionServerBundle {
172: private fun makeJavaExecutable(path: String) {
181: private fun deleteRecursively(path: Path) {
190: fun currentDesktopHost(): ExtensionServerHost {
Exact file bytes / download · SHA-256 1b360f08d8ec09addec8ae174a8c274be0d061feb5c4c79c331a187de905d9f1.
Complete file
package eu.friedcutlet.yokan.ext
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.nio.file.attribute.PosixFilePermission
import java.security.MessageDigest
import java.time.Duration
import java.util.zip.ZipInputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class DesktopExtensionServerInstaller(
private val installRoot: Path,
private val httpClient: HttpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(30))
.followRedirects(HttpClient.Redirect.NORMAL)
.build(),
) {
suspend fun discoverLatest(): ExtensionServerRelease = withContext(Dispatchers.IO) {
val request = HttpRequest.newBuilder(URI.create(ExtensionServerLatestReleaseUrl))
.header("Accept", "application/vnd.github+json")
.header("User-Agent", "Yokan")
.GET()
.build()
val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString())
if (response.statusCode() !in 200..299) {
throw ExtensionServerException(
"RELEASE_HTTP_ERROR",
"GitHub release request failed with HTTP ${response.statusCode()}",
)
}
parseExtensionServerRelease(response.body())
}
suspend fun installLatest(
onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> },
): InstalledExtensionServerBundle {
val release = discoverLatest()
return install(release, release.selectBundle(currentDesktopHost()), onProgress)
}
suspend fun install(
release: ExtensionServerRelease,
asset: ExtensionServerReleaseAsset,
onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> },
): InstalledExtensionServerBundle = withContext(Dispatchers.IO) {
require(asset.name.endsWith(".zip", ignoreCase = true)) { "Only ZIP bundles are supported" }
Files.createDirectories(installRoot)
val archive = Files.createTempFile(installRoot, ".download-", ".zip")
val staging = Files.createTempDirectory(installRoot, ".install-")
val finalDirectory = installRoot.resolve(release.version)
try {
download(asset, archive, onProgress)
verifySha256(archive, asset.sha256)
extractZip(archive, staging)
val bundle = resolveBundle(staging, release.version)
makeJavaExecutable(bundle.jvmPath)
deleteRecursively(finalDirectory)
try {
Files.move(staging, finalDirectory, StandardCopyOption.ATOMIC_MOVE)
} catch (_: Exception) {
Files.move(staging, finalDirectory)
}
resolveBundle(finalDirectory, release.version)
} finally {
Files.deleteIfExists(archive)
deleteRecursively(staging)
}
}
fun installedBundle(version: String): InstalledExtensionServerBundle? {
val directory = installRoot.resolve(version)
if (!Files.isDirectory(directory)) return null
return runCatching { resolveBundle(directory, version) }.getOrNull()
}
fun detectBundle(directory: Path): InstalledExtensionServerBundle {
require(Files.isDirectory(directory)) { "Selected extension server location is not a directory: $directory" }
return resolveBundle(directory, directory.fileName?.toString().orEmpty().ifBlank { "manual" })
.also { makeJavaExecutable(it.jvmPath) }
}
private fun download(
asset: ExtensionServerReleaseAsset,
target: Path,
onProgress: (Long, Long) -> Unit,
) {
val request = HttpRequest.newBuilder(URI.create(asset.downloadUrl))
.header("Accept", "application/octet-stream")
.header("User-Agent", "Yokan")
.GET()
.build()
val response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream())
if (response.statusCode() !in 200..299) {
response.body().close()
throw ExtensionServerException("DOWNLOAD_HTTP_ERROR", "Bundle download failed with HTTP ${response.statusCode()}")
}
val expected = response.headers().firstValueAsLong("content-length").orElse(asset.size)
response.body().use { source ->
BufferedInputStream(source).use { input ->
BufferedOutputStream(Files.newOutputStream(target)).use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var downloaded = 0L
while (true) {
val count = input.read(buffer)
if (count < 0) break
output.write(buffer, 0, count)
downloaded += count
onProgress(downloaded, expected)
}
}
}
}
}
private fun verifySha256(path: Path, expected: String?) {
if (expected == null) throw ExtensionServerException("MISSING_DIGEST", "Release asset has no SHA-256 digest")
val digest = MessageDigest.getInstance("SHA-256")
Files.newInputStream(path).use { input ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
val count = input.read(buffer)
if (count < 0) break
digest.update(buffer, 0, count)
}
}
val actual = digest.digest().joinToString("") { byte -> "%02x".format(byte) }
if (!actual.equals(expected, ignoreCase = true)) {
throw ExtensionServerException("DIGEST_MISMATCH", "Bundle SHA-256 mismatch: expected $expected, received $actual")
}
}
private fun extractZip(archive: Path, destination: Path) {
ZipInputStream(BufferedInputStream(Files.newInputStream(archive))).use { zip ->
while (true) {
val entry = zip.nextEntry ?: break
val target = destination.resolve(entry.name).normalize()
if (!target.startsWith(destination)) {
throw ExtensionServerException("UNSAFE_ARCHIVE", "Bundle contains a path outside its install directory")
}
if (entry.isDirectory) {
Files.createDirectories(target)
} else {
Files.createDirectories(target.parent)
BufferedOutputStream(Files.newOutputStream(target)).use { output -> zip.copyTo(output) }
}
zip.closeEntry()
}
}
}
private fun resolveBundle(root: Path, version: String): InstalledExtensionServerBundle {
val allFiles = Files.walk(root).use { paths -> paths.filter(Files::isRegularFile).toList() }
val jar = allFiles.firstOrNull { path ->
val name = path.fileName.toString()
name.endsWith(".jar", ignoreCase = true) && name.contains("ExtensionServer", ignoreCase = true)
} ?: throw ExtensionServerException("MISSING_JAR", "Downloaded bundle contains no extension server JAR")
val javaName = if (currentDesktopHost().os == ExtensionServerHostOs.Windows) "java.exe" else "java"
val java = allFiles.firstOrNull { path ->
path.fileName.toString().equals(javaName, ignoreCase = true) && path.parent?.fileName?.toString() == "bin"
} ?: throw ExtensionServerException("MISSING_JAVA", "Downloaded bundle contains no Java executable")
return InstalledExtensionServerBundle(version, root.toAbsolutePath().toString(), java.toAbsolutePath().toString(), jar.toAbsolutePath().toString())
}
private fun makeJavaExecutable(path: String) {
val java = Path.of(path)
runCatching {
val permissions = Files.getPosixFilePermissions(java).toMutableSet()
permissions += PosixFilePermission.OWNER_EXECUTE
Files.setPosixFilePermissions(java, permissions)
}.getOrElse { java.toFile().setExecutable(true, true) }
}
private fun deleteRecursively(path: Path) {
if (!Files.exists(path)) return
Files.walk(path).use { paths ->
paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists)
}
}
}
fun currentDesktopHost(): ExtensionServerHost {
val osName = System.getProperty("os.name").lowercase()
val os = when {
"win" in osName -> ExtensionServerHostOs.Windows
"mac" in osName || "darwin" in osName -> ExtensionServerHostOs.MacOs
"linux" in osName -> ExtensionServerHostOs.Linux
else -> throw ExtensionServerException("UNSUPPORTED_PLATFORM", "Unsupported desktop OS: $osName")
}
val archName = System.getProperty("os.arch").lowercase()
val arch = when (archName) {
"x86_64", "amd64" -> ExtensionServerHostArch.X64
"aarch64", "arm64" -> ExtensionServerHostArch.Arm64
else -> throw ExtensionServerException("UNSUPPORTED_PLATFORM", "Unsupported desktop architecture: $archName")
}
return ExtensionServerHost(os, arch)
}
vendor/yokan-ext/src/desktopTest/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerInstallerTest.kt
- Source · test / fixture · 103 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
16: class DesktopExtensionServerInstallerTest {
18: fun verifiesExtractsAndResolvesBundle() = runTest {
45: fun rejectsDigestMismatchWithoutInstallingVersion() = runTest {
68: private fun createBundleArchive(root: java.nio.file.Path): java.nio.file.Path {
83: private fun serveFile(path: java.nio.file.Path): HttpServer {
94: private fun sha256(path: java.nio.file.Path): String {
99: private fun deleteRecursively(path: java.nio.file.Path) {
Exact file bytes / download · SHA-256 b95f74c4ba408c1d544cf70c019b96d626efd8b4fd66e2ff51709f152dfd9962.
Complete file
package eu.friedcutlet.yokan.ext
import com.sun.net.httpserver.HttpServer
import java.net.InetSocketAddress
import java.nio.file.Files
import java.security.MessageDigest
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlinx.coroutines.test.runTest
import kotlin.io.path.exists
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class DesktopExtensionServerInstallerTest {
@Test
fun verifiesExtractsAndResolvesBundle() = runTest {
val root = Files.createTempDirectory("yokan-ext-installer-")
val archive = createBundleArchive(root)
val server = serveFile(archive)
try {
val asset = ExtensionServerReleaseAsset(
name = "test-bundle.zip",
downloadUrl = "http://127.0.0.1:${server.address.port}/bundle.zip",
size = Files.size(archive),
sha256 = sha256(archive),
)
val release = ExtensionServerRelease("9.9.9", listOf(asset))
val progress = mutableListOf<Long>()
val bundle = DesktopExtensionServerInstaller(root.resolve("installed"))
.install(release, asset) { downloaded, _ -> progress += downloaded }
assertEquals("9.9.9", bundle.version)
assertTrue(Files.isRegularFile(java.nio.file.Path.of(bundle.serverJarPath)))
assertTrue(Files.isRegularFile(java.nio.file.Path.of(bundle.jvmPath)))
assertTrue(progress.last() == asset.size)
} finally {
server.stop(0)
deleteRecursively(root)
}
}
@Test
fun rejectsDigestMismatchWithoutInstallingVersion() = runTest {
val root = Files.createTempDirectory("yokan-ext-digest-")
val archive = createBundleArchive(root)
val server = serveFile(archive)
try {
val asset = ExtensionServerReleaseAsset(
"test-bundle.zip",
"http://127.0.0.1:${server.address.port}/bundle.zip",
Files.size(archive),
"0".repeat(64),
)
val installer = DesktopExtensionServerInstaller(root.resolve("installed"))
val error = assertFailsWith<ExtensionServerException> {
installer.install(ExtensionServerRelease("1.0.0", listOf(asset)), asset)
}
assertEquals("DIGEST_MISMATCH", error.code)
assertTrue(!root.resolve("installed/1.0.0").exists())
} finally {
server.stop(0)
deleteRecursively(root)
}
}
private fun createBundleArchive(root: java.nio.file.Path): java.nio.file.Path {
val archive = root.resolve("bundle.zip")
ZipOutputStream(Files.newOutputStream(archive)).use { zip ->
mapOf(
"bundle/jre/bin/${if (System.getProperty("os.name").contains("win", true)) "java.exe" else "java"}" to "fake java",
"bundle/MExtensionServer.jar" to "fake jar",
).forEach { (name, content) ->
zip.putNextEntry(ZipEntry(name))
zip.write(content.encodeToByteArray())
zip.closeEntry()
}
}
return archive
}
private fun serveFile(path: java.nio.file.Path): HttpServer {
val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
server.createContext("/bundle.zip") { exchange ->
val bytes = Files.readAllBytes(path)
exchange.sendResponseHeaders(200, bytes.size.toLong())
exchange.responseBody.use { it.write(bytes) }
}
server.start()
return server
}
private fun sha256(path: java.nio.file.Path): String {
val digest = MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(path))
return digest.joinToString("") { "%02x".format(it) }
}
private fun deleteRecursively(path: java.nio.file.Path) {
if (!Files.exists(path)) return
Files.walk(path).use { paths -> paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists) }
}
}
vendor/yokan-ext/src/desktopTest/kotlin/eu/friedcutlet/yokan/ext/DesktopExtensionServerTest.kt
- Source · test / fixture · 67 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
11: class DesktopExtensionServerTest {
13: fun missingJarFailsBeforeLaunching() = runTest {
23: fun ownsAndStopsLaunchedProcess() = runTest {
47: fun dataDirConfinesHomeTempAndOnlyWhenSet() {
Exact file bytes / download · SHA-256 98efb95b125fec7326fb7af0601d5f19c8bd1ddc262852dba3d9cfa6c6238dfc.
Complete file
package eu.friedcutlet.yokan.ext
import java.nio.file.Files
import kotlin.io.path.writeText
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class DesktopExtensionServerTest {
@Test
fun missingJarFailsBeforeLaunching() = runTest {
val server = DesktopExtensionServer()
val error = assertFailsWith<ExtensionServerException> {
server.start(ExtensionServerConfig(43122, serverJarPath = "/missing/server.jar"))
}
assertEquals("MISSING_JAR", error.code)
assertEquals(ExtensionServerPhase.Failed, server.status.value.phase)
}
@Test
fun ownsAndStopsLaunchedProcess() = runTest {
if (System.getProperty("os.name").contains("win", ignoreCase = true)) return@runTest
val directory = Files.createTempDirectory("yokan-ext-runner-")
try {
val java = directory.resolve("fake-java")
java.writeText("#!/bin/sh\nsleep 30\n")
assertTrue(java.toFile().setExecutable(true))
val jar = Files.createFile(directory.resolve("MExtensionServer.jar"))
val server = DesktopExtensionServer()
val running = server.start(ExtensionServerConfig(43123, java.toString(), jar.toString()))
assertEquals(ExtensionServerPhase.Running, running.phase)
assertEquals(43123, running.port)
val stopped = server.stop()
assertEquals(ExtensionServerPhase.Stopped, stopped.phase)
} finally {
Files.walk(directory).use { paths ->
paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists)
}
}
}
@Test
fun dataDirConfinesHomeTempAndOnlyWhenSet() {
val jar = java.io.File("/opt/MExtensionServer.jar")
val dataDir = java.io.File("/data/profiles/p_1/extension-server-data")
assertEquals(
listOf("java", "-jar", jar.absolutePath, "8080"),
desktopExtensionServerCommand("java", jar, 8080, null),
)
assertEquals(
listOf(
"java",
"-Duser.home=${dataDir.absolutePath}",
"-Djava.io.tmpdir=${java.io.File(dataDir, "tmp").absolutePath}",
"-jar",
jar.absolutePath,
"8080",
),
desktopExtensionServerCommand("java", jar, 8080, dataDir),
)
}
}
vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServer.kt
- Source · implementation · 160 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
30: class IosExtensionServer : ExtensionServer {
34: override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock {
107: override suspend fun stop(): ExtensionServerStatus = lock.withLock {
117: private fun resolveJavaHome(explicit: String?): String {
131: private fun findLibrary(home: String, name: String): String? {
145: private fun requireFile(path: String, code: String, label: String) {
149: private fun fileExists(path: String): Boolean = NSFileManager.defaultManager.fileExistsAtPath(path)
151: private fun normalizePath(path: String?): String? = path?.trim()?.trim('"', '\'')?.removePrefix("file://")?.takeIf(String::isNotEmpty)
Exact file bytes / download · SHA-256 84eb5dbe7fb7960968a8806562ada2d2f653c3299484cfb5565b101a45e5c88f.
Complete file
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.ext
import eu.friedcutlet.yokan.ext.jvmbridge.yokan_jvm_launch_main
import eu.friedcutlet.yokan.ext.jvmbridge.yokan_jvm_has_jit_permission
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.allocArray
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.toKString
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import platform.Foundation.NSBundle
import platform.Foundation.NSFileManager
import platform.Foundation.NSHomeDirectory
import platform.Foundation.NSTemporaryDirectory
import platform.UIKit.UIDevice
import platform.darwin.dispatch_async
import platform.darwin.dispatch_get_global_queue
import platform.posix.chdir
import platform.posix.setenv
/**
* Embedded iOS runner. The signed OpenJDK runtime is loaded in-process.
* JNI permits one JVM per process lifetime, so a running or exited JVM cannot be replaced.
*/
class IosExtensionServer : ExtensionServer {
override val status: StateFlow<ExtensionServerStatus> = sharedStatus
override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = lock.withLock {
when (val current = sharedStatus.value.phase) {
ExtensionServerPhase.Running -> {
if (sharedStatus.value.port == config.port) return sharedStatus.value
throw ExtensionServerException(
"ALREADY_RUNNING",
"The embedded iOS JVM is already running on port ${sharedStatus.value.port}; relaunch Yokan to change it",
)
}
ExtensionServerPhase.Stopped -> if (jvmWasStarted) {
throw ExtensionServerException("JVM_EXITED", "The embedded iOS JVM already exited; relaunch Yokan to start it again")
}
ExtensionServerPhase.Starting, ExtensionServerPhase.Stopping -> {
throw ExtensionServerException("BUSY", "The embedded iOS JVM is changing state")
}
ExtensionServerPhase.Failed -> if (jvmWasStarted) {
throw ExtensionServerException("JVM_EXITED", "The embedded iOS JVM cannot be restarted; relaunch Yokan")
}
}
val jar = normalizePath(config.serverJarPath)
?: throw ExtensionServerException("MISSING_JAR", "An extension server JAR is required on iOS")
requireFile(jar, "MISSING_JAR", "Extension server JAR")
val javaHome = resolveJavaHome(normalizePath(config.jvmPath))
val jvmPath = findLibrary(javaHome, "libjvm.dylib")
?: throw ExtensionServerException("MISSING_JAVA", "The signed iOS runtime has no libjvm.dylib: $javaHome")
if (yokan_jvm_has_jit_permission() == 0) {
throw ExtensionServerException(
"JIT_UNAVAILABLE",
"Enable JIT for Yokan with SideStore, AltStore, or StikDebug before starting the embedded server. " +
"On iOS 26 or later, keep the debugger attached.",
)
}
val useMirroredCodeCache = UIDevice.currentDevice.systemVersion.substringBefore('.').toIntOrNull()?.let { it >= 26 } == true
val mainClassName = "mextensionserver.MainKt"
val temporaryDirectory = NSTemporaryDirectory()
val userHome = NSHomeDirectory()
setenv("JAVA_HOME", javaHome, 1)
chdir(NSHomeDirectory())
jvmWasStarted = true
sharedStatus.value = ExtensionServerStatus(ExtensionServerPhase.Starting, config.port, "Launching embedded iOS JVM")
dispatch_async(dispatch_get_global_queue(0, 0u)) {
var errorMessage = ""
val code = memScoped {
val errorBuffer = allocArray<ByteVar>(ErrorBufferSize)
yokan_jvm_launch_main(
jvm_path = jvmPath,
jar_path = jar,
main_class_name = mainClassName,
port = config.port.toString(),
temporary_directory = temporaryDirectory,
user_home = userHome,
use_mirrored_code_cache = if (useMirroredCodeCache) 1 else 0,
error_buffer = errorBuffer,
error_capacity = ErrorBufferSize.toULong(),
).also { result ->
if (result != 0) errorMessage = errorBuffer.toKString()
}
}
sharedStatus.value = ExtensionServerStatus(
if (code == 0) ExtensionServerPhase.Stopped else ExtensionServerPhase.Failed,
message = if (code == 0) {
"Embedded iOS JVM exited"
} else {
errorMessage.ifBlank { "Embedded iOS JVM failed with code $code" }
},
)
}
ExtensionServerStatus(ExtensionServerPhase.Running, config.port, "Embedded iOS JVM started on port ${config.port}")
.also { sharedStatus.value = it }
}
override suspend fun stop(): ExtensionServerStatus = lock.withLock {
if (sharedStatus.value.phase == ExtensionServerPhase.Running) {
throw ExtensionServerException(
"STOP_UNSUPPORTED",
"The embedded iOS JVM cannot stop without terminating Yokan",
)
}
sharedStatus.value
}
private fun resolveJavaHome(explicit: String?): String {
val candidates = buildList {
explicit?.let {
add(if (it.endsWith("/bin/java")) it.removeSuffix("/bin/java") else it)
}
NSBundle.mainBundle.resourcePath?.let { add("$it/java_runtimes/java-21-openjdk") }
}
return candidates.firstOrNull { findLibrary(it, "libjvm.dylib") != null }
?: throw ExtensionServerException(
"MISSING_JAVA",
"No signed iOS OpenJDK runtime found; checked ${candidates.joinToString()}",
)
}
private fun findLibrary(home: String, name: String): String? {
val relativePaths = listOf(
"lib/$name",
"lib/server/$name",
"lib/zero/$name",
"lib/client/$name",
"lib/minimal/$name",
"lib/jli/$name",
"jre/lib/jli/$name",
"jre/lib/server/$name",
)
return relativePaths.asSequence().map { "$home/$it" }.firstOrNull(::fileExists)
}
private fun requireFile(path: String, code: String, label: String) {
if (!fileExists(path)) throw ExtensionServerException(code, "$label does not exist: $path")
}
private fun fileExists(path: String): Boolean = NSFileManager.defaultManager.fileExistsAtPath(path)
private fun normalizePath(path: String?): String? = path?.trim()?.trim('"', '\'')?.removePrefix("file://")?.takeIf(String::isNotEmpty)
private companion object {
val lock = Mutex()
val sharedStatus = MutableStateFlow(ExtensionServerStatus.Stopped)
var jvmWasStarted = false
const val ErrorBufferSize = 1_024
}
}
vendor/yokan-ext/src/iosMain/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServerInstaller.kt
- Source · implementation · 233 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
21: class IosExtensionServerInstaller private constructor(
41: suspend fun install(
70: fun importJar(sourcePath: String): InstalledExtensionServerBundle {
95: private suspend fun download(
139: private fun resolveBundle(directory: Path, version: String): InstalledExtensionServerBundle {
154: private fun copy(source: Path, destination: Path) = copy(fileSystem, source, destination)
156: private fun copy(sourceFileSystem: FileSystem, source: Path, destination: Path) {
168: internal fun createForTesting(
183: private fun versionFromPath(path: Path): String =
187: internal fun verifyIosExtensionServerArchiveSha256(
211: internal fun extractIosExtensionServerJar(
Exact file bytes / download · SHA-256 dc3485d21f6c08dd9557235a4126e3870e5e083ad669c41e807dffb074e791ce.
Complete file
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.ext
import io.ktor.client.HttpClient
import io.ktor.client.engine.darwin.Darwin
import io.ktor.client.request.prepareGet
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.isSuccess
import io.ktor.utils.io.readAvailable
import okio.Buffer
import okio.FileSystem
import okio.HashingSource
import okio.Path
import okio.Path.Companion.toPath
import okio.buffer
import okio.openZip
import platform.Foundation.NSURL
/** Installs only the architecture-independent server JAR; iOS JVM binaries stay build-provisioned. */
class IosExtensionServerInstaller private constructor(
installRoot: String,
private val bundledJvmPath: String,
private val fileSystem: FileSystem,
private val archiveDownloader: (suspend (ExtensionServerReleaseAsset, Path, (Long, Long) -> Unit) -> Unit)?,
private val trustedDigest: (ExtensionServerRelease, ExtensionServerReleaseAsset) -> String,
) {
constructor(
installRoot: String,
bundledJvmPath: String,
) : this(
installRoot = installRoot,
bundledJvmPath = bundledJvmPath,
fileSystem = FileSystem.SYSTEM,
archiveDownloader = null,
trustedDigest = { release, asset -> release.trustedSha256(asset) },
)
private val installRoot = installRoot.toPath(normalize = true)
suspend fun install(
release: ExtensionServerRelease,
asset: ExtensionServerReleaseAsset,
onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> },
): InstalledExtensionServerBundle {
if (!asset.name.endsWith(".zip", ignoreCase = true)) {
throw ExtensionServerException("UNSUPPORTED_ARCHIVE", "Only ZIP bundles are supported")
}
val expectedDigest = trustedDigest(release, asset)
fileSystem.createDirectories(installRoot)
val archive = installRoot / ".download-${release.version}.zip"
val staging = installRoot / ".install-${release.version}"
val destination = installRoot / release.version
try {
fileSystem.delete(archive, mustExist = false)
fileSystem.deleteRecursively(staging, mustExist = false)
download(asset, archive, onProgress)
verifyIosExtensionServerArchiveSha256(fileSystem, archive, expectedDigest)
fileSystem.createDirectories(staging)
extractIosExtensionServerJar(fileSystem, archive, staging)
fileSystem.deleteRecursively(destination, mustExist = false)
fileSystem.atomicMove(staging, destination)
return resolveBundle(destination, release.version)
} finally {
fileSystem.delete(archive, mustExist = false)
fileSystem.deleteRecursively(staging, mustExist = false)
}
}
fun importJar(sourcePath: String): InstalledExtensionServerBundle {
val source = sourcePath.removePrefix("file://").toPath(normalize = true)
if (source.name.substringAfterLast('.', "").lowercase() != "jar" || fileSystem.metadataOrNull(source) == null) {
throw ExtensionServerException("MISSING_JAR", "Selected extension server JAR does not exist: $source")
}
val destinationDirectory = installRoot / "manual"
val destination = destinationDirectory / source.name
val staging = destinationDirectory / ".${source.name}.import"
fileSystem.createDirectories(destinationDirectory)
fileSystem.delete(staging, mustExist = false)
try {
copy(source, staging)
fileSystem.delete(destination, mustExist = false)
fileSystem.atomicMove(staging, destination)
} finally {
fileSystem.delete(staging, mustExist = false)
}
return InstalledExtensionServerBundle(
version = versionFromPath(destination),
rootPath = destinationDirectory.toString(),
jvmPath = bundledJvmPath,
serverJarPath = destination.toString(),
)
}
private suspend fun download(
asset: ExtensionServerReleaseAsset,
target: Path,
onProgress: (Long, Long) -> Unit,
) {
archiveDownloader?.let { downloader ->
downloader(asset, target, onProgress)
return
}
NSURL.URLWithString(asset.downloadUrl)
?: throw ExtensionServerException("INVALID_DOWNLOAD_URL", "Invalid bundle URL: ${asset.downloadUrl}")
val client = HttpClient(Darwin)
try {
client.prepareGet(asset.downloadUrl).execute { response ->
if (!response.status.isSuccess()) {
throw ExtensionServerException(
"DOWNLOAD_HTTP_ERROR",
"Bundle download failed with HTTP ${response.status.value}",
)
}
val channel = response.bodyAsChannel()
val expected = response.headers["Content-Length"]?.toLongOrNull() ?: asset.size
val output = fileSystem.sink(target).buffer()
val buffer = ByteArray(8_192)
var downloaded = 0L
try {
while (true) {
val count = channel.readAvailable(buffer)
if (count < 0) break
if (count == 0) continue
output.write(buffer, 0, count)
downloaded += count
onProgress(downloaded, expected)
}
} finally {
output.close()
}
}
} finally {
client.close()
}
}
private fun resolveBundle(directory: Path, version: String): InstalledExtensionServerBundle {
val jar = fileSystem.listRecursively(directory)
.firstOrNull { path ->
val name = path.name.lowercase()
name.endsWith(".jar") && "extensionserver" in name && fileSystem.metadata(path).isRegularFile
}
?: throw ExtensionServerException("BUNDLE_INVALID", "Installed bundle has no extension server JAR")
return InstalledExtensionServerBundle(
version = version,
rootPath = directory.toString(),
jvmPath = bundledJvmPath,
serverJarPath = jar.toString(),
)
}
private fun copy(source: Path, destination: Path) = copy(fileSystem, source, destination)
private fun copy(sourceFileSystem: FileSystem, source: Path, destination: Path) {
val input = sourceFileSystem.source(source).buffer()
val output = fileSystem.sink(destination).buffer()
try {
output.writeAll(input)
} finally {
output.close()
input.close()
}
}
companion object {
internal fun createForTesting(
installRoot: String,
bundledJvmPath: String,
fileSystem: FileSystem,
archiveDownloader: suspend (ExtensionServerReleaseAsset, Path, (Long, Long) -> Unit) -> Unit,
trustedDigest: (ExtensionServerRelease, ExtensionServerReleaseAsset) -> String,
): IosExtensionServerInstaller = IosExtensionServerInstaller(
installRoot = installRoot,
bundledJvmPath = bundledJvmPath,
fileSystem = fileSystem,
archiveDownloader = archiveDownloader,
trustedDigest = trustedDigest,
)
}
private fun versionFromPath(path: Path): String =
Regex("""v?(\d+\.\d+\.\d+)""").find(path.name)?.groupValues?.getOrNull(1) ?: "manual"
}
internal fun verifyIosExtensionServerArchiveSha256(
fileSystem: FileSystem,
path: Path,
expected: String?,
) {
if (expected == null) {
throw ExtensionServerException("MISSING_DIGEST", "Release asset has no trusted SHA-256 digest")
}
val hashingSource = HashingSource.sha256(fileSystem.source(path))
val buffer = Buffer()
try {
while (hashingSource.read(buffer, 8_192) != -1L) buffer.clear()
} finally {
hashingSource.close()
}
val actual = hashingSource.hash.hex()
if (!actual.equals(expected, ignoreCase = true)) {
throw ExtensionServerException(
"CHECKSUM_MISMATCH",
"Bundle checksum mismatch: expected $expected, received $actual",
)
}
}
internal fun extractIosExtensionServerJar(
fileSystem: FileSystem,
archive: Path,
destination: Path,
): Path {
val zip = fileSystem.openZip(archive)
val jar = zip.listRecursively("/".toPath())
.firstOrNull { path ->
val name = path.name.lowercase()
name.endsWith(".jar") && "extensionserver" in name && zip.metadata(path).isRegularFile
}
?: throw ExtensionServerException("BUNDLE_INVALID", "Downloaded bundle has no extension server JAR")
val extracted = destination / jar.name
val input = zip.source(jar).buffer()
val output = fileSystem.sink(extracted).buffer()
try {
output.writeAll(input)
} finally {
output.close()
input.close()
}
return extracted
}
vendor/yokan-ext/src/iosTest/kotlin/eu/friedcutlet/yokan/ext/IosExtensionServerInstallerTest.kt
- Source · test / fixture · 207 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
18: class IosExtensionServerInstallerTest {
22: fun importsJarAtomicallyAndUsesBundledJvm() = withTemporaryRoot { root ->
39: fun rejectsNonJarImports() = withTemporaryRoot { root ->
55: fun rejectsUntrustedReleaseBeforeDownload() = runTest {
79: fun verifiesChecksumAndSelectsExtensionServerJar() = runTest {
103: fun rejectsMissingTrustedDigest() = withTemporaryRoot { root ->
115: fun removesArchiveAndStagingAfterChecksumMismatch() = runTest {
134: private fun releaseAsset() = ExtensionServerReleaseAsset(
141: private fun testInstaller(
153: private fun writeBytes(path: Path, value: ByteArray) {
162: private fun writeText(path: Path, value: String) {
171: private fun readText(path: Path): String {
180: private fun withTemporaryRoot(block: (Path) -> Unit) {
190: private suspend fun withTemporaryRootSuspend(block: suspend (Path) -> Unit) {
Exact file bytes / download · SHA-256 0609d320c5d076314601c53a9dc472b80158db9ef5317c864e333ec12093307b.
Complete file
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.ext
import kotlinx.coroutines.test.runTest
import okio.FileSystem
import okio.ByteString.Companion.decodeBase64
import okio.Path
import okio.Path.Companion.toPath
import okio.buffer
import platform.Foundation.NSTemporaryDirectory
import platform.Foundation.NSUUID
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class IosExtensionServerInstallerTest {
private val fileSystem = FileSystem.SYSTEM
@Test
fun importsJarAtomicallyAndUsesBundledJvm() = withTemporaryRoot { root ->
val source = root / "MExtensionServer-v1.2.3.jar"
writeText(source, "server")
val installer = IosExtensionServerInstaller(
installRoot = (root / "installed").toString(),
bundledJvmPath = "/app/java-21-openjdk",
)
val installed = installer.importJar(source.toString())
assertEquals("1.2.3", installed.version)
assertEquals("/app/java-21-openjdk", installed.jvmPath)
assertTrue(fileSystem.exists(installed.serverJarPath.toPath()))
assertEquals("server", readText(installed.serverJarPath.toPath()))
}
@Test
fun rejectsNonJarImports() = withTemporaryRoot { root ->
val source = root / "MExtensionServer.txt"
writeText(source, "not a jar")
val installer = IosExtensionServerInstaller(
installRoot = (root / "installed").toString(),
bundledJvmPath = "/app/java-21-openjdk",
)
val error = assertFailsWith<ExtensionServerException> {
installer.importJar(source.toString())
}
assertEquals("MISSING_JAR", error.code)
}
@Test
fun rejectsUntrustedReleaseBeforeDownload() = runTest {
withTemporaryRootSuspend { root ->
val installRoot = root / "installed"
val asset = releaseAsset()
var downloadCalled = false
val installer = IosExtensionServerInstaller.createForTesting(
installRoot = installRoot.toString(),
bundledJvmPath = "/app/java-21-openjdk",
fileSystem = fileSystem,
archiveDownloader = { _, _, _ -> downloadCalled = true },
trustedDigest = { release, selected -> release.trustedSha256(selected) },
)
val error = assertFailsWith<ExtensionServerException> {
installer.install(ExtensionServerRelease("9.9.9", listOf(asset)), asset)
}
assertEquals("UNTRUSTED_RELEASE", error.code)
assertTrue(!downloadCalled)
assertTrue(!fileSystem.exists(installRoot))
}
}
@Test
fun verifiesChecksumAndSelectsExtensionServerJar() = runTest {
withTemporaryRootSuspend { root ->
val installRoot = root / "installed"
val asset = releaseAsset()
val progress = mutableListOf<Long>()
val installer = testInstaller(installRoot, FixtureSha256) { _, target, onProgress ->
writeBytes(target, FixtureArchive)
onProgress(FixtureArchive.size.toLong(), FixtureArchive.size.toLong())
}
val installed = installer.install(ExtensionServerRelease("1.0.4", listOf(asset)), asset) {
downloaded,
_,
->
progress += downloaded
}
assertEquals("MExtensionServer.jar", installed.serverJarPath.toPath().name)
assertEquals("server", readText(installed.serverJarPath.toPath()))
assertEquals(FixtureArchive.size.toLong(), progress.last())
}
}
@Test
fun rejectsMissingTrustedDigest() = withTemporaryRoot { root ->
val archive = root / "bundle.zip"
writeBytes(archive, FixtureArchive)
val error = assertFailsWith<ExtensionServerException> {
verifyIosExtensionServerArchiveSha256(fileSystem, archive, null)
}
assertEquals("MISSING_DIGEST", error.code)
}
@Test
fun removesArchiveAndStagingAfterChecksumMismatch() = runTest {
withTemporaryRootSuspend { root ->
val installRoot = root / "installed"
val asset = releaseAsset()
val installer = testInstaller(installRoot, "0".repeat(64)) { _, target, _ ->
writeBytes(target, FixtureArchive)
}
val error = assertFailsWith<ExtensionServerException> {
installer.install(ExtensionServerRelease("1.0.4", listOf(asset)), asset)
}
assertEquals("CHECKSUM_MISMATCH", error.code)
assertTrue(!fileSystem.exists(installRoot / ".download-1.0.4.zip"))
assertTrue(!fileSystem.exists(installRoot / ".install-1.0.4"))
assertTrue(!fileSystem.exists(installRoot / "1.0.4"))
}
}
private fun releaseAsset() = ExtensionServerReleaseAsset(
name = "macOS-arm64-bundle.zip",
downloadUrl = "https://example.test/bundle.zip",
size = FixtureArchive.size.toLong(),
sha256 = null,
)
private fun testInstaller(
installRoot: Path,
digest: String,
downloader: suspend (ExtensionServerReleaseAsset, Path, (Long, Long) -> Unit) -> Unit,
) = IosExtensionServerInstaller.createForTesting(
installRoot = installRoot.toString(),
bundledJvmPath = "/app/java-21-openjdk",
fileSystem = fileSystem,
archiveDownloader = downloader,
trustedDigest = { _, _ -> digest },
)
private fun writeBytes(path: Path, value: ByteArray) {
val sink = fileSystem.sink(path).buffer()
try {
sink.write(value)
} finally {
sink.close()
}
}
private fun writeText(path: Path, value: String) {
val sink = fileSystem.sink(path).buffer()
try {
sink.writeUtf8(value)
} finally {
sink.close()
}
}
private fun readText(path: Path): String {
val source = fileSystem.source(path).buffer()
return try {
source.readUtf8()
} finally {
source.close()
}
}
private fun withTemporaryRoot(block: (Path) -> Unit) {
val root = "${NSTemporaryDirectory().trimEnd('/')}/yokan-ext-${NSUUID.UUID().UUIDString}".toPath()
fileSystem.createDirectories(root)
try {
block(root)
} finally {
fileSystem.deleteRecursively(root, mustExist = false)
}
}
private suspend fun withTemporaryRootSuspend(block: suspend (Path) -> Unit) {
val root = "${NSTemporaryDirectory().trimEnd('/')}/yokan-ext-${NSUUID.UUID().UUIDString}".toPath()
fileSystem.createDirectories(root)
try {
block(root)
} finally {
fileSystem.deleteRecursively(root, mustExist = false)
}
}
private companion object {
const val FixtureSha256 = "ad0b8a48643602e5baf16bdc621000450254ea2280606a5b590a94ba245145b6"
val FixtureArchive = checkNotNull(
"UEsDBBQAAAAAAAAAIQAo6kUnBQAAAAUAAAAQAAAAYnVuZGxlL290aGVyLmphcmRlY295UEsDBBQAAAAAAAAAIQD21W1aBgAAAAYAAAAbAAAAYnVuZGxlL01FeHRlbnNpb25TZXJ2ZXIuamFyc2VydmVyUEsBAhQDFAAAAAAAAAAhACjqRScFAAAABQAAABAAAAAAAAAAAAAAAIABAAAAAGJ1bmRsZS9vdGhlci5qYXJQSwECFAMUAAAAAAAAACEA9tVtWgYAAAAGAAAAGwAAAAAAAAAAAAAAgAEzAAAAYnVuZGxlL01FeHRlbnNpb25TZXJ2ZXIuamFyUEsFBgAAAAACAAIAhwAAAHIAAAAAAA=="
.decodeBase64(),
).toByteArray()
}
}
vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.def
- Source · configuration / resource · 2 lines.
- Manual task: Recreate the keys, identifiers, build relationships or resource names used by the consuming code. Preserve serialized names and schema compatibility; omit machine-specific values.
Exact file bytes / download · SHA-256 0b2f414b7a322d043668eb7d61a9dd19c3ff81ff79e3020ee6f7ae04be3c12a9.
Complete file
headers = JvmBridge.h
package = eu.friedcutlet.yokan.ext.jvmbridge
vendor/yokan-ext/src/nativeInterop/cinterop/JvmBridge.h
- Source · implementation · 292 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Exact file bytes / download · SHA-256 6d112e01a1b200887c2915b86c8c2ca7dffe4a72deb4347a35aa14e9dbd67a33.
Complete file
#ifndef YOKAN_JVM_BRIDGE_H
#define YOKAN_JVM_BRIDGE_H
#include <dlfcn.h>
#include <TargetConditionals.h>
#include <jni.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#define YOKAN_CS_OPS_STATUS 0
#define YOKAN_CS_DEBUGGED 0x10000000
extern int csops(pid_t pid, unsigned int ops, void *useraddr, size_t usersize);
static inline int32_t yokan_jvm_has_jit_permission(void) {
#if TARGET_OS_SIMULATOR
return 1;
#else
uint32_t flags = 0;
return csops(getpid(), YOKAN_CS_OPS_STATUS, &flags, sizeof(flags)) == 0 &&
(flags & YOKAN_CS_DEBUGGED) != 0;
#endif
}
static inline void yokan_jvm_set_error(char *buffer, size_t capacity, const char *message) {
if (buffer != NULL && capacity > 0) {
snprintf(buffer, capacity, "%s", message != NULL ? message : "Unknown embedded JVM error");
}
}
static inline char *yokan_jvm_property(const char *name, const char *value) {
const size_t size = strlen(name) + strlen(value) + 3;
char *property = (char *)malloc(size);
if (property != NULL) {
snprintf(property, size, "-D%s=%s", name, value);
}
return property;
}
static inline void yokan_jvm_set_pending_exception(
JNIEnv *env,
char *buffer,
size_t capacity,
const char *fallback
) {
if (!(*env)->ExceptionCheck(env)) {
yokan_jvm_set_error(buffer, capacity, fallback);
return;
}
jthrowable throwable = (*env)->ExceptionOccurred(env);
(*env)->ExceptionClear(env);
jclass throwable_class = throwable == NULL ? NULL :
(jclass)(*env)->GetObjectClass(env, throwable);
jmethodID to_string = throwable_class == NULL ? NULL :
(*env)->GetMethodID(env, throwable_class, "toString", "()Ljava/lang/String;");
jstring description = to_string == NULL ? NULL :
(jstring)(*env)->CallObjectMethod(env, throwable, to_string);
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionClear(env);
description = NULL;
}
int wrote_description = 0;
if (description != NULL) {
const char *utf = (*env)->GetStringUTFChars(env, description, NULL);
if (utf != NULL) {
yokan_jvm_set_error(buffer, capacity, utf);
wrote_description = 1;
(*env)->ReleaseStringUTFChars(env, description, utf);
}
}
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionClear(env);
}
if (!wrote_description) {
yokan_jvm_set_error(buffer, capacity, fallback);
}
if (description != NULL) (*env)->DeleteLocalRef(env, description);
if (throwable_class != NULL) (*env)->DeleteLocalRef(env, throwable_class);
if (throwable != NULL) (*env)->DeleteLocalRef(env, throwable);
}
static inline jclass yokan_jvm_load_class(
JNIEnv *env,
const char *jar_path,
const char *class_name
) {
jclass file_class = (*env)->FindClass(env, "java/io/File");
jmethodID file_constructor = file_class == NULL ? NULL :
(*env)->GetMethodID(env, file_class, "<init>", "(Ljava/lang/String;)V");
jstring path = file_constructor == NULL ? NULL : (*env)->NewStringUTF(env, jar_path);
jobject file = path == NULL ? NULL :
(*env)->NewObject(env, file_class, file_constructor, path);
jmethodID to_uri = file == NULL ? NULL :
(*env)->GetMethodID(env, file_class, "toURI", "()Ljava/net/URI;");
jobject uri = to_uri == NULL ? NULL : (*env)->CallObjectMethod(env, file, to_uri);
jclass uri_class = uri == NULL ? NULL : (*env)->FindClass(env, "java/net/URI");
jmethodID to_url = uri_class == NULL ? NULL :
(*env)->GetMethodID(env, uri_class, "toURL", "()Ljava/net/URL;");
jobject url = to_url == NULL ? NULL : (*env)->CallObjectMethod(env, uri, to_url);
jclass url_class = url == NULL ? NULL : (*env)->FindClass(env, "java/net/URL");
jobjectArray urls = url_class == NULL ? NULL :
(*env)->NewObjectArray(env, 1, url_class, url);
jclass loader_class = urls == NULL ? NULL :
(*env)->FindClass(env, "java/net/URLClassLoader");
jmethodID new_loader = loader_class == NULL ? NULL :
(*env)->GetStaticMethodID(
env,
loader_class,
"newInstance",
"([Ljava/net/URL;)Ljava/net/URLClassLoader;"
);
jobject loader = new_loader == NULL ? NULL :
(*env)->CallStaticObjectMethod(env, loader_class, new_loader, urls);
jclass thread_class = loader == NULL ? NULL : (*env)->FindClass(env, "java/lang/Thread");
jmethodID current_thread = thread_class == NULL ? NULL :
(*env)->GetStaticMethodID(env, thread_class, "currentThread", "()Ljava/lang/Thread;");
jobject thread = current_thread == NULL ? NULL :
(*env)->CallStaticObjectMethod(env, thread_class, current_thread);
jmethodID set_context_loader = thread == NULL ? NULL :
(*env)->GetMethodID(
env,
thread_class,
"setContextClassLoader",
"(Ljava/lang/ClassLoader;)V"
);
if (set_context_loader == NULL) {
return NULL;
}
(*env)->CallVoidMethod(env, thread, set_context_loader, loader);
jclass class_loader_class = (*env)->FindClass(env, "java/lang/ClassLoader");
jmethodID load_class = class_loader_class == NULL ? NULL :
(*env)->GetMethodID(
env,
class_loader_class,
"loadClass",
"(Ljava/lang/String;)Ljava/lang/Class;"
);
jstring requested_class = load_class == NULL ? NULL :
(*env)->NewStringUTF(env, class_name);
jobject loaded_class = requested_class == NULL ? NULL :
(*env)->CallObjectMethod(env, loader, load_class, requested_class);
return (jclass)loaded_class;
}
/*
* Starts OpenJDK through the JNI invocation API and calls a static
* main(String[]) method. JLI_Launch cannot be used inside an iOS host app:
* Apple's libjli startup path resolves the process-wide `main` symbol and
* would invoke the SwiftUI application entry point a second time.
*/
static inline int32_t yokan_jvm_launch_main(
const char *jvm_path,
const char *jar_path,
const char *main_class_name,
const char *port,
const char *temporary_directory,
const char *user_home,
int32_t use_mirrored_code_cache,
char *error_buffer,
size_t error_capacity
) {
void *handle = dlopen(jvm_path, RTLD_NOW | RTLD_GLOBAL);
if (handle == NULL) {
yokan_jvm_set_error(error_buffer, error_capacity, dlerror());
return 1;
}
typedef jint (*CreateJavaVm)(JavaVM **, void **, void *);
CreateJavaVm create_vm = (CreateJavaVm)dlsym(handle, "JNI_CreateJavaVM");
if (create_vm == NULL) {
yokan_jvm_set_error(error_buffer, error_capacity, "libjvm.dylib does not export JNI_CreateJavaVM");
return 2;
}
char *class_path = yokan_jvm_property("java.class.path", jar_path);
char *tmp_dir = yokan_jvm_property("java.io.tmpdir", temporary_directory);
char *home = yokan_jvm_property("user.home", user_home);
if (class_path == NULL || tmp_dir == NULL || home == NULL) {
free(class_path);
free(tmp_dir);
free(home);
yokan_jvm_set_error(error_buffer, error_capacity, "Could not allocate embedded JVM options");
return 3;
}
JavaVMOption options[12];
jint option_count = 0;
options[option_count++] = (JavaVMOption) { .optionString = "-Xint", .extraInfo = NULL };
options[option_count++] = (JavaVMOption) { .optionString = "-Xms32m", .extraInfo = NULL };
options[option_count++] = (JavaVMOption) { .optionString = "-Xmx512m", .extraInfo = NULL };
/*
* HotSpot's compressed class space requires an extended virtual address
* range that ordinary sideloaded iOS processes do not receive.
*/
options[option_count++] = (JavaVMOption) { .optionString = "-XX:-UseCompressedClassPointers", .extraInfo = NULL };
options[option_count++] = (JavaVMOption) { .optionString = "-XX:+UnlockExperimentalVMOptions", .extraInfo = NULL };
if (use_mirrored_code_cache) {
options[option_count++] = (JavaVMOption) { .optionString = "-XX:+MirrorMappedCodeCache", .extraInfo = NULL };
}
options[option_count++] = (JavaVMOption) { .optionString = "-Xrs", .extraInfo = NULL };
options[option_count++] = (JavaVMOption) { .optionString = "-XX:-UsePerfData", .extraInfo = NULL };
options[option_count++] = (JavaVMOption) { .optionString = "-Djava.awt.headless=true", .extraInfo = NULL };
options[option_count++] = (JavaVMOption) { .optionString = class_path, .extraInfo = NULL };
options[option_count++] = (JavaVMOption) { .optionString = tmp_dir, .extraInfo = NULL };
options[option_count++] = (JavaVMOption) { .optionString = home, .extraInfo = NULL };
JavaVMInitArgs init_args = {
.version = JNI_VERSION_1_8,
.nOptions = option_count,
.options = options,
.ignoreUnrecognized = JNI_FALSE,
};
JavaVM *vm = NULL;
JNIEnv *env = NULL;
const jint create_result = create_vm(&vm, (void **)&env, &init_args);
free(class_path);
free(tmp_dir);
free(home);
if (create_result != JNI_OK || vm == NULL || env == NULL) {
char message[128];
snprintf(message, sizeof(message), "JNI_CreateJavaVM failed with code %d", create_result);
yokan_jvm_set_error(error_buffer, error_capacity, message);
return 4;
}
jclass main_class = yokan_jvm_load_class(env, jar_path, main_class_name);
if (main_class == NULL) {
yokan_jvm_set_pending_exception(
env,
error_buffer,
error_capacity,
"Extension server main class was not found"
);
return 5;
}
jmethodID main_method = (*env)->GetStaticMethodID(env, main_class, "main", "([Ljava/lang/String;)V");
if (main_method == NULL) {
yokan_jvm_set_pending_exception(
env,
error_buffer,
error_capacity,
"Extension server main(String[]) method was not found"
);
return 6;
}
jclass string_class = (*env)->FindClass(env, "java/lang/String");
jobjectArray arguments = string_class == NULL ? NULL : (*env)->NewObjectArray(env, 1, string_class, NULL);
jstring port_argument = arguments == NULL ? NULL : (*env)->NewStringUTF(env, port);
if (arguments == NULL || port_argument == NULL || (*env)->ExceptionCheck(env)) {
yokan_jvm_set_pending_exception(
env,
error_buffer,
error_capacity,
"Could not create extension server arguments"
);
return 7;
}
(*env)->SetObjectArrayElement(env, arguments, 0, port_argument);
if ((*env)->ExceptionCheck(env)) {
yokan_jvm_set_pending_exception(
env,
error_buffer,
error_capacity,
"Could not populate extension server arguments"
);
return 7;
}
jvalue call_arguments[1];
call_arguments[0].l = arguments;
(*env)->CallStaticVoidMethodA(env, main_class, main_method, call_arguments);
if ((*env)->ExceptionCheck(env)) {
yokan_jvm_set_pending_exception(
env,
error_buffer,
error_capacity,
"Extension server main method failed"
);
return 8;
}
return 0;
}
#endif
vendor/yokan-ext/src/nativeInterop/cinterop/jni.h
- Source · implementation · 2001 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
67: class _jobject {};
68: class _jclass : public _jobject {};
69: class _jthrowable : public _jobject {};
70: class _jstring : public _jobject {};
71: class _jarray : public _jobject {};
72: class _jbooleanArray : public _jarray {};
73: class _jbyteArray : public _jarray {};
74: class _jcharArray : public _jarray {};
75: class _jshortArray : public _jarray {};
76: class _jintArray : public _jarray {};
77: class _jlongArray : public _jarray {};
78: class _jfloatArray : public _jarray {};
79: class _jdoubleArray : public _jarray {};
80: class _jobjectArray : public _jarray {};
Exact file bytes / download · SHA-256 99e64ebbe749e6df284f852f11b3c73f6ea97baf15120428f40f887fe0616e61.
Complete file
/*
* Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* We used part of Netscape's Java Runtime Interface (JRI) as the starting
* point of our design and implementation.
*/
/******************************************************************************
* Java Runtime Interface
* Copyright (c) 1996 Netscape Communications Corporation. All rights reserved.
*****************************************************************************/
#ifndef _JAVASOFT_JNI_H_
#define _JAVASOFT_JNI_H_
#include <stdio.h>
#include <stdarg.h>
/* jni_md.h contains the machine-dependent typedefs for jbyte, jint
and jlong */
#include "jni_md.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* JNI Types
*/
#ifndef JNI_TYPES_ALREADY_DEFINED_IN_JNI_MD_H
typedef unsigned char jboolean;
typedef unsigned short jchar;
typedef short jshort;
typedef float jfloat;
typedef double jdouble;
typedef jint jsize;
#ifdef __cplusplus
class _jobject {};
class _jclass : public _jobject {};
class _jthrowable : public _jobject {};
class _jstring : public _jobject {};
class _jarray : public _jobject {};
class _jbooleanArray : public _jarray {};
class _jbyteArray : public _jarray {};
class _jcharArray : public _jarray {};
class _jshortArray : public _jarray {};
class _jintArray : public _jarray {};
class _jlongArray : public _jarray {};
class _jfloatArray : public _jarray {};
class _jdoubleArray : public _jarray {};
class _jobjectArray : public _jarray {};
typedef _jobject *jobject;
typedef _jclass *jclass;
typedef _jthrowable *jthrowable;
typedef _jstring *jstring;
typedef _jarray *jarray;
typedef _jbooleanArray *jbooleanArray;
typedef _jbyteArray *jbyteArray;
typedef _jcharArray *jcharArray;
typedef _jshortArray *jshortArray;
typedef _jintArray *jintArray;
typedef _jlongArray *jlongArray;
typedef _jfloatArray *jfloatArray;
typedef _jdoubleArray *jdoubleArray;
typedef _jobjectArray *jobjectArray;
#else
struct _jobject;
typedef struct _jobject *jobject;
typedef jobject jclass;
typedef jobject jthrowable;
typedef jobject jstring;
typedef jobject jarray;
typedef jarray jbooleanArray;
typedef jarray jbyteArray;
typedef jarray jcharArray;
typedef jarray jshortArray;
typedef jarray jintArray;
typedef jarray jlongArray;
typedef jarray jfloatArray;
typedef jarray jdoubleArray;
typedef jarray jobjectArray;
#endif
typedef jobject jweak;
typedef union jvalue {
jboolean z;
jbyte b;
jchar c;
jshort s;
jint i;
jlong j;
jfloat f;
jdouble d;
jobject l;
} jvalue;
struct _jfieldID;
typedef struct _jfieldID *jfieldID;
struct _jmethodID;
typedef struct _jmethodID *jmethodID;
/* Return values from jobjectRefType */
typedef enum _jobjectType {
JNIInvalidRefType = 0,
JNILocalRefType = 1,
JNIGlobalRefType = 2,
JNIWeakGlobalRefType = 3
} jobjectRefType;
#endif /* JNI_TYPES_ALREADY_DEFINED_IN_JNI_MD_H */
/*
* jboolean constants
*/
#define JNI_FALSE 0
#define JNI_TRUE 1
/*
* possible return values for JNI functions.
*/
#define JNI_OK 0 /* success */
#define JNI_ERR (-1) /* unknown error */
#define JNI_EDETACHED (-2) /* thread detached from the VM */
#define JNI_EVERSION (-3) /* JNI version error */
#define JNI_ENOMEM (-4) /* not enough memory */
#define JNI_EEXIST (-5) /* VM already created */
#define JNI_EINVAL (-6) /* invalid arguments */
/*
* used in ReleaseScalarArrayElements
*/
#define JNI_COMMIT 1
#define JNI_ABORT 2
/*
* used in RegisterNatives to describe native method name, signature,
* and function pointer.
*/
typedef struct {
char *name;
char *signature;
void *fnPtr;
} JNINativeMethod;
/*
* JNI Native Method Interface.
*/
struct JNINativeInterface_;
struct JNIEnv_;
#ifdef __cplusplus
typedef JNIEnv_ JNIEnv;
#else
typedef const struct JNINativeInterface_ *JNIEnv;
#endif
/*
* JNI Invocation Interface.
*/
struct JNIInvokeInterface_;
struct JavaVM_;
#ifdef __cplusplus
typedef JavaVM_ JavaVM;
#else
typedef const struct JNIInvokeInterface_ *JavaVM;
#endif
struct JNINativeInterface_ {
void *reserved0;
void *reserved1;
void *reserved2;
void *reserved3;
jint (JNICALL *GetVersion)(JNIEnv *env);
jclass (JNICALL *DefineClass)
(JNIEnv *env, const char *name, jobject loader, const jbyte *buf,
jsize len);
jclass (JNICALL *FindClass)
(JNIEnv *env, const char *name);
jmethodID (JNICALL *FromReflectedMethod)
(JNIEnv *env, jobject method);
jfieldID (JNICALL *FromReflectedField)
(JNIEnv *env, jobject field);
jobject (JNICALL *ToReflectedMethod)
(JNIEnv *env, jclass cls, jmethodID methodID, jboolean isStatic);
jclass (JNICALL *GetSuperclass)
(JNIEnv *env, jclass sub);
jboolean (JNICALL *IsAssignableFrom)
(JNIEnv *env, jclass sub, jclass sup);
jobject (JNICALL *ToReflectedField)
(JNIEnv *env, jclass cls, jfieldID fieldID, jboolean isStatic);
jint (JNICALL *Throw)
(JNIEnv *env, jthrowable obj);
jint (JNICALL *ThrowNew)
(JNIEnv *env, jclass clazz, const char *msg);
jthrowable (JNICALL *ExceptionOccurred)
(JNIEnv *env);
void (JNICALL *ExceptionDescribe)
(JNIEnv *env);
void (JNICALL *ExceptionClear)
(JNIEnv *env);
void (JNICALL *FatalError)
(JNIEnv *env, const char *msg);
jint (JNICALL *PushLocalFrame)
(JNIEnv *env, jint capacity);
jobject (JNICALL *PopLocalFrame)
(JNIEnv *env, jobject result);
jobject (JNICALL *NewGlobalRef)
(JNIEnv *env, jobject lobj);
void (JNICALL *DeleteGlobalRef)
(JNIEnv *env, jobject gref);
void (JNICALL *DeleteLocalRef)
(JNIEnv *env, jobject obj);
jboolean (JNICALL *IsSameObject)
(JNIEnv *env, jobject obj1, jobject obj2);
jobject (JNICALL *NewLocalRef)
(JNIEnv *env, jobject ref);
jint (JNICALL *EnsureLocalCapacity)
(JNIEnv *env, jint capacity);
jobject (JNICALL *AllocObject)
(JNIEnv *env, jclass clazz);
jobject (JNICALL *NewObject)
(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
jobject (JNICALL *NewObjectV)
(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
jobject (JNICALL *NewObjectA)
(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
jclass (JNICALL *GetObjectClass)
(JNIEnv *env, jobject obj);
jboolean (JNICALL *IsInstanceOf)
(JNIEnv *env, jobject obj, jclass clazz);
jmethodID (JNICALL *GetMethodID)
(JNIEnv *env, jclass clazz, const char *name, const char *sig);
jobject (JNICALL *CallObjectMethod)
(JNIEnv *env, jobject obj, jmethodID methodID, ...);
jobject (JNICALL *CallObjectMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
jobject (JNICALL *CallObjectMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);
jboolean (JNICALL *CallBooleanMethod)
(JNIEnv *env, jobject obj, jmethodID methodID, ...);
jboolean (JNICALL *CallBooleanMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
jboolean (JNICALL *CallBooleanMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);
jbyte (JNICALL *CallByteMethod)
(JNIEnv *env, jobject obj, jmethodID methodID, ...);
jbyte (JNICALL *CallByteMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
jbyte (JNICALL *CallByteMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
jchar (JNICALL *CallCharMethod)
(JNIEnv *env, jobject obj, jmethodID methodID, ...);
jchar (JNICALL *CallCharMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
jchar (JNICALL *CallCharMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
jshort (JNICALL *CallShortMethod)
(JNIEnv *env, jobject obj, jmethodID methodID, ...);
jshort (JNICALL *CallShortMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
jshort (JNICALL *CallShortMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
jint (JNICALL *CallIntMethod)
(JNIEnv *env, jobject obj, jmethodID methodID, ...);
jint (JNICALL *CallIntMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
jint (JNICALL *CallIntMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
jlong (JNICALL *CallLongMethod)
(JNIEnv *env, jobject obj, jmethodID methodID, ...);
jlong (JNICALL *CallLongMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
jlong (JNICALL *CallLongMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
jfloat (JNICALL *CallFloatMethod)
(JNIEnv *env, jobject obj, jmethodID methodID, ...);
jfloat (JNICALL *CallFloatMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
jfloat (JNICALL *CallFloatMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
jdouble (JNICALL *CallDoubleMethod)
(JNIEnv *env, jobject obj, jmethodID methodID, ...);
jdouble (JNICALL *CallDoubleMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
jdouble (JNICALL *CallDoubleMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args);
void (JNICALL *CallVoidMethod)
(JNIEnv *env, jobject obj, jmethodID methodID, ...);
void (JNICALL *CallVoidMethodV)
(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
void (JNICALL *CallVoidMethodA)
(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue * args);
jobject (JNICALL *CallNonvirtualObjectMethod)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
jobject (JNICALL *CallNonvirtualObjectMethodV)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
va_list args);
jobject (JNICALL *CallNonvirtualObjectMethodA)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
const jvalue * args);
jboolean (JNICALL *CallNonvirtualBooleanMethod)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
jboolean (JNICALL *CallNonvirtualBooleanMethodV)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
va_list args);
jboolean (JNICALL *CallNonvirtualBooleanMethodA)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
const jvalue * args);
jbyte (JNICALL *CallNonvirtualByteMethod)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
jbyte (JNICALL *CallNonvirtualByteMethodV)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
va_list args);
jbyte (JNICALL *CallNonvirtualByteMethodA)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
const jvalue *args);
jchar (JNICALL *CallNonvirtualCharMethod)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
jchar (JNICALL *CallNonvirtualCharMethodV)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
va_list args);
jchar (JNICALL *CallNonvirtualCharMethodA)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
const jvalue *args);
jshort (JNICALL *CallNonvirtualShortMethod)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
jshort (JNICALL *CallNonvirtualShortMethodV)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
va_list args);
jshort (JNICALL *CallNonvirtualShortMethodA)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
const jvalue *args);
jint (JNICALL *CallNonvirtualIntMethod)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
jint (JNICALL *CallNonvirtualIntMethodV)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
va_list args);
jint (JNICALL *CallNonvirtualIntMethodA)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
const jvalue *args);
jlong (JNICALL *CallNonvirtualLongMethod)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
jlong (JNICALL *CallNonvirtualLongMethodV)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
va_list args);
jlong (JNICALL *CallNonvirtualLongMethodA)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
const jvalue *args);
jfloat (JNICALL *CallNonvirtualFloatMethod)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
jfloat (JNICALL *CallNonvirtualFloatMethodV)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
va_list args);
jfloat (JNICALL *CallNonvirtualFloatMethodA)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
const jvalue *args);
jdouble (JNICALL *CallNonvirtualDoubleMethod)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
jdouble (JNICALL *CallNonvirtualDoubleMethodV)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
va_list args);
jdouble (JNICALL *CallNonvirtualDoubleMethodA)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
const jvalue *args);
void (JNICALL *CallNonvirtualVoidMethod)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID, ...);
void (JNICALL *CallNonvirtualVoidMethodV)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
va_list args);
void (JNICALL *CallNonvirtualVoidMethodA)
(JNIEnv *env, jobject obj, jclass clazz, jmethodID methodID,
const jvalue * args);
jfieldID (JNICALL *GetFieldID)
(JNIEnv *env, jclass clazz, const char *name, const char *sig);
jobject (JNICALL *GetObjectField)
(JNIEnv *env, jobject obj, jfieldID fieldID);
jboolean (JNICALL *GetBooleanField)
(JNIEnv *env, jobject obj, jfieldID fieldID);
jbyte (JNICALL *GetByteField)
(JNIEnv *env, jobject obj, jfieldID fieldID);
jchar (JNICALL *GetCharField)
(JNIEnv *env, jobject obj, jfieldID fieldID);
jshort (JNICALL *GetShortField)
(JNIEnv *env, jobject obj, jfieldID fieldID);
jint (JNICALL *GetIntField)
(JNIEnv *env, jobject obj, jfieldID fieldID);
jlong (JNICALL *GetLongField)
(JNIEnv *env, jobject obj, jfieldID fieldID);
jfloat (JNICALL *GetFloatField)
(JNIEnv *env, jobject obj, jfieldID fieldID);
jdouble (JNICALL *GetDoubleField)
(JNIEnv *env, jobject obj, jfieldID fieldID);
void (JNICALL *SetObjectField)
(JNIEnv *env, jobject obj, jfieldID fieldID, jobject val);
void (JNICALL *SetBooleanField)
(JNIEnv *env, jobject obj, jfieldID fieldID, jboolean val);
void (JNICALL *SetByteField)
(JNIEnv *env, jobject obj, jfieldID fieldID, jbyte val);
void (JNICALL *SetCharField)
(JNIEnv *env, jobject obj, jfieldID fieldID, jchar val);
void (JNICALL *SetShortField)
(JNIEnv *env, jobject obj, jfieldID fieldID, jshort val);
void (JNICALL *SetIntField)
(JNIEnv *env, jobject obj, jfieldID fieldID, jint val);
void (JNICALL *SetLongField)
(JNIEnv *env, jobject obj, jfieldID fieldID, jlong val);
void (JNICALL *SetFloatField)
(JNIEnv *env, jobject obj, jfieldID fieldID, jfloat val);
void (JNICALL *SetDoubleField)
(JNIEnv *env, jobject obj, jfieldID fieldID, jdouble val);
jmethodID (JNICALL *GetStaticMethodID)
(JNIEnv *env, jclass clazz, const char *name, const char *sig);
jobject (JNICALL *CallStaticObjectMethod)
(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
jobject (JNICALL *CallStaticObjectMethodV)
(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
jobject (JNICALL *CallStaticObjectMethodA)
(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
jboolean (JNICALL *CallStaticBooleanMethod)
(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
jboolean (JNICALL *CallStaticBooleanMethodV)
(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
jboolean (JNICALL *CallStaticBooleanMethodA)
(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
jbyte (JNICALL *CallStaticByteMethod)
(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
jbyte (JNICALL *CallStaticByteMethodV)
(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
jbyte (JNICALL *CallStaticByteMethodA)
(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
jchar (JNICALL *CallStaticCharMethod)
(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
jchar (JNICALL *CallStaticCharMethodV)
(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
jchar (JNICALL *CallStaticCharMethodA)
(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
jshort (JNICALL *CallStaticShortMethod)
(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
jshort (JNICALL *CallStaticShortMethodV)
(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
jshort (JNICALL *CallStaticShortMethodA)
(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
jint (JNICALL *CallStaticIntMethod)
(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
jint (JNICALL *CallStaticIntMethodV)
(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
jint (JNICALL *CallStaticIntMethodA)
(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
jlong (JNICALL *CallStaticLongMethod)
(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
jlong (JNICALL *CallStaticLongMethodV)
(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
jlong (JNICALL *CallStaticLongMethodA)
(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
jfloat (JNICALL *CallStaticFloatMethod)
(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
jfloat (JNICALL *CallStaticFloatMethodV)
(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
jfloat (JNICALL *CallStaticFloatMethodA)
(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
jdouble (JNICALL *CallStaticDoubleMethod)
(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
jdouble (JNICALL *CallStaticDoubleMethodV)
(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
jdouble (JNICALL *CallStaticDoubleMethodA)
(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
void (JNICALL *CallStaticVoidMethod)
(JNIEnv *env, jclass cls, jmethodID methodID, ...);
void (JNICALL *CallStaticVoidMethodV)
(JNIEnv *env, jclass cls, jmethodID methodID, va_list args);
void (JNICALL *CallStaticVoidMethodA)
(JNIEnv *env, jclass cls, jmethodID methodID, const jvalue * args);
jfieldID (JNICALL *GetStaticFieldID)
(JNIEnv *env, jclass clazz, const char *name, const char *sig);
jobject (JNICALL *GetStaticObjectField)
(JNIEnv *env, jclass clazz, jfieldID fieldID);
jboolean (JNICALL *GetStaticBooleanField)
(JNIEnv *env, jclass clazz, jfieldID fieldID);
jbyte (JNICALL *GetStaticByteField)
(JNIEnv *env, jclass clazz, jfieldID fieldID);
jchar (JNICALL *GetStaticCharField)
(JNIEnv *env, jclass clazz, jfieldID fieldID);
jshort (JNICALL *GetStaticShortField)
(JNIEnv *env, jclass clazz, jfieldID fieldID);
jint (JNICALL *GetStaticIntField)
(JNIEnv *env, jclass clazz, jfieldID fieldID);
jlong (JNICALL *GetStaticLongField)
(JNIEnv *env, jclass clazz, jfieldID fieldID);
jfloat (JNICALL *GetStaticFloatField)
(JNIEnv *env, jclass clazz, jfieldID fieldID);
jdouble (JNICALL *GetStaticDoubleField)
(JNIEnv *env, jclass clazz, jfieldID fieldID);
void (JNICALL *SetStaticObjectField)
(JNIEnv *env, jclass clazz, jfieldID fieldID, jobject value);
void (JNICALL *SetStaticBooleanField)
(JNIEnv *env, jclass clazz, jfieldID fieldID, jboolean value);
void (JNICALL *SetStaticByteField)
(JNIEnv *env, jclass clazz, jfieldID fieldID, jbyte value);
void (JNICALL *SetStaticCharField)
(JNIEnv *env, jclass clazz, jfieldID fieldID, jchar value);
void (JNICALL *SetStaticShortField)
(JNIEnv *env, jclass clazz, jfieldID fieldID, jshort value);
void (JNICALL *SetStaticIntField)
(JNIEnv *env, jclass clazz, jfieldID fieldID, jint value);
void (JNICALL *SetStaticLongField)
(JNIEnv *env, jclass clazz, jfieldID fieldID, jlong value);
void (JNICALL *SetStaticFloatField)
(JNIEnv *env, jclass clazz, jfieldID fieldID, jfloat value);
void (JNICALL *SetStaticDoubleField)
(JNIEnv *env, jclass clazz, jfieldID fieldID, jdouble value);
jstring (JNICALL *NewString)
(JNIEnv *env, const jchar *unicode, jsize len);
jsize (JNICALL *GetStringLength)
(JNIEnv *env, jstring str);
const jchar *(JNICALL *GetStringChars)
(JNIEnv *env, jstring str, jboolean *isCopy);
void (JNICALL *ReleaseStringChars)
(JNIEnv *env, jstring str, const jchar *chars);
jstring (JNICALL *NewStringUTF)
(JNIEnv *env, const char *utf);
jsize (JNICALL *GetStringUTFLength)
(JNIEnv *env, jstring str);
const char* (JNICALL *GetStringUTFChars)
(JNIEnv *env, jstring str, jboolean *isCopy);
void (JNICALL *ReleaseStringUTFChars)
(JNIEnv *env, jstring str, const char* chars);
jsize (JNICALL *GetArrayLength)
(JNIEnv *env, jarray array);
jobjectArray (JNICALL *NewObjectArray)
(JNIEnv *env, jsize len, jclass clazz, jobject init);
jobject (JNICALL *GetObjectArrayElement)
(JNIEnv *env, jobjectArray array, jsize index);
void (JNICALL *SetObjectArrayElement)
(JNIEnv *env, jobjectArray array, jsize index, jobject val);
jbooleanArray (JNICALL *NewBooleanArray)
(JNIEnv *env, jsize len);
jbyteArray (JNICALL *NewByteArray)
(JNIEnv *env, jsize len);
jcharArray (JNICALL *NewCharArray)
(JNIEnv *env, jsize len);
jshortArray (JNICALL *NewShortArray)
(JNIEnv *env, jsize len);
jintArray (JNICALL *NewIntArray)
(JNIEnv *env, jsize len);
jlongArray (JNICALL *NewLongArray)
(JNIEnv *env, jsize len);
jfloatArray (JNICALL *NewFloatArray)
(JNIEnv *env, jsize len);
jdoubleArray (JNICALL *NewDoubleArray)
(JNIEnv *env, jsize len);
jboolean * (JNICALL *GetBooleanArrayElements)
(JNIEnv *env, jbooleanArray array, jboolean *isCopy);
jbyte * (JNICALL *GetByteArrayElements)
(JNIEnv *env, jbyteArray array, jboolean *isCopy);
jchar * (JNICALL *GetCharArrayElements)
(JNIEnv *env, jcharArray array, jboolean *isCopy);
jshort * (JNICALL *GetShortArrayElements)
(JNIEnv *env, jshortArray array, jboolean *isCopy);
jint * (JNICALL *GetIntArrayElements)
(JNIEnv *env, jintArray array, jboolean *isCopy);
jlong * (JNICALL *GetLongArrayElements)
(JNIEnv *env, jlongArray array, jboolean *isCopy);
jfloat * (JNICALL *GetFloatArrayElements)
(JNIEnv *env, jfloatArray array, jboolean *isCopy);
jdouble * (JNICALL *GetDoubleArrayElements)
(JNIEnv *env, jdoubleArray array, jboolean *isCopy);
void (JNICALL *ReleaseBooleanArrayElements)
(JNIEnv *env, jbooleanArray array, jboolean *elems, jint mode);
void (JNICALL *ReleaseByteArrayElements)
(JNIEnv *env, jbyteArray array, jbyte *elems, jint mode);
void (JNICALL *ReleaseCharArrayElements)
(JNIEnv *env, jcharArray array, jchar *elems, jint mode);
void (JNICALL *ReleaseShortArrayElements)
(JNIEnv *env, jshortArray array, jshort *elems, jint mode);
void (JNICALL *ReleaseIntArrayElements)
(JNIEnv *env, jintArray array, jint *elems, jint mode);
void (JNICALL *ReleaseLongArrayElements)
(JNIEnv *env, jlongArray array, jlong *elems, jint mode);
void (JNICALL *ReleaseFloatArrayElements)
(JNIEnv *env, jfloatArray array, jfloat *elems, jint mode);
void (JNICALL *ReleaseDoubleArrayElements)
(JNIEnv *env, jdoubleArray array, jdouble *elems, jint mode);
void (JNICALL *GetBooleanArrayRegion)
(JNIEnv *env, jbooleanArray array, jsize start, jsize l, jboolean *buf);
void (JNICALL *GetByteArrayRegion)
(JNIEnv *env, jbyteArray array, jsize start, jsize len, jbyte *buf);
void (JNICALL *GetCharArrayRegion)
(JNIEnv *env, jcharArray array, jsize start, jsize len, jchar *buf);
void (JNICALL *GetShortArrayRegion)
(JNIEnv *env, jshortArray array, jsize start, jsize len, jshort *buf);
void (JNICALL *GetIntArrayRegion)
(JNIEnv *env, jintArray array, jsize start, jsize len, jint *buf);
void (JNICALL *GetLongArrayRegion)
(JNIEnv *env, jlongArray array, jsize start, jsize len, jlong *buf);
void (JNICALL *GetFloatArrayRegion)
(JNIEnv *env, jfloatArray array, jsize start, jsize len, jfloat *buf);
void (JNICALL *GetDoubleArrayRegion)
(JNIEnv *env, jdoubleArray array, jsize start, jsize len, jdouble *buf);
void (JNICALL *SetBooleanArrayRegion)
(JNIEnv *env, jbooleanArray array, jsize start, jsize l, const jboolean *buf);
void (JNICALL *SetByteArrayRegion)
(JNIEnv *env, jbyteArray array, jsize start, jsize len, const jbyte *buf);
void (JNICALL *SetCharArrayRegion)
(JNIEnv *env, jcharArray array, jsize start, jsize len, const jchar *buf);
void (JNICALL *SetShortArrayRegion)
(JNIEnv *env, jshortArray array, jsize start, jsize len, const jshort *buf);
void (JNICALL *SetIntArrayRegion)
(JNIEnv *env, jintArray array, jsize start, jsize len, const jint *buf);
void (JNICALL *SetLongArrayRegion)
(JNIEnv *env, jlongArray array, jsize start, jsize len, const jlong *buf);
void (JNICALL *SetFloatArrayRegion)
(JNIEnv *env, jfloatArray array, jsize start, jsize len, const jfloat *buf);
void (JNICALL *SetDoubleArrayRegion)
(JNIEnv *env, jdoubleArray array, jsize start, jsize len, const jdouble *buf);
jint (JNICALL *RegisterNatives)
(JNIEnv *env, jclass clazz, const JNINativeMethod *methods,
jint nMethods);
jint (JNICALL *UnregisterNatives)
(JNIEnv *env, jclass clazz);
jint (JNICALL *MonitorEnter)
(JNIEnv *env, jobject obj);
jint (JNICALL *MonitorExit)
(JNIEnv *env, jobject obj);
jint (JNICALL *GetJavaVM)
(JNIEnv *env, JavaVM **vm);
void (JNICALL *GetStringRegion)
(JNIEnv *env, jstring str, jsize start, jsize len, jchar *buf);
void (JNICALL *GetStringUTFRegion)
(JNIEnv *env, jstring str, jsize start, jsize len, char *buf);
void * (JNICALL *GetPrimitiveArrayCritical)
(JNIEnv *env, jarray array, jboolean *isCopy);
void (JNICALL *ReleasePrimitiveArrayCritical)
(JNIEnv *env, jarray array, void *carray, jint mode);
const jchar * (JNICALL *GetStringCritical)
(JNIEnv *env, jstring string, jboolean *isCopy);
void (JNICALL *ReleaseStringCritical)
(JNIEnv *env, jstring string, const jchar *cstring);
jweak (JNICALL *NewWeakGlobalRef)
(JNIEnv *env, jobject obj);
void (JNICALL *DeleteWeakGlobalRef)
(JNIEnv *env, jweak ref);
jboolean (JNICALL *ExceptionCheck)
(JNIEnv *env);
jobject (JNICALL *NewDirectByteBuffer)
(JNIEnv* env, void* address, jlong capacity);
void* (JNICALL *GetDirectBufferAddress)
(JNIEnv* env, jobject buf);
jlong (JNICALL *GetDirectBufferCapacity)
(JNIEnv* env, jobject buf);
/* New JNI 1.6 Features */
jobjectRefType (JNICALL *GetObjectRefType)
(JNIEnv* env, jobject obj);
/* Module Features */
jobject (JNICALL *GetModule)
(JNIEnv* env, jclass clazz);
/* Virtual threads */
jboolean (JNICALL *IsVirtualThread)
(JNIEnv* env, jobject obj);
};
/*
* We use inlined functions for C++ so that programmers can write:
*
* env->FindClass("java/lang/String")
*
* in C++ rather than:
*
* (*env)->FindClass(env, "java/lang/String")
*
* in C.
*/
struct JNIEnv_ {
const struct JNINativeInterface_ *functions;
#ifdef __cplusplus
jint GetVersion() {
return functions->GetVersion(this);
}
jclass DefineClass(const char *name, jobject loader, const jbyte *buf,
jsize len) {
return functions->DefineClass(this, name, loader, buf, len);
}
jclass FindClass(const char *name) {
return functions->FindClass(this, name);
}
jmethodID FromReflectedMethod(jobject method) {
return functions->FromReflectedMethod(this,method);
}
jfieldID FromReflectedField(jobject field) {
return functions->FromReflectedField(this,field);
}
jobject ToReflectedMethod(jclass cls, jmethodID methodID, jboolean isStatic) {
return functions->ToReflectedMethod(this, cls, methodID, isStatic);
}
jclass GetSuperclass(jclass sub) {
return functions->GetSuperclass(this, sub);
}
jboolean IsAssignableFrom(jclass sub, jclass sup) {
return functions->IsAssignableFrom(this, sub, sup);
}
jobject ToReflectedField(jclass cls, jfieldID fieldID, jboolean isStatic) {
return functions->ToReflectedField(this,cls,fieldID,isStatic);
}
jint Throw(jthrowable obj) {
return functions->Throw(this, obj);
}
jint ThrowNew(jclass clazz, const char *msg) {
return functions->ThrowNew(this, clazz, msg);
}
jthrowable ExceptionOccurred() {
return functions->ExceptionOccurred(this);
}
void ExceptionDescribe() {
functions->ExceptionDescribe(this);
}
void ExceptionClear() {
functions->ExceptionClear(this);
}
void FatalError(const char *msg) {
functions->FatalError(this, msg);
}
jint PushLocalFrame(jint capacity) {
return functions->PushLocalFrame(this,capacity);
}
jobject PopLocalFrame(jobject result) {
return functions->PopLocalFrame(this,result);
}
jobject NewGlobalRef(jobject lobj) {
return functions->NewGlobalRef(this,lobj);
}
void DeleteGlobalRef(jobject gref) {
functions->DeleteGlobalRef(this,gref);
}
void DeleteLocalRef(jobject obj) {
functions->DeleteLocalRef(this, obj);
}
jboolean IsSameObject(jobject obj1, jobject obj2) {
return functions->IsSameObject(this,obj1,obj2);
}
jobject NewLocalRef(jobject ref) {
return functions->NewLocalRef(this,ref);
}
jint EnsureLocalCapacity(jint capacity) {
return functions->EnsureLocalCapacity(this,capacity);
}
jobject AllocObject(jclass clazz) {
return functions->AllocObject(this,clazz);
}
jobject NewObject(jclass clazz, jmethodID methodID, ...) {
va_list args;
jobject result;
va_start(args, methodID);
result = functions->NewObjectV(this,clazz,methodID,args);
va_end(args);
return result;
}
jobject NewObjectV(jclass clazz, jmethodID methodID,
va_list args) {
return functions->NewObjectV(this,clazz,methodID,args);
}
jobject NewObjectA(jclass clazz, jmethodID methodID,
const jvalue *args) {
return functions->NewObjectA(this,clazz,methodID,args);
}
jclass GetObjectClass(jobject obj) {
return functions->GetObjectClass(this,obj);
}
jboolean IsInstanceOf(jobject obj, jclass clazz) {
return functions->IsInstanceOf(this,obj,clazz);
}
jmethodID GetMethodID(jclass clazz, const char *name,
const char *sig) {
return functions->GetMethodID(this,clazz,name,sig);
}
jobject CallObjectMethod(jobject obj, jmethodID methodID, ...) {
va_list args;
jobject result;
va_start(args,methodID);
result = functions->CallObjectMethodV(this,obj,methodID,args);
va_end(args);
return result;
}
jobject CallObjectMethodV(jobject obj, jmethodID methodID,
va_list args) {
return functions->CallObjectMethodV(this,obj,methodID,args);
}
jobject CallObjectMethodA(jobject obj, jmethodID methodID,
const jvalue * args) {
return functions->CallObjectMethodA(this,obj,methodID,args);
}
jboolean CallBooleanMethod(jobject obj,
jmethodID methodID, ...) {
va_list args;
jboolean result;
va_start(args,methodID);
result = functions->CallBooleanMethodV(this,obj,methodID,args);
va_end(args);
return result;
}
jboolean CallBooleanMethodV(jobject obj, jmethodID methodID,
va_list args) {
return functions->CallBooleanMethodV(this,obj,methodID,args);
}
jboolean CallBooleanMethodA(jobject obj, jmethodID methodID,
const jvalue * args) {
return functions->CallBooleanMethodA(this,obj,methodID, args);
}
jbyte CallByteMethod(jobject obj, jmethodID methodID, ...) {
va_list args;
jbyte result;
va_start(args,methodID);
result = functions->CallByteMethodV(this,obj,methodID,args);
va_end(args);
return result;
}
jbyte CallByteMethodV(jobject obj, jmethodID methodID,
va_list args) {
return functions->CallByteMethodV(this,obj,methodID,args);
}
jbyte CallByteMethodA(jobject obj, jmethodID methodID,
const jvalue * args) {
return functions->CallByteMethodA(this,obj,methodID,args);
}
jchar CallCharMethod(jobject obj, jmethodID methodID, ...) {
va_list args;
jchar result;
va_start(args,methodID);
result = functions->CallCharMethodV(this,obj,methodID,args);
va_end(args);
return result;
}
jchar CallCharMethodV(jobject obj, jmethodID methodID,
va_list args) {
return functions->CallCharMethodV(this,obj,methodID,args);
}
jchar CallCharMethodA(jobject obj, jmethodID methodID,
const jvalue * args) {
return functions->CallCharMethodA(this,obj,methodID,args);
}
jshort CallShortMethod(jobject obj, jmethodID methodID, ...) {
va_list args;
jshort result;
va_start(args,methodID);
result = functions->CallShortMethodV(this,obj,methodID,args);
va_end(args);
return result;
}
jshort CallShortMethodV(jobject obj, jmethodID methodID,
va_list args) {
return functions->CallShortMethodV(this,obj,methodID,args);
}
jshort CallShortMethodA(jobject obj, jmethodID methodID,
const jvalue * args) {
return functions->CallShortMethodA(this,obj,methodID,args);
}
jint CallIntMethod(jobject obj, jmethodID methodID, ...) {
va_list args;
jint result;
va_start(args,methodID);
result = functions->CallIntMethodV(this,obj,methodID,args);
va_end(args);
return result;
}
jint CallIntMethodV(jobject obj, jmethodID methodID,
va_list args) {
return functions->CallIntMethodV(this,obj,methodID,args);
}
jint CallIntMethodA(jobject obj, jmethodID methodID,
const jvalue * args) {
return functions->CallIntMethodA(this,obj,methodID,args);
}
jlong CallLongMethod(jobject obj, jmethodID methodID, ...) {
va_list args;
jlong result;
va_start(args,methodID);
result = functions->CallLongMethodV(this,obj,methodID,args);
va_end(args);
return result;
}
jlong CallLongMethodV(jobject obj, jmethodID methodID,
va_list args) {
return functions->CallLongMethodV(this,obj,methodID,args);
}
jlong CallLongMethodA(jobject obj, jmethodID methodID,
const jvalue * args) {
return functions->CallLongMethodA(this,obj,methodID,args);
}
jfloat CallFloatMethod(jobject obj, jmethodID methodID, ...) {
va_list args;
jfloat result;
va_start(args,methodID);
result = functions->CallFloatMethodV(this,obj,methodID,args);
va_end(args);
return result;
}
jfloat CallFloatMethodV(jobject obj, jmethodID methodID,
va_list args) {
return functions->CallFloatMethodV(this,obj,methodID,args);
}
jfloat CallFloatMethodA(jobject obj, jmethodID methodID,
const jvalue * args) {
return functions->CallFloatMethodA(this,obj,methodID,args);
}
jdouble CallDoubleMethod(jobject obj, jmethodID methodID, ...) {
va_list args;
jdouble result;
va_start(args,methodID);
result = functions->CallDoubleMethodV(this,obj,methodID,args);
va_end(args);
return result;
}
jdouble CallDoubleMethodV(jobject obj, jmethodID methodID,
va_list args) {
return functions->CallDoubleMethodV(this,obj,methodID,args);
}
jdouble CallDoubleMethodA(jobject obj, jmethodID methodID,
const jvalue * args) {
return functions->CallDoubleMethodA(this,obj,methodID,args);
}
void CallVoidMethod(jobject obj, jmethodID methodID, ...) {
va_list args;
va_start(args,methodID);
functions->CallVoidMethodV(this,obj,methodID,args);
va_end(args);
}
void CallVoidMethodV(jobject obj, jmethodID methodID,
va_list args) {
functions->CallVoidMethodV(this,obj,methodID,args);
}
void CallVoidMethodA(jobject obj, jmethodID methodID,
const jvalue * args) {
functions->CallVoidMethodA(this,obj,methodID,args);
}
jobject CallNonvirtualObjectMethod(jobject obj, jclass clazz,
jmethodID methodID, ...) {
va_list args;
jobject result;
va_start(args,methodID);
result = functions->CallNonvirtualObjectMethodV(this,obj,clazz,
methodID,args);
va_end(args);
return result;
}
jobject CallNonvirtualObjectMethodV(jobject obj, jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallNonvirtualObjectMethodV(this,obj,clazz,
methodID,args);
}
jobject CallNonvirtualObjectMethodA(jobject obj, jclass clazz,
jmethodID methodID, const jvalue * args) {
return functions->CallNonvirtualObjectMethodA(this,obj,clazz,
methodID,args);
}
jboolean CallNonvirtualBooleanMethod(jobject obj, jclass clazz,
jmethodID methodID, ...) {
va_list args;
jboolean result;
va_start(args,methodID);
result = functions->CallNonvirtualBooleanMethodV(this,obj,clazz,
methodID,args);
va_end(args);
return result;
}
jboolean CallNonvirtualBooleanMethodV(jobject obj, jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallNonvirtualBooleanMethodV(this,obj,clazz,
methodID,args);
}
jboolean CallNonvirtualBooleanMethodA(jobject obj, jclass clazz,
jmethodID methodID, const jvalue * args) {
return functions->CallNonvirtualBooleanMethodA(this,obj,clazz,
methodID, args);
}
jbyte CallNonvirtualByteMethod(jobject obj, jclass clazz,
jmethodID methodID, ...) {
va_list args;
jbyte result;
va_start(args,methodID);
result = functions->CallNonvirtualByteMethodV(this,obj,clazz,
methodID,args);
va_end(args);
return result;
}
jbyte CallNonvirtualByteMethodV(jobject obj, jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallNonvirtualByteMethodV(this,obj,clazz,
methodID,args);
}
jbyte CallNonvirtualByteMethodA(jobject obj, jclass clazz,
jmethodID methodID, const jvalue * args) {
return functions->CallNonvirtualByteMethodA(this,obj,clazz,
methodID,args);
}
jchar CallNonvirtualCharMethod(jobject obj, jclass clazz,
jmethodID methodID, ...) {
va_list args;
jchar result;
va_start(args,methodID);
result = functions->CallNonvirtualCharMethodV(this,obj,clazz,
methodID,args);
va_end(args);
return result;
}
jchar CallNonvirtualCharMethodV(jobject obj, jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallNonvirtualCharMethodV(this,obj,clazz,
methodID,args);
}
jchar CallNonvirtualCharMethodA(jobject obj, jclass clazz,
jmethodID methodID, const jvalue * args) {
return functions->CallNonvirtualCharMethodA(this,obj,clazz,
methodID,args);
}
jshort CallNonvirtualShortMethod(jobject obj, jclass clazz,
jmethodID methodID, ...) {
va_list args;
jshort result;
va_start(args,methodID);
result = functions->CallNonvirtualShortMethodV(this,obj,clazz,
methodID,args);
va_end(args);
return result;
}
jshort CallNonvirtualShortMethodV(jobject obj, jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallNonvirtualShortMethodV(this,obj,clazz,
methodID,args);
}
jshort CallNonvirtualShortMethodA(jobject obj, jclass clazz,
jmethodID methodID, const jvalue * args) {
return functions->CallNonvirtualShortMethodA(this,obj,clazz,
methodID,args);
}
jint CallNonvirtualIntMethod(jobject obj, jclass clazz,
jmethodID methodID, ...) {
va_list args;
jint result;
va_start(args,methodID);
result = functions->CallNonvirtualIntMethodV(this,obj,clazz,
methodID,args);
va_end(args);
return result;
}
jint CallNonvirtualIntMethodV(jobject obj, jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallNonvirtualIntMethodV(this,obj,clazz,
methodID,args);
}
jint CallNonvirtualIntMethodA(jobject obj, jclass clazz,
jmethodID methodID, const jvalue * args) {
return functions->CallNonvirtualIntMethodA(this,obj,clazz,
methodID,args);
}
jlong CallNonvirtualLongMethod(jobject obj, jclass clazz,
jmethodID methodID, ...) {
va_list args;
jlong result;
va_start(args,methodID);
result = functions->CallNonvirtualLongMethodV(this,obj,clazz,
methodID,args);
va_end(args);
return result;
}
jlong CallNonvirtualLongMethodV(jobject obj, jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallNonvirtualLongMethodV(this,obj,clazz,
methodID,args);
}
jlong CallNonvirtualLongMethodA(jobject obj, jclass clazz,
jmethodID methodID, const jvalue * args) {
return functions->CallNonvirtualLongMethodA(this,obj,clazz,
methodID,args);
}
jfloat CallNonvirtualFloatMethod(jobject obj, jclass clazz,
jmethodID methodID, ...) {
va_list args;
jfloat result;
va_start(args,methodID);
result = functions->CallNonvirtualFloatMethodV(this,obj,clazz,
methodID,args);
va_end(args);
return result;
}
jfloat CallNonvirtualFloatMethodV(jobject obj, jclass clazz,
jmethodID methodID,
va_list args) {
return functions->CallNonvirtualFloatMethodV(this,obj,clazz,
methodID,args);
}
jfloat CallNonvirtualFloatMethodA(jobject obj, jclass clazz,
jmethodID methodID,
const jvalue * args) {
return functions->CallNonvirtualFloatMethodA(this,obj,clazz,
methodID,args);
}
jdouble CallNonvirtualDoubleMethod(jobject obj, jclass clazz,
jmethodID methodID, ...) {
va_list args;
jdouble result;
va_start(args,methodID);
result = functions->CallNonvirtualDoubleMethodV(this,obj,clazz,
methodID,args);
va_end(args);
return result;
}
jdouble CallNonvirtualDoubleMethodV(jobject obj, jclass clazz,
jmethodID methodID,
va_list args) {
return functions->CallNonvirtualDoubleMethodV(this,obj,clazz,
methodID,args);
}
jdouble CallNonvirtualDoubleMethodA(jobject obj, jclass clazz,
jmethodID methodID,
const jvalue * args) {
return functions->CallNonvirtualDoubleMethodA(this,obj,clazz,
methodID,args);
}
void CallNonvirtualVoidMethod(jobject obj, jclass clazz,
jmethodID methodID, ...) {
va_list args;
va_start(args,methodID);
functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);
va_end(args);
}
void CallNonvirtualVoidMethodV(jobject obj, jclass clazz,
jmethodID methodID,
va_list args) {
functions->CallNonvirtualVoidMethodV(this,obj,clazz,methodID,args);
}
void CallNonvirtualVoidMethodA(jobject obj, jclass clazz,
jmethodID methodID,
const jvalue * args) {
functions->CallNonvirtualVoidMethodA(this,obj,clazz,methodID,args);
}
jfieldID GetFieldID(jclass clazz, const char *name,
const char *sig) {
return functions->GetFieldID(this,clazz,name,sig);
}
jobject GetObjectField(jobject obj, jfieldID fieldID) {
return functions->GetObjectField(this,obj,fieldID);
}
jboolean GetBooleanField(jobject obj, jfieldID fieldID) {
return functions->GetBooleanField(this,obj,fieldID);
}
jbyte GetByteField(jobject obj, jfieldID fieldID) {
return functions->GetByteField(this,obj,fieldID);
}
jchar GetCharField(jobject obj, jfieldID fieldID) {
return functions->GetCharField(this,obj,fieldID);
}
jshort GetShortField(jobject obj, jfieldID fieldID) {
return functions->GetShortField(this,obj,fieldID);
}
jint GetIntField(jobject obj, jfieldID fieldID) {
return functions->GetIntField(this,obj,fieldID);
}
jlong GetLongField(jobject obj, jfieldID fieldID) {
return functions->GetLongField(this,obj,fieldID);
}
jfloat GetFloatField(jobject obj, jfieldID fieldID) {
return functions->GetFloatField(this,obj,fieldID);
}
jdouble GetDoubleField(jobject obj, jfieldID fieldID) {
return functions->GetDoubleField(this,obj,fieldID);
}
void SetObjectField(jobject obj, jfieldID fieldID, jobject val) {
functions->SetObjectField(this,obj,fieldID,val);
}
void SetBooleanField(jobject obj, jfieldID fieldID,
jboolean val) {
functions->SetBooleanField(this,obj,fieldID,val);
}
void SetByteField(jobject obj, jfieldID fieldID,
jbyte val) {
functions->SetByteField(this,obj,fieldID,val);
}
void SetCharField(jobject obj, jfieldID fieldID,
jchar val) {
functions->SetCharField(this,obj,fieldID,val);
}
void SetShortField(jobject obj, jfieldID fieldID,
jshort val) {
functions->SetShortField(this,obj,fieldID,val);
}
void SetIntField(jobject obj, jfieldID fieldID,
jint val) {
functions->SetIntField(this,obj,fieldID,val);
}
void SetLongField(jobject obj, jfieldID fieldID,
jlong val) {
functions->SetLongField(this,obj,fieldID,val);
}
void SetFloatField(jobject obj, jfieldID fieldID,
jfloat val) {
functions->SetFloatField(this,obj,fieldID,val);
}
void SetDoubleField(jobject obj, jfieldID fieldID,
jdouble val) {
functions->SetDoubleField(this,obj,fieldID,val);
}
jmethodID GetStaticMethodID(jclass clazz, const char *name,
const char *sig) {
return functions->GetStaticMethodID(this,clazz,name,sig);
}
jobject CallStaticObjectMethod(jclass clazz, jmethodID methodID,
...) {
va_list args;
jobject result;
va_start(args,methodID);
result = functions->CallStaticObjectMethodV(this,clazz,methodID,args);
va_end(args);
return result;
}
jobject CallStaticObjectMethodV(jclass clazz, jmethodID methodID,
va_list args) {
return functions->CallStaticObjectMethodV(this,clazz,methodID,args);
}
jobject CallStaticObjectMethodA(jclass clazz, jmethodID methodID,
const jvalue *args) {
return functions->CallStaticObjectMethodA(this,clazz,methodID,args);
}
jboolean CallStaticBooleanMethod(jclass clazz,
jmethodID methodID, ...) {
va_list args;
jboolean result;
va_start(args,methodID);
result = functions->CallStaticBooleanMethodV(this,clazz,methodID,args);
va_end(args);
return result;
}
jboolean CallStaticBooleanMethodV(jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallStaticBooleanMethodV(this,clazz,methodID,args);
}
jboolean CallStaticBooleanMethodA(jclass clazz,
jmethodID methodID, const jvalue *args) {
return functions->CallStaticBooleanMethodA(this,clazz,methodID,args);
}
jbyte CallStaticByteMethod(jclass clazz,
jmethodID methodID, ...) {
va_list args;
jbyte result;
va_start(args,methodID);
result = functions->CallStaticByteMethodV(this,clazz,methodID,args);
va_end(args);
return result;
}
jbyte CallStaticByteMethodV(jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallStaticByteMethodV(this,clazz,methodID,args);
}
jbyte CallStaticByteMethodA(jclass clazz,
jmethodID methodID, const jvalue *args) {
return functions->CallStaticByteMethodA(this,clazz,methodID,args);
}
jchar CallStaticCharMethod(jclass clazz,
jmethodID methodID, ...) {
va_list args;
jchar result;
va_start(args,methodID);
result = functions->CallStaticCharMethodV(this,clazz,methodID,args);
va_end(args);
return result;
}
jchar CallStaticCharMethodV(jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallStaticCharMethodV(this,clazz,methodID,args);
}
jchar CallStaticCharMethodA(jclass clazz,
jmethodID methodID, const jvalue *args) {
return functions->CallStaticCharMethodA(this,clazz,methodID,args);
}
jshort CallStaticShortMethod(jclass clazz,
jmethodID methodID, ...) {
va_list args;
jshort result;
va_start(args,methodID);
result = functions->CallStaticShortMethodV(this,clazz,methodID,args);
va_end(args);
return result;
}
jshort CallStaticShortMethodV(jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallStaticShortMethodV(this,clazz,methodID,args);
}
jshort CallStaticShortMethodA(jclass clazz,
jmethodID methodID, const jvalue *args) {
return functions->CallStaticShortMethodA(this,clazz,methodID,args);
}
jint CallStaticIntMethod(jclass clazz,
jmethodID methodID, ...) {
va_list args;
jint result;
va_start(args,methodID);
result = functions->CallStaticIntMethodV(this,clazz,methodID,args);
va_end(args);
return result;
}
jint CallStaticIntMethodV(jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallStaticIntMethodV(this,clazz,methodID,args);
}
jint CallStaticIntMethodA(jclass clazz,
jmethodID methodID, const jvalue *args) {
return functions->CallStaticIntMethodA(this,clazz,methodID,args);
}
jlong CallStaticLongMethod(jclass clazz,
jmethodID methodID, ...) {
va_list args;
jlong result;
va_start(args,methodID);
result = functions->CallStaticLongMethodV(this,clazz,methodID,args);
va_end(args);
return result;
}
jlong CallStaticLongMethodV(jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallStaticLongMethodV(this,clazz,methodID,args);
}
jlong CallStaticLongMethodA(jclass clazz,
jmethodID methodID, const jvalue *args) {
return functions->CallStaticLongMethodA(this,clazz,methodID,args);
}
jfloat CallStaticFloatMethod(jclass clazz,
jmethodID methodID, ...) {
va_list args;
jfloat result;
va_start(args,methodID);
result = functions->CallStaticFloatMethodV(this,clazz,methodID,args);
va_end(args);
return result;
}
jfloat CallStaticFloatMethodV(jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallStaticFloatMethodV(this,clazz,methodID,args);
}
jfloat CallStaticFloatMethodA(jclass clazz,
jmethodID methodID, const jvalue *args) {
return functions->CallStaticFloatMethodA(this,clazz,methodID,args);
}
jdouble CallStaticDoubleMethod(jclass clazz,
jmethodID methodID, ...) {
va_list args;
jdouble result;
va_start(args,methodID);
result = functions->CallStaticDoubleMethodV(this,clazz,methodID,args);
va_end(args);
return result;
}
jdouble CallStaticDoubleMethodV(jclass clazz,
jmethodID methodID, va_list args) {
return functions->CallStaticDoubleMethodV(this,clazz,methodID,args);
}
jdouble CallStaticDoubleMethodA(jclass clazz,
jmethodID methodID, const jvalue *args) {
return functions->CallStaticDoubleMethodA(this,clazz,methodID,args);
}
void CallStaticVoidMethod(jclass cls, jmethodID methodID, ...) {
va_list args;
va_start(args,methodID);
functions->CallStaticVoidMethodV(this,cls,methodID,args);
va_end(args);
}
void CallStaticVoidMethodV(jclass cls, jmethodID methodID,
va_list args) {
functions->CallStaticVoidMethodV(this,cls,methodID,args);
}
void CallStaticVoidMethodA(jclass cls, jmethodID methodID,
const jvalue * args) {
functions->CallStaticVoidMethodA(this,cls,methodID,args);
}
jfieldID GetStaticFieldID(jclass clazz, const char *name,
const char *sig) {
return functions->GetStaticFieldID(this,clazz,name,sig);
}
jobject GetStaticObjectField(jclass clazz, jfieldID fieldID) {
return functions->GetStaticObjectField(this,clazz,fieldID);
}
jboolean GetStaticBooleanField(jclass clazz, jfieldID fieldID) {
return functions->GetStaticBooleanField(this,clazz,fieldID);
}
jbyte GetStaticByteField(jclass clazz, jfieldID fieldID) {
return functions->GetStaticByteField(this,clazz,fieldID);
}
jchar GetStaticCharField(jclass clazz, jfieldID fieldID) {
return functions->GetStaticCharField(this,clazz,fieldID);
}
jshort GetStaticShortField(jclass clazz, jfieldID fieldID) {
return functions->GetStaticShortField(this,clazz,fieldID);
}
jint GetStaticIntField(jclass clazz, jfieldID fieldID) {
return functions->GetStaticIntField(this,clazz,fieldID);
}
jlong GetStaticLongField(jclass clazz, jfieldID fieldID) {
return functions->GetStaticLongField(this,clazz,fieldID);
}
jfloat GetStaticFloatField(jclass clazz, jfieldID fieldID) {
return functions->GetStaticFloatField(this,clazz,fieldID);
}
jdouble GetStaticDoubleField(jclass clazz, jfieldID fieldID) {
return functions->GetStaticDoubleField(this,clazz,fieldID);
}
void SetStaticObjectField(jclass clazz, jfieldID fieldID,
jobject value) {
functions->SetStaticObjectField(this,clazz,fieldID,value);
}
void SetStaticBooleanField(jclass clazz, jfieldID fieldID,
jboolean value) {
functions->SetStaticBooleanField(this,clazz,fieldID,value);
}
void SetStaticByteField(jclass clazz, jfieldID fieldID,
jbyte value) {
functions->SetStaticByteField(this,clazz,fieldID,value);
}
void SetStaticCharField(jclass clazz, jfieldID fieldID,
jchar value) {
functions->SetStaticCharField(this,clazz,fieldID,value);
}
void SetStaticShortField(jclass clazz, jfieldID fieldID,
jshort value) {
functions->SetStaticShortField(this,clazz,fieldID,value);
}
void SetStaticIntField(jclass clazz, jfieldID fieldID,
jint value) {
functions->SetStaticIntField(this,clazz,fieldID,value);
}
void SetStaticLongField(jclass clazz, jfieldID fieldID,
jlong value) {
functions->SetStaticLongField(this,clazz,fieldID,value);
}
void SetStaticFloatField(jclass clazz, jfieldID fieldID,
jfloat value) {
functions->SetStaticFloatField(this,clazz,fieldID,value);
}
void SetStaticDoubleField(jclass clazz, jfieldID fieldID,
jdouble value) {
functions->SetStaticDoubleField(this,clazz,fieldID,value);
}
jstring NewString(const jchar *unicode, jsize len) {
return functions->NewString(this,unicode,len);
}
jsize GetStringLength(jstring str) {
return functions->GetStringLength(this,str);
}
const jchar *GetStringChars(jstring str, jboolean *isCopy) {
return functions->GetStringChars(this,str,isCopy);
}
void ReleaseStringChars(jstring str, const jchar *chars) {
functions->ReleaseStringChars(this,str,chars);
}
jstring NewStringUTF(const char *utf) {
return functions->NewStringUTF(this,utf);
}
jsize GetStringUTFLength(jstring str) {
return functions->GetStringUTFLength(this,str);
}
const char* GetStringUTFChars(jstring str, jboolean *isCopy) {
return functions->GetStringUTFChars(this,str,isCopy);
}
void ReleaseStringUTFChars(jstring str, const char* chars) {
functions->ReleaseStringUTFChars(this,str,chars);
}
jsize GetArrayLength(jarray array) {
return functions->GetArrayLength(this,array);
}
jobjectArray NewObjectArray(jsize len, jclass clazz,
jobject init) {
return functions->NewObjectArray(this,len,clazz,init);
}
jobject GetObjectArrayElement(jobjectArray array, jsize index) {
return functions->GetObjectArrayElement(this,array,index);
}
void SetObjectArrayElement(jobjectArray array, jsize index,
jobject val) {
functions->SetObjectArrayElement(this,array,index,val);
}
jbooleanArray NewBooleanArray(jsize len) {
return functions->NewBooleanArray(this,len);
}
jbyteArray NewByteArray(jsize len) {
return functions->NewByteArray(this,len);
}
jcharArray NewCharArray(jsize len) {
return functions->NewCharArray(this,len);
}
jshortArray NewShortArray(jsize len) {
return functions->NewShortArray(this,len);
}
jintArray NewIntArray(jsize len) {
return functions->NewIntArray(this,len);
}
jlongArray NewLongArray(jsize len) {
return functions->NewLongArray(this,len);
}
jfloatArray NewFloatArray(jsize len) {
return functions->NewFloatArray(this,len);
}
jdoubleArray NewDoubleArray(jsize len) {
return functions->NewDoubleArray(this,len);
}
jboolean * GetBooleanArrayElements(jbooleanArray array, jboolean *isCopy) {
return functions->GetBooleanArrayElements(this,array,isCopy);
}
jbyte * GetByteArrayElements(jbyteArray array, jboolean *isCopy) {
return functions->GetByteArrayElements(this,array,isCopy);
}
jchar * GetCharArrayElements(jcharArray array, jboolean *isCopy) {
return functions->GetCharArrayElements(this,array,isCopy);
}
jshort * GetShortArrayElements(jshortArray array, jboolean *isCopy) {
return functions->GetShortArrayElements(this,array,isCopy);
}
jint * GetIntArrayElements(jintArray array, jboolean *isCopy) {
return functions->GetIntArrayElements(this,array,isCopy);
}
jlong * GetLongArrayElements(jlongArray array, jboolean *isCopy) {
return functions->GetLongArrayElements(this,array,isCopy);
}
jfloat * GetFloatArrayElements(jfloatArray array, jboolean *isCopy) {
return functions->GetFloatArrayElements(this,array,isCopy);
}
jdouble * GetDoubleArrayElements(jdoubleArray array, jboolean *isCopy) {
return functions->GetDoubleArrayElements(this,array,isCopy);
}
void ReleaseBooleanArrayElements(jbooleanArray array,
jboolean *elems,
jint mode) {
functions->ReleaseBooleanArrayElements(this,array,elems,mode);
}
void ReleaseByteArrayElements(jbyteArray array,
jbyte *elems,
jint mode) {
functions->ReleaseByteArrayElements(this,array,elems,mode);
}
void ReleaseCharArrayElements(jcharArray array,
jchar *elems,
jint mode) {
functions->ReleaseCharArrayElements(this,array,elems,mode);
}
void ReleaseShortArrayElements(jshortArray array,
jshort *elems,
jint mode) {
functions->ReleaseShortArrayElements(this,array,elems,mode);
}
void ReleaseIntArrayElements(jintArray array,
jint *elems,
jint mode) {
functions->ReleaseIntArrayElements(this,array,elems,mode);
}
void ReleaseLongArrayElements(jlongArray array,
jlong *elems,
jint mode) {
functions->ReleaseLongArrayElements(this,array,elems,mode);
}
void ReleaseFloatArrayElements(jfloatArray array,
jfloat *elems,
jint mode) {
functions->ReleaseFloatArrayElements(this,array,elems,mode);
}
void ReleaseDoubleArrayElements(jdoubleArray array,
jdouble *elems,
jint mode) {
functions->ReleaseDoubleArrayElements(this,array,elems,mode);
}
void GetBooleanArrayRegion(jbooleanArray array,
jsize start, jsize len, jboolean *buf) {
functions->GetBooleanArrayRegion(this,array,start,len,buf);
}
void GetByteArrayRegion(jbyteArray array,
jsize start, jsize len, jbyte *buf) {
functions->GetByteArrayRegion(this,array,start,len,buf);
}
void GetCharArrayRegion(jcharArray array,
jsize start, jsize len, jchar *buf) {
functions->GetCharArrayRegion(this,array,start,len,buf);
}
void GetShortArrayRegion(jshortArray array,
jsize start, jsize len, jshort *buf) {
functions->GetShortArrayRegion(this,array,start,len,buf);
}
void GetIntArrayRegion(jintArray array,
jsize start, jsize len, jint *buf) {
functions->GetIntArrayRegion(this,array,start,len,buf);
}
void GetLongArrayRegion(jlongArray array,
jsize start, jsize len, jlong *buf) {
functions->GetLongArrayRegion(this,array,start,len,buf);
}
void GetFloatArrayRegion(jfloatArray array,
jsize start, jsize len, jfloat *buf) {
functions->GetFloatArrayRegion(this,array,start,len,buf);
}
void GetDoubleArrayRegion(jdoubleArray array,
jsize start, jsize len, jdouble *buf) {
functions->GetDoubleArrayRegion(this,array,start,len,buf);
}
void SetBooleanArrayRegion(jbooleanArray array, jsize start, jsize len,
const jboolean *buf) {
functions->SetBooleanArrayRegion(this,array,start,len,buf);
}
void SetByteArrayRegion(jbyteArray array, jsize start, jsize len,
const jbyte *buf) {
functions->SetByteArrayRegion(this,array,start,len,buf);
}
void SetCharArrayRegion(jcharArray array, jsize start, jsize len,
const jchar *buf) {
functions->SetCharArrayRegion(this,array,start,len,buf);
}
void SetShortArrayRegion(jshortArray array, jsize start, jsize len,
const jshort *buf) {
functions->SetShortArrayRegion(this,array,start,len,buf);
}
void SetIntArrayRegion(jintArray array, jsize start, jsize len,
const jint *buf) {
functions->SetIntArrayRegion(this,array,start,len,buf);
}
void SetLongArrayRegion(jlongArray array, jsize start, jsize len,
const jlong *buf) {
functions->SetLongArrayRegion(this,array,start,len,buf);
}
void SetFloatArrayRegion(jfloatArray array, jsize start, jsize len,
const jfloat *buf) {
functions->SetFloatArrayRegion(this,array,start,len,buf);
}
void SetDoubleArrayRegion(jdoubleArray array, jsize start, jsize len,
const jdouble *buf) {
functions->SetDoubleArrayRegion(this,array,start,len,buf);
}
jint RegisterNatives(jclass clazz, const JNINativeMethod *methods,
jint nMethods) {
return functions->RegisterNatives(this,clazz,methods,nMethods);
}
jint UnregisterNatives(jclass clazz) {
return functions->UnregisterNatives(this,clazz);
}
jint MonitorEnter(jobject obj) {
return functions->MonitorEnter(this,obj);
}
jint MonitorExit(jobject obj) {
return functions->MonitorExit(this,obj);
}
jint GetJavaVM(JavaVM **vm) {
return functions->GetJavaVM(this,vm);
}
void GetStringRegion(jstring str, jsize start, jsize len, jchar *buf) {
functions->GetStringRegion(this,str,start,len,buf);
}
void GetStringUTFRegion(jstring str, jsize start, jsize len, char *buf) {
functions->GetStringUTFRegion(this,str,start,len,buf);
}
void * GetPrimitiveArrayCritical(jarray array, jboolean *isCopy) {
return functions->GetPrimitiveArrayCritical(this,array,isCopy);
}
void ReleasePrimitiveArrayCritical(jarray array, void *carray, jint mode) {
functions->ReleasePrimitiveArrayCritical(this,array,carray,mode);
}
const jchar * GetStringCritical(jstring string, jboolean *isCopy) {
return functions->GetStringCritical(this,string,isCopy);
}
void ReleaseStringCritical(jstring string, const jchar *cstring) {
functions->ReleaseStringCritical(this,string,cstring);
}
jweak NewWeakGlobalRef(jobject obj) {
return functions->NewWeakGlobalRef(this,obj);
}
void DeleteWeakGlobalRef(jweak ref) {
functions->DeleteWeakGlobalRef(this,ref);
}
jboolean ExceptionCheck() {
return functions->ExceptionCheck(this);
}
jobject NewDirectByteBuffer(void* address, jlong capacity) {
return functions->NewDirectByteBuffer(this, address, capacity);
}
void* GetDirectBufferAddress(jobject buf) {
return functions->GetDirectBufferAddress(this, buf);
}
jlong GetDirectBufferCapacity(jobject buf) {
return functions->GetDirectBufferCapacity(this, buf);
}
jobjectRefType GetObjectRefType(jobject obj) {
return functions->GetObjectRefType(this, obj);
}
/* Module Features */
jobject GetModule(jclass clazz) {
return functions->GetModule(this, clazz);
}
/* Virtual threads */
jboolean IsVirtualThread(jobject obj) {
return functions->IsVirtualThread(this, obj);
}
#endif /* __cplusplus */
};
/*
* optionString may be any option accepted by the JVM, or one of the
* following:
*
* -D<name>=<value> Set a system property.
* -verbose[:class|gc|jni] Enable verbose output, comma-separated. E.g.
* "-verbose:class" or "-verbose:gc,class"
* Standard names include: gc, class, and jni.
* All nonstandard (VM-specific) names must begin
* with "X".
* vfprintf extraInfo is a pointer to the vfprintf hook.
* exit extraInfo is a pointer to the exit hook.
* abort extraInfo is a pointer to the abort hook.
*/
typedef struct JavaVMOption {
char *optionString;
void *extraInfo;
} JavaVMOption;
typedef struct JavaVMInitArgs {
jint version;
jint nOptions;
JavaVMOption *options;
jboolean ignoreUnrecognized;
} JavaVMInitArgs;
typedef struct JavaVMAttachArgs {
jint version;
char *name;
jobject group;
} JavaVMAttachArgs;
/* These will be VM-specific. */
#define JDK1_2
#define JDK1_4
/* End VM-specific. */
struct JNIInvokeInterface_ {
void *reserved0;
void *reserved1;
void *reserved2;
jint (JNICALL *DestroyJavaVM)(JavaVM *vm);
jint (JNICALL *AttachCurrentThread)(JavaVM *vm, void **penv, void *args);
jint (JNICALL *DetachCurrentThread)(JavaVM *vm);
jint (JNICALL *GetEnv)(JavaVM *vm, void **penv, jint version);
jint (JNICALL *AttachCurrentThreadAsDaemon)(JavaVM *vm, void **penv, void *args);
};
struct JavaVM_ {
const struct JNIInvokeInterface_ *functions;
#ifdef __cplusplus
jint DestroyJavaVM() {
return functions->DestroyJavaVM(this);
}
jint AttachCurrentThread(void **penv, void *args) {
return functions->AttachCurrentThread(this, penv, args);
}
jint DetachCurrentThread() {
return functions->DetachCurrentThread(this);
}
jint GetEnv(void **penv, jint version) {
return functions->GetEnv(this, penv, version);
}
jint AttachCurrentThreadAsDaemon(void **penv, void *args) {
return functions->AttachCurrentThreadAsDaemon(this, penv, args);
}
#endif
};
#ifdef _JNI_IMPLEMENTATION_
#define _JNI_IMPORT_OR_EXPORT_ JNIEXPORT
#else
#define _JNI_IMPORT_OR_EXPORT_ JNIIMPORT
#endif
_JNI_IMPORT_OR_EXPORT_ jint JNICALL
JNI_GetDefaultJavaVMInitArgs(void *args);
_JNI_IMPORT_OR_EXPORT_ jint JNICALL
JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args);
_JNI_IMPORT_OR_EXPORT_ jint JNICALL
JNI_GetCreatedJavaVMs(JavaVM **, jsize, jsize *);
/* Defined by native libraries. */
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *vm, void *reserved);
JNIEXPORT void JNICALL
JNI_OnUnload(JavaVM *vm, void *reserved);
#define JNI_VERSION_1_1 0x00010001
#define JNI_VERSION_1_2 0x00010002
#define JNI_VERSION_1_4 0x00010004
#define JNI_VERSION_1_6 0x00010006
#define JNI_VERSION_1_8 0x00010008
#define JNI_VERSION_9 0x00090000
#define JNI_VERSION_10 0x000a0000
#define JNI_VERSION_19 0x00130000
#define JNI_VERSION_20 0x00140000
#define JNI_VERSION_21 0x00150000
#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */
#endif /* !_JAVASOFT_JNI_H_ */
vendor/yokan-ext/src/nativeInterop/cinterop/jni_md.h
- Source · implementation · 66 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Exact file bytes / download · SHA-256 88cb5c33e306900dd35a78d5a439087123b8e91b0986bb5acb42cc9bd2fcc42e.
Complete file
/*
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#ifndef _JAVASOFT_JNI_MD_H_
#define _JAVASOFT_JNI_MD_H_
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#ifndef JNIEXPORT
#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
#ifdef ARM
#define JNIEXPORT __attribute__((externally_visible,visibility("default")))
#else
#define JNIEXPORT __attribute__((visibility("default")))
#endif
#else
#define JNIEXPORT
#endif
#endif
#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
#ifdef ARM
#define JNIIMPORT __attribute__((externally_visible,visibility("default")))
#else
#define JNIIMPORT __attribute__((visibility("default")))
#endif
#else
#define JNIIMPORT
#endif
#define JNICALL
typedef int jint;
#ifdef _LP64
typedef long jlong;
#else
typedef long long jlong;
#endif
typedef signed char jbyte;
#endif /* !_JAVASOFT_JNI_MD_H_ */