Overhaul 2025 (See PR for changes)

This commit is contained in:
Mio.
2025-06-27 23:44:38 +02:00
parent c52d8831aa
commit 965c2a4f43
81 changed files with 4404 additions and 2086 deletions

View File

@@ -1,12 +1,14 @@
# Editor configuration, see https://editorconfig.org # Editor configuration, see https://editorconfig.org
root = true root = true
[*]
insert_final_newline = true
end_of_line = lf
[*.kt] [*.kt]
charset = utf-8 charset = utf-8
end_of_line = lf
indent_size = 4 indent_size = 4
indent_style = space indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true trim_trailing_whitespace = true
ij_kotlin_allow_trailing_comma = true ij_kotlin_allow_trailing_comma = true
ij_kotlin_allow_trailing_comma_on_call_site = true ij_kotlin_allow_trailing_comma_on_call_site = true
@@ -15,5 +17,3 @@ ij_kotlin_name_count_to_use_star_import_for_members = 2147483647
[*.properties] [*.properties]
charset = utf-8 charset = utf-8
end_of_line = lf
insert_final_newline = true

View File

@@ -2,11 +2,11 @@
I acknowledge that: I acknowledge that:
- I have updated to the latest version of the app (stable is v0.14.7) - I have updated to the latest version of the app (stable is v0.15.1)
- I have updated all extensions - I have updated all extensions
- If this is an issue with the app itself, that I should be opening an issue in https://github.com/tachiyomiorg/tachiyomi - If this is an issue with the app itself, that I should be opening an issue in https://github.com/tachiyomiorg/tachiyomi
- I have searched the existing issues for duplicates - I have searched the existing issues for duplicates
- For source requests, I have checked the list of existing extensions including the multi-source spreadsheet: https://tachiyomi.org/extensions/
**DELETE THIS SECTION IF YOU HAVE READ AND ACKNOWLEDGED IT** **DELETE THIS SECTION IF YOU HAVE READ AND ACKNOWLEDGED IT**

View File

@@ -7,3 +7,4 @@ Checklist:
- [ ] Have not changed source names - [ ] Have not changed source names
- [ ] Have explicitly kept the `id` if a source's name or language were changed - [ ] Have explicitly kept the `id` if a source's name or language were changed
- [ ] Have tested the modifications by compiling and running the extension through Android Studio - [ ] Have tested the modifications by compiling and running the extension through Android Studio
- [ ] Have removed `web_hi_res_512.png` when adding a new extension

40
.github/renovate.json vendored
View File

@@ -1,8 +1,44 @@
{ {
"labels": [
"Dependencies"
],
"rebaseWhen": "conflicted",
"automerge": true,
"semanticCommits": "enabled",
"extends": [ "extends": [
"config:base" "config:best-practices"
],
"schedule": [
"on sunday"
], ],
"includePaths": [ "includePaths": [
"buildSrc/gradle/**",
"gradle/**",
".github/**" ".github/**"
],
"ignoreDeps": [
"keiyoushi/issue-moderator-action"
],
"packageRules": [
{
"matchManagers": [
"github-actions"
],
"groupName": "{{manager}} dependencies"
},
{
"matchManagers": [
"gradle"
],
"enabled": false
},
{
"matchPackageNames": [
"com.android.tools.build:gradle",
"gradle"
],
"draftPR": true,
"enabled": true
}
] ]
} }

View File

@@ -1,17 +0,0 @@
#!/bin/bash
set -e
rsync -a --delete --exclude .git --exclude .gitignore ../master/repo/ .
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git config --global user.name "github-actions[bot]"
git status
if [ -n "$(git status --porcelain)" ]; then
git add .
git commit -m "Update extensions repo"
git push
# Purge cached index on jsDelivr
curl https://purge.jsdelivr.net/gh/tachiyomiorg/tachiyomi-extensions@repo/index.min.json
else
echo "No changes to commit"
fi

View File

@@ -1,69 +0,0 @@
#!/bin/bash
set -e
TOOLS="$(ls -d ${ANDROID_HOME}/build-tools/* | tail -1)"
mkdir -p repo/apk
mkdir -p repo/icon
cp -f apk/* repo/apk
cd repo
APKS=( ../apk/*".apk" )
for APK in ${APKS[@]}; do
FILENAME=$(basename ${APK})
BADGING="$(${TOOLS}/aapt dump --include-meta-data badging $APK)"
PACKAGE=$(echo "$BADGING" | grep package:)
PKGNAME=$(echo $PACKAGE | grep -Po "package: name='\K[^']+")
VCODE=$(echo $PACKAGE | grep -Po "versionCode='\K[^']+")
VNAME=$(echo $PACKAGE | grep -Po "versionName='\K[^']+")
NSFW=$(echo $BADGING | grep -Po "tachiyomi.extension.nsfw' value='\K[^']+")
HASREADME=$(echo $BADGING | grep -Po "tachiyomi.extension.hasReadme' value='\K[^']+")
HASCHANGELOG=$(echo $BADGING | grep -Po "tachiyomi.extension.hasChangelog' value='\K[^']+")
APPLICATION=$(echo "$BADGING" | grep application:)
LABEL=$(echo $APPLICATION | grep -Po "label='\K[^']+")
LANG=$(echo $APK | grep -Po "tachiyomi-\K[^\.]+")
ICON=$(echo "$BADGING" | grep -Po "application-icon-320.*'\K[^']+")
unzip -p $APK $ICON > icon/${PKGNAME}.png
# TODO: legacy icons; remove after a while
cp icon/${PKGNAME}.png icon/${FILENAME%.*}.png
SOURCE_INFO=$(jq ".[\"$PKGNAME\"]" < ../output.json)
# Fixes the language code without needing to update the packages.
SOURCE_LEN=$(echo $SOURCE_INFO | jq length)
if [ $SOURCE_LEN = "1" ]; then
SOURCE_LANG=$(echo $SOURCE_INFO | jq -r '.[0].lang')
if [ $SOURCE_LANG != $LANG ] && [ $SOURCE_LANG != "all" ] && [ $SOURCE_LANG != "other" ] && [ $LANG != "all" ] && [ $LANG != "other" ]; then
LANG=$SOURCE_LANG
fi
fi
jq -n \
--arg name "$LABEL" \
--arg pkg "$PKGNAME" \
--arg apk "$FILENAME" \
--arg lang "$LANG" \
--argjson code $VCODE \
--arg version "$VNAME" \
--argjson nsfw $NSFW \
--argjson hasReadme $HASREADME \
--argjson hasChangelog $HASCHANGELOG \
--argjson sources "$SOURCE_INFO" \
'{name:$name, pkg:$pkg, apk:$apk, lang:$lang, code:$code, version:$version, nsfw:$nsfw, hasReadme:$hasReadme, hasChangelog:$hasChangelog, sources:$sources}'
done | jq -sr '[.[]]' > index.json
# Alternate minified copy
jq -c '.' < index.json > index.min.json
cat index.json

View File

@@ -1,26 +0,0 @@
#!/bin/bash
set -e
shopt -s globstar nullglob extglob
# Get APKs from previous jobs' artifacts
cp -R ~/apk-artifacts/ $PWD
APKS=( **/*".apk" )
# Fail if too little extensions seem to have been built
#if [ "${#APKS[@]}" -le "100" ]; then
# echo "Insufficient amount of APKs found. Please check the project configuration."
# exit 1
#else
echo "Moving ${#APKS[@]} APKs"
#fi
DEST=$PWD/apk
rm -rf $DEST && mkdir -p $DEST
for APK in ${APKS[@]}; do
BASENAME=$(basename $APK)
APKNAME="${BASENAME%%+(-release*)}.apk"
APKDEST="$DEST/$APKNAME"
cp $APK $APKDEST
done

View File

@@ -1,25 +0,0 @@
name: "Batch close stale issues"
on:
# Monthly
schedule:
- cron: '0 0 1 * *'
# Manual trigger
workflow_dispatch:
inputs:
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
# Close everything older than a year
days-before-issue-stale: 365
days-before-issue-close: 0
exempt-issue-labels: "do-not-autoclose,Meta request"
close-issue-message: "In an effort to have a more manageable issue backlog, we're closing older requests that weren't addressed since there's a low chance of it being addressed if it hasn't already. If your request is still relevant, please [open a new request](https://github.com/tachiyomiorg/tachiyomi-extensions/issues/new/choose)."
close-issue-reason: not_planned
ascending: true
operations-per-run: 250

View File

@@ -1,10 +1,12 @@
name: PR build check name: PR check
on: on:
pull_request: pull_request:
paths-ignore: paths:
- '**.md' - '**'
- '.github/workflows/issue_moderator.yml' - '!**.md'
- '!.github/**'
- '.github/workflows/build_pull_request.yml'
concurrency: concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }} group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
@@ -12,146 +14,59 @@ concurrency:
env: env:
CI_CHUNK_SIZE: 65 CI_CHUNK_SIZE: 65
IS_PR_CHECK: true
jobs: jobs:
prepare: prepare:
name: Prepare job name: Prepare job
runs-on: ubuntu-latest runs-on: 'ubuntu-24.04'
outputs: outputs:
individualMatrix: ${{ steps.generate-matrices.outputs.individualMatrix }} matrix: ${{ steps.generate-matrices.outputs.matrix }}
multisrcMatrix: ${{ steps.generate-matrices.outputs.multisrcMatrix }} delete: ${{ steps.generate-matrices.outputs.delete }}
isIndividualChanged: ${{ steps.parse-changed-files.outputs.isIndividualChanged }}
isMultisrcChanged: ${{ steps.parse-changed-files.outputs.isMultisrcChanged }}
env:
CI_MODULE_GEN: true
steps: steps:
- name: Clone repo - name: Checkout PR
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Validate Gradle Wrapper
uses: gradle/wrapper-validation-action@v1
- name: Set up JDK
uses: actions/setup-java@v4
with: with:
java-version: 11 fetch-depth: 0
distribution: adopt
- id: get-changed-files - name: Set up Java
name: Get changed files uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
uses: Ana06/get-changed-files@v2.2.0
- id: parse-changed-files
name: Parse changed files
run: |
isIndividualChanged=0
isMultisrcChanged=0
for changedFile in ${{ steps.get-changed-files.outputs.all }}; do
if [[ ${changedFile} == src/* ]]; then
isIndividualChanged=1
elif [[ ${changedFile} == multisrc/* ]]; then
isMultisrcChanged=1
elif [[ ${changedFile} == .github/workflows/issue_moderator.yml ]]; then
true
elif [[ ${changedFile} == *.md ]]; then
true
else
isIndividualChanged=1
isMultisrcChanged=1
break
fi
done
echo "isIndividualChanged=$isIndividualChanged" >> $GITHUB_OUTPUT
echo "isMultisrcChanged=$isMultisrcChanged" >> $GITHUB_OUTPUT
- name: Generate multisrc sources
if: ${{ steps.parse-changed-files.outputs.isMultisrcChanged == '1' }}
uses: gradle/gradle-build-action@v2
with: with:
arguments: :multisrc:generateExtensions java-version: 17
distribution: temurin
- name: Get number of modules - name: Set up Gradle
run: | uses: gradle/actions/setup-gradle@06832c7b30a0129d7fb559bcc6e43d26f6374244 # v4.3.1
set -x with:
./gradlew -q projects | grep '.*extensions\:\(individual\|multisrc\)\:.*\:.*' > projects.txt cache-read-only: true
echo "NUM_INDIVIDUAL_MODULES=$(cat projects.txt | grep '.*\:individual\:.*' | wc -l)" >> $GITHUB_ENV
echo "NUM_MULTISRC_MODULES=$(cat projects.txt | grep '.*\:multisrc\:.*' | wc -l)" >> $GITHUB_ENV
- id: generate-matrices - id: generate-matrices
name: Create output matrices name: Generate build matrices
uses: actions/github-script@v7 run: |
with: python ./.github/scripts/generate-build-matrices.py origin/master Debug
script: |
const numIndividualModules = process.env.NUM_INDIVIDUAL_MODULES;
const numMultisrcModules = process.env.NUM_MULTISRC_MODULES;
const chunkSize = process.env.CI_CHUNK_SIZE;
const numIndividualChunks = Math.ceil(numIndividualModules / chunkSize); build:
const numMultisrcChunks = Math.ceil(numMultisrcModules / chunkSize); name: Build extensions (${{ matrix.chunk.number }})
console.log(`Individual modules: ${numIndividualModules} (${numIndividualChunks} chunks of ${chunkSize})`);
console.log(`Multi-source modules: ${numMultisrcModules} (${numMultisrcChunks} chunks of ${chunkSize})`);
core.setOutput('individualMatrix', { 'chunk': [...Array(numIndividualChunks).keys()] });
core.setOutput('multisrcMatrix', { 'chunk': [...Array(numMultisrcChunks).keys()] });
build_multisrc:
name: Build multisrc modules
needs: prepare needs: prepare
if: ${{ needs.prepare.outputs.isMultisrcChanged == '1' }} runs-on: 'ubuntu-24.04'
runs-on: ubuntu-latest if: ${{ toJson(fromJson(needs.prepare.outputs.matrix).chunk) != '[]' }}
strategy: strategy:
matrix: ${{ fromJSON(needs.prepare.outputs.multisrcMatrix) }} matrix: ${{ fromJSON(needs.prepare.outputs.matrix) }}
steps: steps:
- name: Checkout PR - name: Checkout PR
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Set up JDK - name: Set up Java
uses: actions/setup-java@v4 uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
with: with:
java-version: 11 java-version: 17
distribution: adopt distribution: temurin
- name: Generate sources from the multi-source library - name: Set up Gradle
uses: gradle/gradle-build-action@v2 uses: gradle/actions/setup-gradle@06832c7b30a0129d7fb559bcc6e43d26f6374244 # v4.3.1
env:
CI_MODULE_GEN: "true"
with: with:
arguments: :multisrc:generateExtensions
cache-read-only: true cache-read-only: true
- name: Build extensions (chunk ${{ matrix.chunk }}) - name: Build extensions (${{ matrix.chunk.number }})
uses: gradle/gradle-build-action@v2 run: |
env: ./gradlew $(echo '${{ toJson(matrix.chunk.modules) }}' | jq -r 'join(" ")')
CI_MULTISRC: "true"
CI_CHUNK_NUM: ${{ matrix.chunk }}
with:
arguments: assembleDebug
cache-read-only: true
build_individual:
name: Build individual modules
needs: prepare
if: ${{ needs.prepare.outputs.isIndividualChanged == '1' }}
runs-on: ubuntu-latest
strategy:
matrix: ${{ fromJSON(needs.prepare.outputs.individualMatrix) }}
steps:
- name: Checkout PR
uses: actions/checkout@v4
- name: Set up JDK
uses: actions/setup-java@v4
with:
java-version: 11
distribution: adopt
- name: Build extensions (chunk ${{ matrix.chunk }})
uses: gradle/gradle-build-action@v2
env:
CI_MULTISRC: "false"
CI_CHUNK_NUM: ${{ matrix.chunk }}
with:
arguments: assembleDebug
cache-read-only: true

View File

@@ -3,10 +3,16 @@ name: CI
on: on:
push: push:
branches: branches:
# - main
- master - master
paths-ignore: paths:
- '**.md' - '**'
- '.github/workflows/issue_moderator.yml' - '!**.md'
- '!.github/**'
- '.github/scripts/**'
- '.github/workflows/build_push.yml'
# Manual trigger
workflow_dispatch:
concurrency: concurrency:
group: ${{ github.workflow }} group: ${{ github.workflow }}
@@ -14,132 +20,149 @@ concurrency:
env: env:
CI_CHUNK_SIZE: 65 CI_CHUNK_SIZE: 65
IS_PR_CHECK: false
jobs: jobs:
prepare: prepare:
name: Prepare job name: Prepare job
runs-on: ubuntu-latest runs-on: 'ubuntu-24.04'
outputs: outputs:
individualMatrix: ${{ steps.generate-matrices.outputs.individualMatrix }} latestCommitMessage: ${{ steps.set-env.outputs.LATEST_COMMIT_MESSAGE }}
env: matrix: ${{ steps.generate-matrices.outputs.matrix }}
CI_MODULE_GEN: true delete: ${{ steps.generate-matrices.outputs.delete }}
steps: steps:
- name: Clone repo - name: Checkout ${{ github.ref_name }} branch
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Validate Gradle Wrapper
uses: gradle/wrapper-validation-action@v1
- name: Set up JDK
uses: actions/setup-java@v4
with: with:
java-version: 11 fetch-depth: 0
distribution: adopt
- name: Set env
- name: Get number of modules id: set-env
run: | run: |
set -x echo "LATEST_COMMIT_MESSAGE<<{delimiter}
./gradlew -q projects | grep '.*extensions\:\(individual\)\:.*\:.*' > projects.txt $(git log -1 --pretty=%B)
{delimiter}" >> $GITHUB_OUTPUT
echo "NUM_INDIVIDUAL_MODULES=$(cat projects.txt | grep '.*\:individual\:.*' | wc -l)" >> $GITHUB_ENV - name: Set up Java
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
with:
java-version: 17
distribution: temurin
- name: Set up Gradle
uses: gradle/actions/setup-gradle@06832c7b30a0129d7fb559bcc6e43d26f6374244 # v4.3.1
with:
cache-read-only: true
- name: Get last successful CI commit
id: last_successful_ci_commit
uses: nrwl/nx-set-shas@dbe0650947e5f2c81f59190a38512cf49126fe6b # v4.3.0
with:
main-branch-name: ${{ github.ref_name }}
- id: generate-matrices - id: generate-matrices
name: Create output matrices name: Create output matrices
uses: actions/github-script@v7 run: |
with: python ./.github/scripts/generate-build-matrices.py ${{ steps.last_successful_ci_commit.outputs.base }} Release
script: |
const numIndividualModules = process.env.NUM_INDIVIDUAL_MODULES;
const chunkSize = process.env.CI_CHUNK_SIZE;
const numIndividualChunks = Math.ceil(numIndividualModules / chunkSize); build:
name: Build extensions (${{ matrix.chunk.number }})
console.log(`Individual modules: ${numIndividualModules} (${numIndividualChunks} chunks of ${chunkSize})`);
core.setOutput('individualMatrix', { 'chunk': [...Array(numIndividualChunks).keys()] });
build_individual:
name: Build individual modules
needs: prepare needs: prepare
runs-on: ubuntu-latest runs-on: 'ubuntu-24.04'
if: ${{ toJson(fromJson(needs.prepare.outputs.matrix).chunk) != '[]' }}
strategy: strategy:
matrix: ${{ fromJSON(needs.prepare.outputs.individualMatrix) }} matrix: ${{ fromJSON(needs.prepare.outputs.matrix) }}
steps: steps:
- name: Checkout master branch - name: Checkout ${{ github.ref_name }} branch
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- name: Set up JDK - name: Set up Java
uses: actions/setup-java@v4 uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
with: with:
java-version: 11 java-version: 17
distribution: adopt distribution: temurin
- name: Set up Gradle
uses: gradle/actions/setup-gradle@06832c7b30a0129d7fb559bcc6e43d26f6374244 # v4.3.1
with:
cache-read-only: ${{ matrix.chunk.number > 1 }}
- name: Prepare signing key - name: Prepare signing key
run: | run: |
echo ${{ secrets.SIGNING_KEY }} | base64 -d > signingkey.jks echo ${{ secrets.SIGNING_KEY }} | base64 -d > signingkey.jks
- name: Build extensions (chunk ${{ matrix.chunk }}) - name: Build extensions (${{ matrix.chunk.number }})
uses: gradle/gradle-build-action@v2
env: env:
CI_MULTISRC: "false"
CI_CHUNK_NUM: ${{ matrix.chunk }}
ALIAS: ${{ secrets.ALIAS }} ALIAS: ${{ secrets.ALIAS }}
KEY_STORE_PASSWORD: ${{ secrets.KEY_STORE_PASSWORD }} KEY_STORE_PASSWORD: ${{ secrets.KEY_STORE_PASSWORD }}
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }} KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
with: run: |
arguments: assembleRelease ./gradlew $(echo '${{ toJson(matrix.chunk.modules) }}' | jq -r 'join(" ")')
- name: Upload APKs (chunk ${{ matrix.chunk }}) - name: Upload APKs (${{ matrix.chunk.number }})
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: "github.repository == 'Kareadita/tach-extension'" if: github.repository == 'Kareadita/tach-extension'
with: with:
name: "individual-apks-${{ matrix.chunk }}" name: "individual-apks-${{ matrix.chunk.number }}"
path: "**/*.apk" path: "**/*.apk"
retention-days: 1 retention-days: 1
- name: Clean up CI files - name: Clean up CI files
run: rm signingkey.jks run: rm signingkey.jks
publish_repo: publish:
name: Publish repo name: Publish extension repo
needs: needs: [prepare, build]
- build_individual if: github.repository == 'Kareadita/tach-extension'
if: "github.repository == 'Kareadita/tach-extension'" runs-on: 'ubuntu-24.04'
runs-on: ubuntu-latest
steps: steps:
- name: Download APK artifacts - name: Download APK artifacts
uses: actions/download-artifact@v4 uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with: with:
path: ~/apk-artifacts path: ~/apk-artifacts
- name: Set up JDK - name: Set up JDK
uses: actions/setup-java@v4 uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
with: with:
java-version: 17 java-version: 17
distribution: adopt distribution: temurin
- name: Checkout master branch - name: Checkout ${{ github.ref_name }} branch
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with: with:
ref: master ref: ${{ github.ref_name }}
path: master path: ${{ github.ref_name }}
- name: Create repo artifacts - name: Create repo artifacts
run: | run: |
cd master cd ${{ github.ref_name }}
./.github/scripts/move-apks.sh python ./.github/scripts/move-built-apks.py
INSPECTOR_LINK="$(curl -s "https://api.github.com/repos/tachiyomiorg/tachiyomi-extensions-inspector/releases/latest" | jq -r '.assets[0].browser_download_url')" INSPECTOR_LINK="$(curl -s "https://api.github.com/repos/keiyoushi/extensions-inspector/releases/latest" | jq -r '.assets[0].browser_download_url')"
curl -L "$INSPECTOR_LINK" -o ./Inspector.jar curl -L "$INSPECTOR_LINK" -o ./Inspector.jar
java -jar ./Inspector.jar "apk" "output.json" "tmp" java -jar ./Inspector.jar "repo/apk" "output.json" "tmp"
./.github/scripts/create-repo.sh python ./.github/scripts/create-repo.py
- name: Checkout repo branch - name: Checkout repo branch
uses: actions/checkout@v4 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with: with:
repository: yuzono/manga-repo
token: ${{ secrets.BOT_PAT }}
ref: repo ref: repo
path: repo path: repo
- name: Deploy repo - name: Merge repo
run: | run: |
cd repo cd repo
../master/.github/scripts/commit-repo.sh python ../${{ github.ref_name }}/.github/scripts/merge-repo.py '${{ needs.prepare.outputs.delete }}' '${{ github.ref_name }}/repo'
- name: Deploy repo
uses: EndBug/add-and-commit@a94899bca583c204427a224a7af87c02f9b325d5 # v9
with:
message: "${{ needs.prepare.outputs.latestCommitMessage }}"
cwd: "./repo"
committer_name: github-actions[bot]
committer_email: github-actions[bot]@users.noreply.github.com
- name: Purge cached index on jsDelivr
run: |
curl https://purge.jsdelivr.net/gh/Kareadita/tach-extension@repo/index.min.json

View File

@@ -2,20 +2,32 @@ name: Issue moderator
on: on:
issues: issues:
types: [opened, edited, reopened] types: [ opened, edited, reopened ]
issue_comment: issue_comment:
types: [created] types: [ created ]
jobs: jobs:
autoclose: autoclose:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Moderate issues - name: Moderate issues
uses: tachiyomiorg/issue-moderator-action@v2 uses: keiyoushi/issue-moderator-action@a017be83547db6e107431ce7575f53c1dfa3296a
with: with:
repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token: ${{ secrets.GITHUB_TOKEN }}
duplicate-label: Duplicate duplicate-label: Duplicate
blurbs: |
[
{
"keywords": ["cf", "cloudflare"],
"message": "Refer to the **Solving Cloudflare issues** section at https://yuzono.github.io/docs/guides/troubleshooting#cloudflare. If it doesn't work, migrate to other sources or wait until they lower their protection."
},
{
"keywords": ["uninstall"],
"message": "Uninstall the extension before updating. If that does not work, uninstall it from your device's settings by navigating to your device's Settings -> Apps and uninstall it from there by looking for `Tachiyomi: <extension name>`.\n\nThis is usually caused your previous extension having a different signature from the updated extension, making Android refuse to update it."
}
]
duplicate-check-enabled: true duplicate-check-enabled: true
duplicate-check-labels: | duplicate-check-labels: |
["Source request", "Domain changed"] ["Source request", "Domain changed"]
@@ -23,51 +35,37 @@ jobs:
existing-check-enabled: true existing-check-enabled: true
existing-check-labels: | existing-check-labels: |
["Source request", "Domain changed"] ["Source request", "Domain changed"]
existing-check-repo-url: https://raw.githubusercontent.com/yuzono/manga-repo/repo/index.min.json
auto-close-rules: | auto-close-rules: |
[ [
{
"type": "body",
"regex": ".*DELETE THIS SECTION IF YOU HAVE READ AND ACKNOWLEDGED IT.*",
"message": "The acknowledgment section was not removed."
},
{
"type": "body",
"regex": ".*\\* (Tachiyomi version|Android version|Device): \\?.*",
"message": "Requested information in the template was not filled out."
},
{
"type": "title",
"regex": ".*(Source name|Short description).*",
"message": "You did not fill out the description in the title."
},
{ {
"type": "both", "type": "both",
"regex": ".*(hq\\s*dragon|manga\\s*host|supermangas|superhentais|union\\s*mangas|yes\\s*mangas|manhuascan|manhwahot|leitor\\.?net|manga\\s*livre|tsuki\\s*mangas|manga\\s*yabu|mangas\\.in|mangas\\.pw|hentaikai|toptoon\\+?|colamanhua|mangadig|hitomi\\.la|copymanga|neox|1manga\\.co|mangafox\\.fun|mangahere\\.onl|mangakakalot\\.fun|manganel(?!o)|mangaonline\\.fun|mangatoday|manga\\.town|onemanga\\.info|koushoku|ksk\\.moe|comikey|leercapitulo|c[uứ]u\\s*truy[eệ]n|day\\s*comics?|reaper\\s*scans|constellar\\s*scans|mode\\s*scanlator|bakai|japscan|izakaya|blackout\\s*comics|anchira).*", "regex": ".*(?:fail(?:ed|ure|s)?|can\\s*(?:no|')?t|(?:not|un).*able|(?<!n[o']?t )blocked by|error) (?:to )?(?:get past|by ?pass|penetrate)?.*cl[oa]ud ?fl?[ai]re.*",
"ignoreCase": true,
"labels": ["invalid"],
"message": "{match} will not be added back as it is too difficult to maintain. Read [this](https://github.com/tachiyomiorg/tachiyomi-extensions/blob/master/REMOVED_SOURCES.md) for more information."
},
{
"type": "both",
"regex": ".*(komiktap|gourmet\\s*scans|mangawow|hikari\\s*scans|knightnoscanlations|mangasy|nartag|xxx\\s*yaoi|luminous|hunters\\s*scan|reset(?:\\s*|-)scan|astra\\s*scans|manga(?:-|\\s*)pro|shinobiscans|plot ?twist ?no ?fansub(?: ?scans?)?|plot-twistnf-scans(?:\\.com)?|mhscans|aresmanga|realm ?scans?|mono ?manga|dat(?:\\s*|-)?gar\\s*scan|remangas|moon ?daisy(?: scans?)?).*",
"ignoreCase": true,
"labels": ["invalid"],
"message": "{match} will not be added back as the scanlator team has requested it to be removed. Read [this](https://github.com/tachiyomiorg/tachiyomi-extensions/blob/master/REMOVED_SOURCES.md) for more information."
},
{
"type": "both",
"regex": ".*(?:fail(?:ed|ure|s)?|can\\s*(?:no|')?t|(?:not|un).*able|(?<!n[o']?t )blocked by|error) (?:to )?(?:get past|by ?pass|penetrate)?.*cloud ?fl?are.*",
"ignoreCase": true, "ignoreCase": true,
"labels": ["Cloudflare protected"], "labels": ["Cloudflare protected"],
"message": "Refer to the **Solving Cloudflare issues** section at https://tachiyomi.org/docs/guides/troubleshooting/#cloudflare. If it doesn't work, migrate to other sources or wait until they lower their protection." "message": "Refer to the **Solving Cloudflare issues** section at https://yuzono.github.io/docs/guides/troubleshooting#cloudflare. If it doesn't work, migrate to other sources or wait until they lower their protection."
}, },
{ {
"type": "both", "type": "both",
"regex": ".*(slime\\s*read).*", "regex": "remanga\\.org",
"ignoreCase": true, "ignoreCase": true,
"labels": ["invalid"], "labels": ["invalid"],
"message": "{match} will not be added as they have relations to the Mangá Livre team. Read [this](https://github.com/tachiyomiorg/tachiyomi-extensions/blob/master/REMOVED_SOURCES.md) for more information." "message": "ReManga (Russian) will not be added back as it has been removed [due to legal reasons](https://github.com/github/dmca)."
},
{
"type": "both",
"regex": "(kumanga\\.com)",
"ignoreCase": true,
"labels": ["invalid"],
"message": "{match} will not be added back as it is too difficult to maintain."
},
{
"type": "both",
"regex": "(centralnovel\\.com)",
"ignoreCase": true,
"labels": ["invalid"],
"message": "Novels aren't supported"
} }
] ]
auto-close-ignore-label: do-not-autoclose auto-close-ignore-label: do-not-autoclose

View File

@@ -8,11 +8,12 @@ on:
workflow_dispatch: workflow_dispatch:
inputs: inputs:
jobs: jobs:
lock: lock:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: dessant/lock-threads@v5 - uses: dessant/lock-threads@1bf7ec25051fe7c00bdd17e6a7cf3d7bfb7dc771 # v5.0.1
with: with:
github-token: ${{ github.token }} github-token: ${{ github.token }}
issue-inactive-days: '2' issue-inactive-days: '2'

1
.gitignore vendored
View File

@@ -10,3 +10,4 @@ repo/
apk/ apk/
gen gen
generated-src/ generated-src/
.kotlin

View File

@@ -1,156 +1,183 @@
# Contributing # Contributing
This guide have some instructions and tips on how to create a new Tachiyomi extension. Please **read it carefully** if you're a new contributor or don't have any experience on the required languages and knowledges. This guide have some instructions and tips on how to create a new Tachiyomi extension. Please **read
it carefully** if you're a new contributor or don't have any experience on the required languages
and knowledges.
This guide is not definitive and it's being updated over time. If you find any issue on it, feel free to report it through a [Meta Issue](https://github.com/tachiyomiorg/tachiyomi-extensions/issues/new?assignees=&labels=Meta+request&template=request_meta.yml) or fixing it directly by submitting a Pull Request. This guide is not definitive and it's being updated over time. If you find any issue on it, feel
free to report it through a [Meta Issue](https://github.com/yuzono/tachiyomi-extensions/issues/new?assignees=&labels=Meta+request&template=06_request_meta.yml)
or fixing it directly by submitting a Pull Request.
## Table of Contents ## Table of Contents
1. [Prerequisites](#prerequisites) - [Contributing](#contributing)
1. [Tools](#tools) - [Table of Contents](#table-of-contents)
2. [Cloning the repository](#cloning-the-repository) - [Prerequisites](#prerequisites)
2. [Getting help](#getting-help) - [Tools](#tools)
3. [Writing an extension](#writing-an-extension) - [Cloning the repository](#cloning-the-repository)
1. [Setting up a new Gradle module](#setting-up-a-new-gradle-module) - [Getting help](#getting-help)
2. [Core dependencies](#core-dependencies) - [Writing an extension](#writing-an-extension)
3. [Extension main class](#extension-main-class) - [Setting up a new Gradle module](#setting-up-a-new-gradle-module)
4. [Extension call flow](#extension-call-flow) - [Loading a subset of Gradle modules](#loading-a-subset-of-gradle-modules)
5. [Misc notes](#misc-notes) - [Extension file structure](#extension-file-structure)
6. [Advanced extension features](#advanced-extension-features) - [AndroidManifest.xml (optional)](#androidmanifestxml-optional)
4. [Multi-source themes](#multi-source-themes) - [build.gradle](#buildgradle)
1. [The directory structure](#the-directory-structure) - [Core dependencies](#core-dependencies)
2. [Development workflow](#development-workflow) - [Extension API](#extension-api)
3. [Scaffolding overrides](#scaffolding-overrides) - [DataImage library](#dataimage-library)
4. [Additional Notes](#additional-notes) - [i18n library](#i18n-library)
5. [Running](#running) - [Additional dependencies](#additional-dependencies)
6. [Debugging](#debugging) - [Extension main class](#extension-main-class)
1. [Android Debugger](#android-debugger) - [Main class key variables](#main-class-key-variables)
2. [Logs](#logs) - [Extension call flow](#extension-call-flow)
3. [Inspecting network calls](#inspecting-network-calls) - [Popular Manga](#popular-manga)
4. [Using external network inspecting tools](#using-external-network-inspecting-tools) - [Latest Manga](#latest-manga)
7. [Building](#building) - [Manga Search](#manga-search)
8. [Submitting the changes](#submitting-the-changes) - [Filters](#filters)
1. [Pull Request checklist](#pull-request-checklist) - [Manga Details](#manga-details)
- [Chapter](#chapter)
- [Chapter Pages](#chapter-pages)
- [Misc notes](#misc-notes)
- [Advanced Extension features](#advanced-extension-features)
- [URL intent filter](#url-intent-filter)
- [Update strategy](#update-strategy)
- [Renaming existing sources](#renaming-existing-sources)
- [Multi-source themes](#multi-source-themes)
- [The directory structure](#the-directory-structure)
- [Development workflow](#development-workflow)
- [Scaffolding overrides](#scaffolding-overrides)
- [Additional Notes](#additional-notes)
- [Running](#running)
- [Debugging](#debugging)
- [Android Debugger](#android-debugger)
- [Logs](#logs)
- [Inspecting network calls](#inspecting-network-calls)
- [Using external network inspecting tools](#using-external-network-inspecting-tools)
- [Setup your proxy server](#setup-your-proxy-server)
- [OkHttp proxy setup](#okhttp-proxy-setup)
- [Building](#building)
- [Submitting the changes](#submitting-the-changes)
- [Pull Request checklist](#pull-request-checklist)
## Prerequisites ## Prerequisites
Before you start, please note that the ability to use following technologies is **required** and that existing contributors will not actively teach them to you. Before you start, please note that the ability to use following technologies is **required** and
that existing contributors will not actively teach them to you.
- Basic [Android development](https://developer.android.com/) - Basic [Android development](https://developer.android.com/)
- [Kotlin](https://kotlinlang.org/) - [Kotlin](https://kotlinlang.org/)
- Web scraping - Web scraping
- [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) - [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML)
- [CSS selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors) - [CSS selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors)
- [OkHttp](https://square.github.io/okhttp/) - [OkHttp](https://square.github.io/okhttp/)
- [JSoup](https://jsoup.org/) - [JSoup](https://jsoup.org/)
### Tools ### Tools
- [Android Studio](https://developer.android.com/studio) - [Android Studio](https://developer.android.com/studio)
- Emulator or phone with developer options enabled and a recent version of Tachiyomi installed - Emulator or phone with developer options enabled and a recent version of Komikku installed
- [Icon Generator](https://as280093.github.io/AndroidAssetStudio/icons-launcher.html) - [Icon Generator](https://as280093.github.io/AndroidAssetStudio/icons-launcher.html)
### Cloning the repository ### Cloning the repository
Some alternative steps can be followed to ignore "repo" branch and skip unrelated sources, which will make it faster to pull, navigate and build. This will also reduce disk usage and network traffic. Some alternative steps can be followed to ignore "repo" branch and skip unrelated sources, which will make it faster to pull, navigate and build. This will also reduce disk usage and network traffic.
**These steps are only needed when the repo is huge and contains a lot of sources. If the repo is small, just do a normal full clone instead.**
<details><summary>Steps</summary> <details><summary>Steps</summary>
1. Make sure to delete "repo" branch in your fork. You may also want to disable Actions in the repo settings. 1. Make sure to delete "repo" branch in your fork. You may also want to disable Actions in the repo settings.
**Also make sure you are using the latest version of Git as many commands used here are pretty new.** **Also make sure you are using the latest version of Git as many commands used here are pretty new.**
2. Do a partial clone. 2. Do a partial clone.
```bash ```bash
git clone --filter=blob:none --sparse <fork-repo-url> git clone --filter=blob:none --sparse <fork-repo-url>
cd tachiyomi-extensions/ cd tachiyomi-extensions/
``` ```
3. Configure sparse checkout. 3. Configure sparse checkout.
There are two modes of pattern matching. The default is cone (🔺) mode. There are two modes of pattern matching. The default is cone (🔺) mode.
Cone mode enables significantly faster pattern matching for big monorepos Cone mode enables significantly faster pattern matching for big monorepos
and the sparse index feature to make Git commands more responsive. and the sparse index feature to make Git commands more responsive.
In this mode, you can only filter by file path, which is less flexible In this mode, you can only filter by file path, which is less flexible
and might require more work when the project structure changes. and might require more work when the project structure changes.
You can skip this code block to use legacy mode if you want easier filters. You can skip this code block to use legacy mode if you want easier filters.
It won't be much slower as the repo doesn't have that many files. It won't be much slower as the repo doesn't have that many files.
To enable cone mode together with sparse index, follow these steps: To enable cone mode together with sparse index, follow these steps:
```bash ```bash
git sparse-checkout set --cone --sparse-index git sparse-checkout set --cone --sparse-index
# add project folders # add project folders
git sparse-checkout add .run buildSrc core gradle lib multisrc/src/main/java/generator git sparse-checkout add buildSrc core gradle lib lib-multisrc utils
# add a single source # add a single source
git sparse-checkout add src/<lang>/<source> git sparse-checkout add src/<lang>/<source>
# add a multisrc theme ```
git sparse-checkout add multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/<source>
git sparse-checkout add multisrc/overrides/<source>
```
To remove a source, open `.git/info/sparse-checkout` and delete the exact To remove a source, open `.git/info/sparse-checkout` and delete the exact
lines you typed when adding it. Don't touch the other auto-generated lines lines you typed when adding it. Don't touch the other auto-generated lines
unless you fully understand how cone mode works, or you might break it. unless you fully understand how cone mode works, or you might break it.
To use the legacy non-cone mode, follow these steps: To use the legacy non-cone mode, follow these steps:
```bash ```bash
# enable sparse checkout # enable sparse checkout
git sparse-checkout set --no-cone git sparse-checkout set --no-cone
# edit sparse checkout filter # edit sparse checkout filter
vim .git/info/sparse-checkout vim .git/info/sparse-checkout
# alternatively, if you have VS Code installed # alternatively, if you have VS Code installed
code .git/info/sparse-checkout code .git/info/sparse-checkout
``` ```
Here's an example:
```bash
/*
!/src/*
!/multisrc/overrides/*
!/multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/*
# allow a single source
/src/<lang>/<source>
# allow a multisrc theme
/multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/<source>
/multisrc/overrides/<source>
# or type the source name directly
<source>
```
Explanation: the rules are like `gitignore`. We first exclude all sources Here's an example:
while retaining project folders, then add the needed sources back manually.
```bash
/*
!/src/*
!/multisrc-lib/*
# allow a single source
/src/<lang>/<source>
# allow a multisrc theme
/lib-multisrc/<source>
# or type the source name directly
<source>
```
Explanation: the rules are like `gitignore`. We first exclude all sources
while retaining project folders, then add the needed sources back manually.
4. Configure remotes. 4. Configure remotes.
```bash ```bash
# add upstream # add upstream
git remote add upstream <tachiyomiorg-repo-url> git remote add upstream <yuzono-url>
# optionally disable push to upstream # optionally disable push to upstream
git remote set-url --push upstream no_pushing git remote set-url --push upstream no_pushing
# ignore 'repo' branch of upstream # ignore 'repo' branch of upstream
# option 1: use negative refspec # option 1: use negative refspec
git config --add remote.upstream.fetch "^refs/heads/repo" git config --add remote.upstream.fetch "^refs/heads/repo"
# option 2: fetch master only (ignore all other branches) # option 2: fetch master only (ignore all other branches)
git config remote.upstream.fetch "+refs/heads/master:refs/remotes/upstream/master" git config remote.upstream.fetch "+refs/heads/master:refs/remotes/upstream/master"
# update remotes # update remotes
git remote update git remote update
# track master of upstream instead of fork # track master of upstream instead of fork
git branch master -u upstream/master git branch master -u upstream/master
``` ```
5. Useful configurations. (optional) 5. Useful configurations. (optional)
```bash ```bash
# prune obsolete remote branches on fetch # prune obsolete remote branches on fetch
git config remote.origin.prune true git config remote.origin.prune true
# fast-forward only when pulling master branch # fast-forward only when pulling master branch
git config pull.ff only git config pull.ff only
# Add an alias to sync master branch without fetching useless blobs. # Add an alias to sync master branch without fetching useless blobs.
# If you run `git pull` to fast-forward in a blobless clone like this, # If you run `git pull` to fast-forward in a blobless clone like this,
# all blobs (files) in the new commits are still fetched regardless of # all blobs (files) in the new commits are still fetched regardless of
# sparse rules, which makes the local repo accumulate unused files. # sparse rules, which makes the local repo accumulate unused files.
# Use `git sync-master` to avoid this. Be careful if you have changes # Use `git sync-master` to avoid this. Be careful if you have changes
# on master branch, which is not a good practice. # on master branch, which is not a good practice.
git config alias.sync-master '!git switch master && git fetch upstream && git reset --keep FETCH_HEAD' git config alias.sync-master '!git switch master && git fetch upstream && git reset --keep FETCH_HEAD'
``` ```
6. Later, if you change the sparse checkout filter, run `git sparse-checkout reapply`. 6. Later, if you change the sparse checkout filter, run `git sparse-checkout reapply`.
Read more on Read more on
@@ -159,26 +186,31 @@ Read more on
[sparse checkout](https://github.blog/2020-01-17-bring-your-monorepo-down-to-size-with-sparse-checkout/), [sparse checkout](https://github.blog/2020-01-17-bring-your-monorepo-down-to-size-with-sparse-checkout/),
[sparse index](https://github.blog/2021-11-10-make-your-monorepo-feel-small-with-gits-sparse-index/), [sparse index](https://github.blog/2021-11-10-make-your-monorepo-feel-small-with-gits-sparse-index/),
and [negative refspecs](https://github.blog/2020-10-19-git-2-29-released/#user-content-negative-refspecs). and [negative refspecs](https://github.blog/2020-10-19-git-2-29-released/#user-content-negative-refspecs).
</details> </details>
## Getting help ## Getting help
- Join [the Discord server](https://discord.gg/tachiyomi) for online help and to ask questions while developing your extension. When doing so, please ask it in the `#programming` channel. - There are some features and tricks that are not explored in this document. Refer to existing
- There are some features and tricks that are not explored in this document. Refer to existing extension code for examples. extension code for examples.
## Writing an extension ## Writing an extension
The quickest way to get started is to copy an existing extension's folder structure and renaming it as needed. We also recommend reading through a few existing extensions' code before you start. The quickest way to get started is to copy an existing extension's folder structure and renaming it
as needed. We also recommend reading through a few existing extensions' code before you start.
### Setting up a new Gradle module ### Setting up a new Gradle module
Each extension should reside in `src/<lang>/<mysourcename>`. Use `all` as `<lang>` if your target source supports multiple languages or if it could support multiple sources. Each extension should reside in `src/<lang>/<mysourcename>`. Use `all` as `<lang>` if your target
source supports multiple languages or if it could support multiple sources.
The `<lang>` used in the folder inside `src` should be the major `language` part. For example, if you will be creating a `pt-BR` source, use `<lang>` here as `pt` only. Inside the source class, use the full locale string instead. The `<lang>` used in the folder inside `src` should be the major `language` part. For example, if
you will be creating a `pt-BR` source, use `<lang>` here as `pt` only. Inside the source class, use
the full locale string instead.
### Loading a subset of Gradle modules ### Loading a subset of Gradle modules
By default, all individual and generated multisrc extensions are loaded for local development. By default, all individual and generated multisrc extensions are loaded for local development.
This may be inconvenient if you only need to work on one extension at a time. This may be inconvenient if you only need to work on one extension at a time.
To adjust which modules are loaded, make adjustments to the `settings.gradle.kts` file as needed. To adjust which modules are loaded, make adjustments to the `settings.gradle.kts` file as needed.
@@ -190,7 +222,7 @@ The simplest extension structure looks like this:
```console ```console
$ tree src/<lang>/<mysourcename>/ $ tree src/<lang>/<mysourcename>/
src/<lang>/<mysourcename>/ src/<lang>/<mysourcename>/
├── AndroidManifest.xml ├── AndroidManifest.xml (optional)
├── build.gradle ├── build.gradle
├── res ├── res
│   ├── mipmap-hdpi │   ├── mipmap-hdpi
@@ -201,9 +233,8 @@ src/<lang>/<mysourcename>/
│   │   └── ic_launcher.png │   │   └── ic_launcher.png
│   ├── mipmap-xxhdpi │   ├── mipmap-xxhdpi
│   │   └── ic_launcher.png │   │   └── ic_launcher.png
│   ── mipmap-xxxhdpi │   ── mipmap-xxxhdpi
│      └── ic_launcher.png │      └── ic_launcher.png
│   └── web_hi_res_512.png
└── src └── src
└── eu └── eu
└── kanade └── kanade
@@ -216,19 +247,22 @@ src/<lang>/<mysourcename>/
13 directories, 9 files 13 directories, 9 files
``` ```
#### AndroidManifest.xml `<lang>` should be an ISO 639-1 compliant language code (two letters or `all`). `<mysourcename>` should be adapted from the site name, and can only contain lowercase ASCII letters and digits.
A minimal [Android manifest file](https://developer.android.com/guide/topics/manifest/manifest-intro) is needed for Android to recognize a extension when it's compiled into an APK file. You can also add intent filters inside this file (see [URL intent filter](#url-intent-filter) for more information).
Your extension code must be placed in the package `eu.kanade.tachiyomi.extension.<lang>.<mysourcename>`.
#### AndroidManifest.xml (optional)
You only need to create this file if you want to add deep linking to your extension.
See [URL intent filter](#url-intent-filter) for more information.
#### build.gradle #### build.gradle
Make sure that your new extension's `build.gradle` file follows the following structure: Make sure that your new extension's `build.gradle` file follows the following structure:
```gradle ```groovy
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
ext { ext {
extName = '<My source name>' extName = '<My source name>'
pkgNameSuffix = '<lang>.<mysourcename>'
extClass = '.<MySourceName>' extClass = '.<MySourceName>'
extVersionCode = 1 extVersionCode = 1
isNsfw = true isNsfw = true
@@ -237,28 +271,30 @@ ext {
apply from: "$rootDir/common.gradle" apply from: "$rootDir/common.gradle"
``` ```
| Field | Description | | Field | Description |
| ----- | ----------- | | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `extName` | The name of the extension. | | `extName` | The name of the extension. |
| `pkgNameSuffix` | A unique suffix added to `eu.kanade.tachiyomi.extension`. The language and the site name should be enough. Remember your extension code implementation must be placed in this package. | | `pkgNameSuffix` | A unique suffix added to `eu.kanade.tachiyomi.extension`. The language and the site name should be enough. Remember your extension code implementation must be placed in this package. |
| `extClass` | Points to the class that implements `Source`. You can use a relative path starting with a dot (the package name is the base path). This is used to find and instantiate the source(s). | | `extClass` | Points to the class that implements `Source`. You can use a relative path starting with a dot (the package name is the base path). This is used to find and instantiate the source(s). |
| `extVersionCode` | The extension version code. This must be a positive integer and incremented with any change to the code. | | `extVersionCode` | The extension version code. This must be a positive integer and incremented with any change to the code. |
| `libVersion` | (Optional, defaults to `1.4`) The version of the [extensions library](https://github.com/tachiyomiorg/extensions-lib) used. | | `isNsfw` | (Optional, defaults to `false`) Flag to indicate that a source contains NSFW content. |
| `isNsfw` | (Optional, defaults to `false`) Flag to indicate that a source contains NSFW content. |
The extension's version name is generated automatically by concatenating `libVersion` and `extVersionCode`. With the example used above, the version would be `1.4.1`. The extension's version name is generated automatically by concatenating `1.4` and `extVersionCode`.
With the example used above, the version would be `1.4.1`.
### Core dependencies ### Core dependencies
#### Extension API #### Extension API
Extensions rely on [extensions-lib](https://github.com/tachiyomiorg/extensions-lib), which provides some interfaces and stubs from the [app](https://github.com/tachiyomiorg/tachiyomi) for compilation purposes. The actual implementations can be found [here](https://github.com/tachiyomiorg/tachiyomi/tree/master/app/src/main/java/eu/kanade/tachiyomi/source). Referencing the actual implementation will help with understanding extensions' call flow. Extensions rely on [extensions-lib](https://github.com/komikku-app/extensions-lib), which provides some interfaces and stubs from the [app](https://github.com/komikku-app/komikku) for compilation purposes. The actual implementations can be found [here](https://github.com/komikku-app/komikku/tree/master/app/src/main/java/eu/kanade/tachiyomi/source). Referencing the actual implementation will help with understanding extensions' call flow.
#### DataImage library #### DataImage library
[`lib-dataimage`](https://github.com/tachiyomiorg/tachiyomi-extensions/tree/master/lib/dataimage) is a library for handling [base 64 encoded image data](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) using an [OkHttp interceptor](https://square.github.io/okhttp/interceptors/). [`lib-dataimage`](https://github.com/yuzono/tachiyomi-extensions/tree/master/lib/dataimage) is a library
or handling [base 64 encoded image data](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)
using an [OkHttp interceptor](https://square.github.io/okhttp/interceptors/).
```gradle ```groovy
dependencies { dependencies {
implementation(project(':lib-dataimage')) implementation(project(':lib-dataimage'))
} }
@@ -266,9 +302,9 @@ dependencies {
#### i18n library #### i18n library
[`lib-i18n`](https://github.com/tachiyomiorg/tachiyomi-extensions/tree/master/lib/i18n) is a library for handling internationalization in the sources. It allows loading `.properties` files with messages located under the `assets/i18n` folder of each extension, that can be used to translate strings under the source. [`lib-i18n`](https://github.com/yuzono/tachiyomi-extensions/tree/master/lib/i18n) is a library for handling internationalization in the sources. It allows loading `.properties` files with messages located under the `assets/i18n` folder of each extension, that can be used to translate strings under the source.
```gradle ```groovy
dependencies { dependencies {
implementation(project(':lib-i18n')) implementation(project(':lib-i18n'))
} }
@@ -276,34 +312,40 @@ dependencies {
#### Additional dependencies #### Additional dependencies
If you find yourself needing additional functionality, you can add more dependencies to your `build.gradle` file. If you find yourself needing additional functionality, you can add more dependencies to your `build.gradle`
Many of [the dependencies](https://github.com/tachiyomiorg/tachiyomi/blob/master/app/build.gradle.kts) from the main Tachiyomi app are exposed to extensions by default. file. Many of [the dependencies](https://github.com/komikku-app/komikku/blob/master/app/build.gradle.kts)
from the main Komikku app are exposed to extensions by default.
> Note that several dependencies are already exposed to all extensions via Gradle version catalog. > [!NOTE]
> To view which are available view `libs.versions.toml` under the `gradle` folder > Several dependencies are already exposed to all extensions via Gradle's version catalog.
> To view which are available check the `gradle/libs.versions.toml` file.
Notice that we're using `compileOnly` instead of `implementation` if the app already contains it. You could use `implementation` instead for a new dependency, or you prefer not to rely on whatever the main app has at the expense of app size. Notice that we're using `compileOnly` instead of `implementation` if the app already contains it.
You could use `implementation` instead for a new dependency, or you prefer not to rely on whatever
the main app has at the expense of app size.
Note that using `compileOnly` restricts you to versions that must be compatible with those used in [the latest stable version of Tachiyomi](https://github.com/tachiyomiorg/tachiyomi/releases/latest). > [!IMPORTANT]
> Using `compileOnly` restricts you to versions that must be compatible with those used in
> [the latest stable version of Komikku](https://github.com/komikku-app/komikku/releases/latest).
### Extension main class ### Extension main class
The class which is referenced and defined by `extClass` in `build.gradle`. This class should implement either `SourceFactory` or extend one of the `Source` implementations: `HttpSource` or `ParsedHttpSource`. The class which is referenced and defined by `extClass` in `build.gradle`. This class should implement either `SourceFactory` or extend one of the `Source` implementations: `HttpSource` or `ParsedHttpSource`.
| Class | Description | | Class | Description |
| ----- | ----------- | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|`SourceFactory`| Used to expose multiple `Source`s. Use this in case of a source that supports multiple languages or mirrors of the same website. For similar websites use [theme sources](#multi-source-themes). | | `SourceFactory` | Used to expose multiple `Source`s. Use this in case of a source that supports multiple languages or mirrors of the same website. For similar websites use [theme sources](#multi-source-themes). |
| `HttpSource`| For online source, where requests are made using HTTP. | | `HttpSource` | For online source, where requests are made using HTTP. |
| `ParsedHttpSource`| Similar to `HttpSource`, but has methods useful for scraping pages. | | `ParsedHttpSource` | Similar to `HttpSource`, but has methods useful for scraping pages. |
#### Main class key variables #### Main class key variables
| Field | Description | | Field | Description |
| ----- | ----------- | | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | Name displayed in the "Sources" tab in Tachiyomi. | | `name` | Name displayed in the "Sources" tab in Komikku. |
| `baseUrl` | Base URL of the source without any trailing slashes. | | `baseUrl` | Base URL of the source without any trailing slashes. |
| `lang` | An ISO 639-1 compliant language code (two letters in lower case in most cases, but can also include the country/dialect part by using a simple dash character). | | `lang` | An ISO 639-1 compliant language code (two letters in lower case in most cases, but can also include the country/dialect part by using a simple dash character). |
| `id` | Identifier of your source, automatically set in `HttpSource`. It should only be manually overriden if you need to copy an existing autogenerated ID. | | `id` | Identifier of your source, automatically set in `HttpSource`. It should only be manually overriden if you need to copy an existing autogenerated ID. |
### Extension call flow ### Extension call flow
@@ -311,38 +353,42 @@ The class which is referenced and defined by `extClass` in `build.gradle`. This
a.k.a. the Browse source entry point in the app (invoked by tapping on the source name). a.k.a. the Browse source entry point in the app (invoked by tapping on the source name).
- The app calls `fetchPopularManga` which should return a `MangasPage` containing the first batch of found `SManga` entries. - The app calls `fetchPopularManga` which should return a `MangasPage` containing the first batch of
- This method supports pagination. When user scrolls the manga list and more results must be fetched, the app calls it again with increasing `page` values (starting with `page=1`). This continues while `MangasPage.hasNextPage` is passed as `true` and `MangasPage.mangas` is not empty. found `SManga` entries. - This method supports pagination. When user scrolls the manga list and more results must be fetched,
- To show the list properly, the app needs `url`, `title` and `thumbnail_url`. You **must** set them here. The rest of the fields could be filled later (refer to Manga Details below). the app calls it again with increasing `page` values (starting with `page=1`). This continues while
- You should set `thumbnail_url` if is available, if not, `getMangaDetails` will be **immediately** called (this will increase network calls heavily and should be avoided). `MangasPage.hasNextPage` is passed as `true` and `MangasPage.mangas` is not empty.
- To show the list properly, the app needs `url`, `title` and `thumbnail_url`. You **must** set them
here. The rest of the fields could be filled later (refer to Manga Details below). - You should set `thumbnail_url` if is available, if not, `getMangaDetails` will be **immediately**
called (this will increase network calls heavily and should be avoided).
#### Latest Manga #### Latest Manga
a.k.a. the Latest source entry point in the app (invoked by tapping on the "Latest" button beside the source name). a.k.a. the Latest source entry point in the app (invoked by tapping on the "Latest" button beside
the source name).
- Enabled if `supportsLatest` is `true` for a source - Enabled if `supportsLatest` is `true` for a source
- Similar to popular manga, but should be fetching the latest entries from a source. - Similar to popular manga, but should be fetching the latest entries from a source.
#### Manga Search #### Manga Search
- When the user searches inside the app, `fetchSearchManga` will be called and the rest of the flow is similar to what happens with `fetchPopularManga`. - When the user searches inside the app, `fetchSearchManga` will be called and the rest of the flow
- If search functionality is not available, return `Observable.just(MangasPage(emptyList(), false))` is similar to what happens with `fetchPopularManga`. - If search functionality is not available, return `Observable.just(MangasPage(emptyList(), false))`
- `getFilterList` will be called to get all filters and filter types. - `getFilterList` will be called to get all filters and filter types.
##### Filters ##### Filters
The search flow have support to filters that can be added to a `FilterList` inside the `getFilterList` method. When the user changes the filters' state, they will be passed to the `searchRequest`, and they can be iterated to create the request (by getting the `filter.state` value, where the type varies depending on the `Filter` used). You can check the filter types available [here](https://github.com/tachiyomiorg/tachiyomi/blob/master/source-api/src/commonMain/kotlin/eu/kanade/tachiyomi/source/model/Filter.kt) and in the table below. The search flow have support to filters that can be added to a `FilterList` inside the `getFilterList` method. When the user changes the filters' state, they will be passed to the `searchRequest`, and they can be iterated to create the request (by getting the `filter.state` value, where the type varies depending on the `Filter` used). You can check the filter types available [here](https://github.com/komikku-app/komikku/blob/master/source-api/src/commonMain/kotlin/eu/kanade/tachiyomi/source/model/Filter.kt) and in the table below.
| Filter | State type | Description | | Filter | State type | Description |
| ------ | ---------- | ----------- | | ------------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Filter.Header` | None | A simple header. Useful for separating sections in the list or showing any note or warning to the user. | | `Filter.Header` | None | A simple header. Useful for separating sections in the list or showing any note or warning to the user. |
| `Filter.Separator` | None | A line separator. Useful for visual distinction between sections. | | `Filter.Separator` | None | A line separator. Useful for visual distinction between sections. |
| `Filter.Select<V>` | `Int` | A select control, similar to HTML's `<select>`. Only one item can be selected, and the state is the index of the selected one. | | `Filter.Select<V>` | `Int` | A select control, similar to HTML's `<select>`. Only one item can be selected, and the state is the index of the selected one. |
| `Filter.Text` | `String` | A text control, similar to HTML's `<input type="text">`. | | `Filter.Text` | `String` | A text control, similar to HTML's `<input type="text">`. |
| `Filter.CheckBox` | `Boolean` | A checkbox control, similar to HTML's `<input type="checkbox">`. The state is `true` if it's checked. | | `Filter.CheckBox` | `Boolean` | A checkbox control, similar to HTML's `<input type="checkbox">`. The state is `true` if it's checked. |
| `Filter.TriState` | `Int` | A enhanced checkbox control that supports an excluding state. The state can be compared with `STATE_IGNORE`, `STATE_INCLUDE` and `STATE_EXCLUDE` constants of the class. | | `Filter.TriState` | `Int` | A enhanced checkbox control that supports an excluding state. The state can be compared with `STATE_IGNORE`, `STATE_INCLUDE` and `STATE_EXCLUDE` constants of the class. |
| `Filter.Group<V>` | `List<V>` | A group of filters (preferentially of the same type). The state will be a `List` with all the states. | | `Filter.Group<V>` | `List<V>` | A group of filters (preferentially of the same type). The state will be a `List` with all the states. |
| `Filter.Sort` | `Selection` | A control for sorting, with support for the ordering. The state indicates which item index is selected and if the sorting is `ascending`. | | `Filter.Sort` | `Selection` | A control for sorting, with support for the ordering. The state indicates which item index is selected and if the sorting is `ascending`. |
All control filters can have a default state set. It's usually recommended if the source have filters to make the initial state match the popular manga list, so when the user open the filter sheet, the state is equal and represents the current manga showing. All control filters can have a default state set. It's usually recommended if the source have filters to make the initial state match the popular manga list, so when the user open the filter sheet, the state is equal and represents the current manga showing.
@@ -358,48 +404,58 @@ open class UriPartFilter(displayName: String, private val vals: Array<Pair<Strin
#### Manga Details #### Manga Details
- When user taps on a manga, `getMangaDetails` and `getChapterList` will be called and the results will be cached. - When user taps on a manga, `getMangaDetails` and `getChapterList` will be called and the results will be cached.
- A `SManga` entry is identified by it's `url`. - A `SManga` entry is identified by it's `url`.
- `getMangaDetails` is called to update a manga's details from when it was initialized earlier. - `getMangaDetails` is called to update a manga's details from when it was initialized earlier.
- `SManga.initialized` tells the app if it should call `getMangaDetails`. If you are overriding `getMangaDetails`, make sure to pass it as `true`. - `SManga.initialized` tells the app if it should call `getMangaDetails`. If you are overriding `getMangaDetails`, make sure to pass it as `true`.
- `SManga.genre` is a string containing list of all genres separated with `", "`. - `SManga.genre` is a string containing list of all genres separated with `", "`.
- `SManga.status` is an "enum" value. Refer to [the values in the `SManga` companion object](https://github.com/tachiyomiorg/extensions-lib/blob/master/library/src/main/java/eu/kanade/tachiyomi/source/model/SManga.kt#L24). - `SManga.status` is an "enum" value. Refer to [the values in the `SManga` companion object](https://github.com/komikku-app/extensions-lib/blob/master/library/src/main/java/eu/kanade/tachiyomi/source/model/SManga.kt#L24).
- During a backup, only `url` and `title` are stored. To restore the rest of the manga data, the app calls `getMangaDetails`, so all fields should be (re)filled in if possible. - During a backup, only `url` and `title` are stored. To restore the rest of the manga data, the app calls `getMangaDetails`, so all fields should be (re)filled in if possible.
- If a `SManga` is cached, `getMangaDetails` will be only called when the user does a manual update (Swipe-to-Refresh). - If a `SManga` is cached, `getMangaDetails` will be only called when the user does a manual update (Swipe-to-Refresh).
- `getChapterList` is called to display the chapter list. - `getChapterList` is called to display the chapter list.
- **The list should be sorted descending by the source order**. - **The list should be sorted descending by the source order**.
- `getMangaUrl` is called when the user taps "Open in WebView". - `getMangaUrl` is called when the user taps "Open in WebView".
- If the source uses an API to fetch the data, consider overriding this method to return the manga absolute URL in the website instead. - If the source uses an API to fetch the data, consider overriding this method to return the manga absolute URL in the website instead.
- It defaults to the URL provided to the request in `mangaDetailsRequest`. - It defaults to the URL provided to the request in `mangaDetailsRequest`.
#### Chapter #### Chapter
- After a chapter list for the manga is fetched and the app is going to cache the data, `prepareNewChapter` will be called. - After a chapter list for the manga is fetched and the app is going to cache the data,
- `SChapter.date_upload` is the [UNIX Epoch time](https://en.wikipedia.org/wiki/Unix_time) **expressed in milliseconds**. `prepareNewChapter` will be called.
- If you don't pass `SChapter.date_upload` and leave it zero, the app will use the default date instead, but it's recommended to always fill it if it's available. - `SChapter.date_upload` is the [UNIX Epoch time](https://en.wikipedia.org/wiki/Unix_time)
- To get the time in milliseconds from a date string, you can use a `SimpleDateFormat` like in the example below. **expressed in milliseconds**. - If you don't pass `SChapter.date_upload` and leave it zero, the app will use the default date
instead, but it's recommended to always fill it if it's available. - To get the time in milliseconds from a date string, you can use a `SimpleDateFormat` like in
the example below.
```kotlin ```kotlin
private fun parseDate(dateStr: String): Long { private fun parseDate(dateStr: String): Long {
return runCatching { DATE_FORMATTER.parse(dateStr)?.time } return try {
.getOrNull() ?: 0L dateFormat.parse(dateStr)!!.time
} } catch (_: ParseException) {
0L
}
}
companion object { private val dateFormat by lazy {
private val DATE_FORMATTER by lazy { SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH) }
} ```
}
``` Make sure you make the `SimpleDateFormat` a class constant or variable so it doesn't get
recreated for every chapter. If you need to parse or format dates in manga description, create
another instance since `SimpleDateFormat` is not thread-safe.
- If the parsing have any problem, make sure to return `0L` so the app will use the default date
instead.
- The app will overwrite dates of existing old chapters **UNLESS** `0L` is returned.
- The default date has [changed](https://github.com/tachiyomiorg/tachiyomi/pull/7197) in
preview ≥ r4442 or stable > 0.13.4.
- In older versions, the default date is always the fetch date.
- In newer versions, this is the same if every (new) chapter has `0L` returned.
- However, if the source only provides the upload date of the latest chapter, you can now set
it to the latest chapter and leave other chapters default. The app will automatically set it (instead of fetch date) to every new chapter and leave old chapters' dates untouched.
Make sure you make the `SimpleDateFormat` a class constant or variable so it doesn't get recreated for every chapter. If you need to parse or format dates in manga description, create another instance since `SimpleDateFormat` is not thread-safe.
- If the parsing have any problem, make sure to return `0L` so the app will use the default date instead.
- The app will overwrite dates of existing old chapters **UNLESS** `0L` is returned.
- The default date has [changed](https://github.com/tachiyomiorg/tachiyomi/pull/7197) in preview ≥ r4442 or stable > 0.13.4.
- In older versions, the default date is always the fetch date.
- In newer versions, this is the same if every (new) chapter has `0L` returned.
- However, if the source only provides the upload date of the latest chapter, you can now set it to the latest chapter and leave other chapters default. The app will automatically set it (instead of fetch date) to every new chapter and leave old chapters' dates untouched.
- `getChapterUrl` is called when the user taps "Open in WebView" in the reader. - `getChapterUrl` is called when the user taps "Open in WebView" in the reader.
- If the source uses an API to fetch the data, consider overriding this method to return the chapter absolute URL in the website instead. - If the source uses an API to fetch the data, consider overriding this method to return the
chapter absolute URL in the website instead.
- It defaults to the URL provided to the request in `pageListRequest`. - It defaults to the URL provided to the request in `pageListRequest`.
#### Chapter Pages #### Chapter Pages
@@ -413,30 +469,48 @@ open class UriPartFilter(displayName: String, private val vals: Array<Pair<Strin
### Misc notes ### Misc notes
- Sometimes you may find no use for some inherited methods. If so just override them and throw exceptions: `throw UnsupportedOperationException("Not used.")` - Sometimes you may find no use for some inherited methods. If so just override them and throw
- You probably will find `getUrlWithoutDomain` useful when parsing the target source URLs. Keep in mind there's a current issue with spaces in the URL though, so if you use it, replace all spaces with URL encoded characters (like `%20`). exceptions: `throw UnsupportedOperationException()`
- If possible try to stick to the general workflow from `HttpSource`/`ParsedHttpSource`; breaking them may cause you more headache than necessary. - You probably will find `getUrlWithoutDomain` useful when parsing the target source URLs. Keep in
- By implementing `ConfigurableSource` you can add settings to your source, which is backed by [`SharedPreferences`](https://developer.android.com/reference/android/content/SharedPreferences). mind there's a current issue with spaces in the URL though, so if you use it, replace all spaces with
URL encoded characters (like `%20`).
- If possible try to stick to the general workflow from `HttpSource`/`ParsedHttpSource`; breaking
them may cause you more headache than necessary.
- By implementing `ConfigurableSource` you can add settings to your source, which is backed by
[`SharedPreferences`](https://developer.android.com/reference/android/content/SharedPreferences).
### Advanced Extension features ### Advanced Extension features
#### URL intent filter #### URL intent filter
Extensions can define URL intent filters by defining it inside a custom `AndroidManifest.xml` file. Extensions can define URL intent filters by defining it inside a custom `AndroidManifest.xml` file.
For an example, refer to [the NHentai module's `AndroidManifest.xml` file](https://github.com/tachiyomiorg/tachiyomi-extensions/blob/master/src/all/nhentai/AndroidManifest.xml) and [its corresponding `NHUrlActivity` handler](https://github.com/tachiyomiorg/tachiyomi-extensions/blob/master/src/all/nhentai/src/eu/kanade/tachiyomi/extension/all/nhentai/NHUrlActivity.kt). For an example, refer to [the NHentai module's `AndroidManifest.xml` file](https://github.com/yuzono/tachiyomi-extensions/blob/master/src/all/nhentai/AndroidManifest.xml) and [its corresponding `NHUrlActivity` handler](https://github.com/yuzono/tachiyomi-extensions/blob/master/src/all/nhentai/src/eu/kanade/tachiyomi/extension/all/nhentai/NHUrlActivity.kt).
To test if the URL intent filter is working as expected, you can try opening the website in a browser and navigating to the endpoint that was added as a filter or clicking a hyperlink. Alternatively, you can use the `adb` command below. To test if the URL intent filter is working as expected, you can try opening the website in a browser
and navigating to the endpoint that was added as a filter or clicking a hyperlink. Alternatively,
you can use the `adb` command below.
```console ```console
$ adb shell am start -d "<your-link>" -a android.intent.action.VIEW $ adb shell am start -d "<your-link>" -a android.intent.action.VIEW
``` ```
> [!CAUTION]
> The activity does not support any Kotlin Intrinsics specific methods or calls,
> and using them will causes crashes in the activity. Consider using Java's equivalent
> methods instead, such as using `String`'s `equals()` instead of using `==`.
>
> You can use Kotlin Intrinsics in the extension source class, this limitation only
> applies to the activity classes.
#### Update strategy #### Update strategy
There is some cases where titles in a source will always only have the same chapter list (i.e. immutable), and don't need to be included in a global update of the app because of that, saving a lot of requests and preventing causing unnecessary damage to the source servers. To change the update strategy of a `SManga`, use the `update_strategy` field. You can find below a description of the current possible values. There is some cases where titles in a source will always only have the same chapter list (i.e. immutable), and don't need to be included in a global update of the app because of that, saving a lot of requests and preventing causing unnecessary damage to the source servers. To change the update strategy of a `SManga`, use the `update_strategy` field. You can find below a description of the current possible values.
- `UpdateStrategy.ALWAYS_UPDATE`: Titles marked as always update will be included in the library update if they aren't excluded by additional restrictions. - `UpdateStrategy.ALWAYS_UPDATE`: Titles marked as always update will be included in the library
- `UpdateStrategy.ONLY_FETCH_ONCE`: Titles marked as only fetch once will be automatically skipped during library updates. Useful for cases where the series is previously known to be finished and have only a single chapter, for example. update if they aren't excluded by additional restrictions.
- `UpdateStrategy.ONLY_FETCH_ONCE`: Titles marked as only fetch once will be automatically skipped
during library updates. Useful for cases where the series is previously known to be finished and have
only a single chapter, for example.
If not set, it defaults to `ALWAYS_UPDATE`. If not set, it defaults to `ALWAYS_UPDATE`.
@@ -444,7 +518,7 @@ If not set, it defaults to `ALWAYS_UPDATE`.
There is some cases where existing sources changes their name on the website. To correctly reflect these changes in the extension, you need to explicity set the `id` to the same old value, otherwise it will get changed by the new `name` value and users will be forced to migrate back to the source. There is some cases where existing sources changes their name on the website. To correctly reflect these changes in the extension, you need to explicity set the `id` to the same old value, otherwise it will get changed by the new `name` value and users will be forced to migrate back to the source.
To get the current `id` value before the name change, you can search the source name in the [repository JSON file](https://github.com/tachiyomiorg/tachiyomi-extensions/blob/repo/index.json) by looking into the `sources` attribute of the extension. When you have the `id` copied, you can override it in the source: To get the current `id` value before the name change, you can search the source name in the [repository JSON file](https://github.com/yuzono/tachiyomi-extensions/blob/repo/index.json) by looking into the `sources` attribute of the extension. When you have the `id` copied, you can override it in the source:
```kotlin ```kotlin
override val id: Long = <the-id> override val id: Long = <the-id>
@@ -452,16 +526,25 @@ override val id: Long = <the-id>
Then the class name and the `name` attribute value can be changed. Also don't forget to update the extension name and class name in the individual Gradle file if it is not a multisrc extension. Then the class name and the `name` attribute value can be changed. Also don't forget to update the extension name and class name in the individual Gradle file if it is not a multisrc extension.
**Important:** the package name **needs** to be the same (even if it has the old name), otherwise users will not receive the extension update when it gets published in the repository. If you're changing the name of a multisrc source, you can manually set it in the generator class of the theme by using `pkgName = "oldpackagename"`. > [!IMPORTANT]
> The package name **needs** to be the same (even if it has the old name), otherwise users will not
> receive the extension update when it gets published in the repository.
The `id` also needs to be explicity set to the old value if you're changing the `lang` attribute. The `id` also needs to be explicity set to the old value if you're changing the `lang` attribute.
> [!NOTE]
> If the source has also changed their theme you can instead just change
> the `name` field in the source class and in the Gradle file. By doing so
> a new `id` will be generated and users will be forced to migrate.
## Multi-source themes ## Multi-source themes
The `multisrc` module houses source code for generating extensions for cases where multiple source sites use the same site generator tool(usually a CMS) for bootsraping their website and this makes them similar enough to prompt code reuse through inheritance/composition; which from now on we will use the general **theme** term to refer to. The `multisrc` module houses source code for generating extensions for cases where multiple source sites use the same site generator tool(usually a CMS) for bootsraping their website and this makes them similar enough to prompt code reuse through inheritance/composition; which from now on we will use the general **theme** term to refer to.
This module contains the *default implementation* for each theme and definitions for each source that builds upon that default implementation and also it's overrides upon that default implementation, all of this becomes a set of source code which then is used to generate individual extensions from. This module contains the _default implementation_ for each theme and definitions for each source that builds upon that default implementation and also it's overrides upon that default implementation, all of this becomes a set of source code which then is used to generate individual extensions from.
### The directory structure ### The directory structure
```console ```console
$ tree multisrc $ tree multisrc
multisrc multisrc
@@ -479,9 +562,8 @@ multisrc
│   │   │   └── ic_launcher.png │   │   │   └── ic_launcher.png
│   │   ├── mipmap-xxhdpi │   │   ├── mipmap-xxhdpi
│   │   │   └── ic_launcher.png │   │   │   └── ic_launcher.png
│   │   ── mipmap-xxxhdpi │   │   ── mipmap-xxxhdpi
│   │      └── ic_launcher.png │   │      └── ic_launcher.png
│   │   └── web_hi_res_512.png
│   └── <sourcepkg> │   └── <sourcepkg>
│   ├── additional.gradle │   ├── additional.gradle
│   ├── AndroidManifest.xml │   ├── AndroidManifest.xml
@@ -494,9 +576,8 @@ multisrc
│   │   │   └── ic_launcher.png │   │   │   └── ic_launcher.png
│   │   ├── mipmap-xxhdpi │   │   ├── mipmap-xxhdpi
│   │   │   └── ic_launcher.png │   │   │   └── ic_launcher.png
│   │   ── mipmap-xxxhdpi │   │   ── mipmap-xxxhdpi
│   │      └── ic_launcher.png │   │      └── ic_launcher.png
│   │   └── web_hi_res_512.png
│   └── src │   └── src
│   └── <SourceName>.kt │   └── <SourceName>.kt
└── src └── src
@@ -526,29 +607,31 @@ multisrc
- `multisrc/overrides/<themepkg>/<sourcepkg>/additional.gradle` defines additional gradle code, this will be copied at the end of the generated gradle file below the theme's `additional.gradle`. - `multisrc/overrides/<themepkg>/<sourcepkg>/additional.gradle` defines additional gradle code, this will be copied at the end of the generated gradle file below the theme's `additional.gradle`.
- `multisrc/overrides/<themepkg>/<sourcepkg>/AndroidManifest.xml` is copied as an override to the default `AndroidManifest.xml` generation if it exists. - `multisrc/overrides/<themepkg>/<sourcepkg>/AndroidManifest.xml` is copied as an override to the default `AndroidManifest.xml` generation if it exists.
> **Note** > [!NOTE]
>
> Files ending with `Gen.kt` (i.e. `multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/<theme>/XxxGen.kt`) > Files ending with `Gen.kt` (i.e. `multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/<theme>/XxxGen.kt`)
> are considered helper files and won't be copied to generated sources. > are considered helper files and won't be copied to generated sources.
### Development workflow ### Development workflow
There are three steps in running and testing a theme source: There are three steps in running and testing a theme source:
1. Generate the sources 1. Generate the sources
- **Option 1: Only generate sources from one theme** - **Option 1: Only generate sources from one theme**
- **Method 1:** Find and run `<ThemeName>Generator` run configuration form the `Run/Debug Configuration` menu. - **Method 1:** Find and run `<ThemeName>Generator` run configuration form the `Run/Debug Configuration` menu.
- **Method 2:** Directly run `<themepkg>.<ThemeName>Generator.main` by pressing the play button in front of the method shown inside Android Studio's Code Editor to generate sources from the said theme. - **Method 2:** Directly run `<themepkg>.<ThemeName>Generator.main` by pressing the play button in front of the method shown inside Android Studio's Code Editor to generate sources from the said theme.
- **Option 2: Generate sources from all themes** - **Option 2: Generate sources from all themes**
- **Method 1:** Run `./gradlew multisrc:generateExtensions` from a terminal window to generate all sources. - **Method 1:** Run `./gradlew multisrc:generateExtensions` from a terminal window to generate all sources.
- **Method 2:** Directly run `Generator.GeneratorMain.main` by pressing the play button in front of the method shown inside Android Studio's Code Editor to generate all sources. - **Method 2:** Directly run `Generator.GeneratorMain.main` by pressing the play button in front of the method shown inside Android Studio's Code Editor to generate all sources.
2. Sync gradle to import the new generated sources inside `generated-src` 2. Sync gradle to import the new generated sources inside `generated-src`
- **Method 1:** Android Studio might prompt to sync the gradle. Click on `Sync Now`. - **Method 1:** Android Studio might prompt to sync the gradle. Click on `Sync Now`.
- **Method 2:** Manually re-sync by opening `File` -> `Sync Project with Gradle Files` or by pressing `Alt+f` then `g`. - **Method 2:** Manually re-sync by opening `File` -> `Sync Project with Gradle Files` or by pressing `Alt+f` then `g`.
3. Build and test the generated Extention like normal `src` sources. 3. Build and test the generated Extention like normal `src` sources.
- It's recommended to make changes here to skip going through step 1 and 2 multiple times, and when you are done, copying the changes back to `multisrc`. - It's recommended to make changes here to skip going through step 1 and 2 multiple times, and when you are done, copying the changes back to `multisrc`.
### Scaffolding overrides ### Scaffolding overrides
You can use this python script to generate scaffolds for source overrides. Put it inside `multisrc/overrides/<themepkg>/` as `scaffold.py`. You can use this python script to generate scaffolds for source overrides. Put it inside `multisrc/overrides/<themepkg>/` as `scaffold.py`.
```python ```python
import os, sys import os, sys
from pathlib import Path from pathlib import Path
@@ -575,65 +658,80 @@ with open(f"{package}/src/{source}.kt", "w") as f:
``` ```
### Additional Notes ### Additional Notes
- Generated sources extension version code is calculated as `baseVersionCode + overrideVersionCode + multisrcLibraryVersion`. - Generated sources extension version code is calculated as `baseVersionCode + overrideVersionCode + multisrcLibraryVersion`.
- Currently `multisrcLibraryVersion` is `0` - Currently `multisrcLibraryVersion` is `0`
- When a new source is added, it doesn't need to set `overrideVersionCode` as it's default is `0`. - When a new source is added, it doesn't need to set `overrideVersionCode` as it's default is `0`.
- For each time a source changes in a way that should the version increase, `overrideVersionCode` should be increased by one. - For each time a source changes in a way that should the version increase, `overrideVersionCode` should be increased by one.
- When a theme's default implementation changes, `baseVersionCode` should be increased, the initial value should be `1`. - When a theme's default implementation changes, `baseVersionCode` should be increased, the initial value should be `1`.
- For example, for a new theme with a new source, extention version code will be `0 + 0 + 1 = 1`. - For example, for a new theme with a new source, extention version code will be `0 + 0 + 1 = 1`.
- `IntelijConfigurationGeneratorMainKt` should be run on creating or removing a multisrc theme. - `IntelijConfigurationGeneratorMainKt` should be run on creating or removing a multisrc theme.
- On removing a theme, you can manually remove the corresponding configuration in the `.run` folder instead. - On removing a theme, you can manually remove the corresponding configuration in the `.run` folder instead.
- Be careful if you're using sparse checkout. If other configurations are accidentally removed, `git add` the file you want and `git restore` the others. Another choice is to allow `/multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/*` before running the generator. - Be careful if you're using sparse checkout. If other configurations are accidentally removed, `git add` the file you want and `git restore` the others. Another choice is to allow `/multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/*` before running the generator.
## Running ## Running
To make local development more convenient, you can use the following run configuration to launch Tachiyomi directly at the Browse panel: To make local development more convenient, you can use the following run configuration to launch
Komikku directly at the Browse panel:
![](https://i.imgur.com/STy0UFY.png) ![](https://i.imgur.com/STy0UFY.png)
If you're running a Preview or debug build of Tachiyomi: If you're running a Preview or debug build of Komikku:
``` ```
-W -S -n eu.kanade.tachiyomi.debug/eu.kanade.tachiyomi.ui.main.MainActivity -a eu.kanade.tachiyomi.SHOW_CATALOGUES -W -S -n app.komikku.dev/eu.kanade.tachiyomi.ui.main.MainActivity -a eu.kanade.tachiyomi.SHOW_CATALOGUES
``` ```
And for a release build of Tachiyomi: And for a release build of Komikku:
``` ```
-W -S -n eu.kanade.tachiyomi/eu.kanade.tachiyomi.ui.main.MainActivity -a eu.kanade.tachiyomi.SHOW_CATALOGUES -W -S -n app.komikku/eu.kanade.tachiyomi.ui.main.MainActivity -a eu.kanade.tachiyomi.SHOW_CATALOGUES
``` ```
If you're deploying to Android 11 or higher, enable the "Always install with package manager" option in the run configurations. > [!IMPORTANT]
> If you're deploying to Android 11 or higher, enable the "Always install with package manager" option in the run configurations. Without this option enabled, you might face issues such as Android Studio running an older version of the extension without the modifications you might have done.
## Debugging ## Debugging
### Android Debugger ### Android Debugger
> [!IMPORTANT]
> If you didn't build the main app from source with debug enabled and are using a release/beta APK, you **need** a rooted device.
> If you are using an emulator instead, make sure you choose a profile **without** Google Play.
You can leverage the Android Debugger to step through your extension while debugging. You can leverage the Android Debugger to step through your extension while debugging.
You *cannot* simply use Android Studio's `Debug 'module.name'` -> this will most likely result in an error while launching. You _cannot_ simply use Android Studio's `Debug 'module.name'` -> this will most likely result in an error while launching.
Instead, once you've built and installed your extension on the target device, use `Attach Debugger to Android Process` to start debugging Tachiyomi. Instead, once you've built and installed your extension on the target device, use
`Attach Debugger to Android Process` to start debugging Komikku.
![](https://i.imgur.com/muhXyfu.png) ![](https://i.imgur.com/muhXyfu.png)
### Logs ### Logs
You can also elect to simply rely on logs printed from your extension, which You can also elect to simply rely on logs printed from your extension, which
show up in the [`Logcat`](https://developer.android.com/studio/debug/am-logcat) panel of Android Studio. show up in the [`Logcat`](https://developer.android.com/studio/debug/am-logcat) panel of Android Studio.
### Inspecting network calls ### Inspecting network calls
One of the easiest way to inspect network issues (such as HTTP errors 404, 429, no chapter found etc.) is to use the [`Logcat`](https://developer.android.com/studio/debug/am-logcat) panel of Android Studio and filtering by the `OkHttpClient` tag. One of the easiest way to inspect network issues (such as HTTP errors 404, 429, no chapter found etc.) is to use the [`Logcat`](https://developer.android.com/studio/debug/am-logcat) panel of Android Studio and filtering by the `OkHttpClient` tag.
To be able to check the calls done by OkHttp, you need to enable verbose logging in the app, that is not enabled by default and is only included in the Preview versions of Tachiyomi. To enable it, go to More -> Settings -> Advanced -> Verbose logging. After enabling it, don't forget to restart the app. To be able to check the calls done by OkHttp, you need to enable verbose logging in the app, that is not enabled by default and is only included in the Preview versions of Komikku. To enable it, go to More -> Settings -> Advanced -> Verbose logging. After enabling it, don't forget to restart the app.
Inspecting the Logcat allows you to get a good look at the call flow and it's more than enough in most cases where issues occurs. However, alternatively, you can also use an external tool like `mitm-proxy`. For that, refer to the next section. Inspecting the Logcat allows you to get a good look at the call flow and it's more than enough in most cases where issues occurs. However, alternatively, you can also use an external tool like `mitm-proxy`. For that, refer to the subsequent sections.
On newer Android Studio versions, you can use its built-in Network Inspector inside the
App Inspection tool window. This feature provides a nice GUI to inspect the requests made in the app.
To use it, follow the [official documentation](https://developer.android.com/studio/debug/network-profiler) and select Komikku package name in the process list.
### Using external network inspecting tools ### Using external network inspecting tools
If you want to take a deeper look into the network flow, such as taking a look into the request and response bodies, you can use an external tool like `mitm-proxy`. If you want to take a deeper look into the network flow, such as taking a look into the request and response bodies, you can use an external tool like `mitm-proxy`.
#### Setup your proxy server #### Setup your proxy server
We are going to use [mitm-proxy](https://mitmproxy.org/) but you can replace it with any other Web Debugger (i.e. Charles, Burp Suite, Fiddler etc). To install and execute, follow the commands bellow. We are going to use [mitm-proxy](https://mitmproxy.org/) but you can replace it with any other Web Debugger (i.e. Charles, Burp Suite, Fiddler etc). To install and execute, follow the commands bellow.
```console ```console
@@ -655,8 +753,8 @@ $ docker run --rm -it -p 8080:8080 \
After installing and running, open your browser and navigate to http://127.0.0.1:8081. After installing and running, open your browser and navigate to http://127.0.0.1:8081.
#### OkHttp proxy setup #### OkHttp proxy setup
Since most of the manga sources are going to use HTTPS, we need to disable SSL verification in order to use the web debugger. For that, add this code to inside your source class:
Since most of the manga sources are going to use HTTPS, we need to disable SSL verification in order to use the web debugger. For that, add this code to inside your source class:
```kotlin ```kotlin
package eu.kanade.tachiyomi.extension.en.mangasource package eu.kanade.tachiyomi.extension.en.mangasource
@@ -702,23 +800,38 @@ class MangaSource : MangaTheme(
} }
``` ```
Note: `10.0.2.2` is usually the address of your loopback interface in the android emulator. If Tachiyomi tells you that it's unable to connect to 10.0.2.2:8080 you will likely need to change it (the same if you are using hardware device). Note: `10.0.2.2` is usually the address of your loopback interface in the android emulator. If Komikku tells you that it's unable to connect to 10.0.2.2:8080 you will likely need to change it (the same if you are using hardware device).
If all went well, you should see all requests and responses made by the source in the web interface of `mitmweb`. If all went well, you should see all requests and responses made by the source in the web interface of `mitmweb`.
## Building ## Building
APKs can be created in Android Studio via `Build > Build Bundle(s) / APK(s) > Build APK(s)` or `Build > Generate Signed Bundle / APK`. APKs can be created in Android Studio via `Build > Build Bundle(s) / APK(s) > Build APK(s)` or
`Build > Generate Signed Bundle / APK`.
If for some reason you decide to build the APK from the command line, you can use the following
command (because you're doing things differently than expected, I assume you have some
knowledge of gradlew and your OS):
```console
// For a single apk, use this command
$ ./gradlew src:<lang>:<source>:assembleDebug
```
## Submitting the changes ## Submitting the changes
When you feel confident about your changes, submit a new Pull Request so your code can be reviewed and merged if it's approved. We encourage following a [GitHub Standard Fork & Pull Request Workflow](https://gist.github.com/Chaser324/ce0505fbed06b947d962) and following the good practices of the workflow, such as not commiting directly to `master`: always create a new branch for your changes. When you feel confident about your changes, submit a new Pull Request so your code can be reviewed and merged if it's approved. We encourage following a [GitHub Standard Fork & Pull Request Workflow](https://gist.github.com/Chaser324/ce0505fbed06b947d962) and following the good practices of the workflow, such as not commiting directly to `master`: always create a new branch for your changes.
If you are more comfortable about using Git GUI-based tools, you can refer to [this guide](https://learntodroid.com/how-to-use-git-and-github-in-android-studio/) about the Git integration inside Android Studio, specifically the "How to Contribute to an to Existing Git Repository in Android Studio" section of the guide. If you are more comfortable about using Git GUI-based tools, you can refer to [this guide](https://learntodroid.com/how-to-use-git-and-github-in-android-studio/)
about the Git integration inside Android Studio, specifically the "How to Contribute to an to Existing
Git Repository in Android Studio" section of the guide.
Make sure you have generated the extension icon using the linked Icon Generator tool in the [Tools](#tools) section. The icon must follow the pattern adopted by all other extensions: a square with rounded corners. > [!IMPORTANT]
> Make sure you have generated the extension icon using the linked Icon Generator tool in the [Tools](#tools)
> section. The icon **must follow the pattern** adopted by all other extensions: a square with rounded
> corners. Make sure to remove the generated `web_hi_res_512.png`.
Please **do test your changes by compiling it through Android Studio** before submitting it. Also make sure to follow the PR checklist available in the PR body field when creating a new PR. As a reference, you can find it below. Please **do test your changes by compiling it through Android Studio** before submitting it. Obvious untested PRs will not be merged, such as ones created with the GitHub web interface. Also make sure to follow the PR checklist available in the PR body field when creating a new PR. As a reference, you can find it below.
### Pull Request checklist ### Pull Request checklist
@@ -728,3 +841,4 @@ Please **do test your changes by compiling it through Android Studio** before su
- Add the `isNsfw = true` flag in `build.gradle` when appropriate - Add the `isNsfw = true` flag in `build.gradle` when appropriate
- Explicitly kept the `id` if a source's name or language were changed - Explicitly kept the `id` if a source's name or language were changed
- Test the modifications by compiling and running the extension through Android Studio - Test the modifications by compiling and running the extension through Android Studio
- Have removed `web_hi_res_512.png` when adding a new extension

315
LICENSE
View File

@@ -2,180 +2,180 @@
Version 2.0, January 2004 Version 2.0, January 2004
http://www.apache.org/licenses/ http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions. 1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, "License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document. and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by "Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License. the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all "Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition, control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the "control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity. outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity "You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License. exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, "Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation including but not limited to software source code, documentation
source, and configuration files. source, and configuration files.
"Object" form shall mean any form resulting from mechanical "Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation, not limited to compiled object code, generated documentation,
and conversions to other media types. and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or "Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work copyright notice that is included in or attached to the work
(an example is provided in the Appendix below). (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object "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 form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of, separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof. the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including "Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner 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 or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted" the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution." designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity "Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work. subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of 2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual, this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of, copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form. Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of 3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual, this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made, (except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work, use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s) Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate granted to You under this License for that Work shall terminate
as of the date such litigation is filed. as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the 4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You modifications, and in Source or Object form, provided that You
meet the following conditions: meet the following conditions:
(a) You must give any other recipients of the Work or (a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices (b) You must cause any modified files to carry prominent notices
stating that You changed the files; and stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works (c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work, attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of excluding those notices that do not pertain to any part of
the Derivative Works; and the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its (d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or, documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed that such additional attribution notices cannot be construed
as modifying the License. as modifying the License.
You may add Your own copyright statement to Your modifications and You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use, for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License. the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, 5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions. this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions. with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade 6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor, names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file. origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or 7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS, Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License. risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, 8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise, whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the 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 (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages. has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing 9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer, the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity, and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify, of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability. of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work. APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}" boilerplate notice, with the fields enclosed by brackets "{}"
@@ -186,17 +186,16 @@
same "printed page" as the copyright notice for easier same "printed page" as the copyright notice for easier
identification within third-party archives. identification within third-party archives.
Copyright {yyyy} {name of copyright owner} Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.

View File

@@ -1,29 +1,48 @@
| Build | Support Server | | Build | Up to date | Install to app |
|-------|---------| |-------|------------|----------------|
| [![CI](https://github.com/tachiyomiorg/tachiyomi-extensions/workflows/CI/badge.svg?event=push)](https://github.com/tachiyomiorg/tachiyomi-extensions/actions/workflows/build_push.yml) | [![Discord](https://img.shields.io/discord/349436576037732353.svg?label=discord&labelColor=7289da&color=2c2f33&style=flat)](https://discord.gg/tachiyomi) | | [![Build](https://github.com/yuzono/tachiyomi-extensions/actions/workflows/build_push.yml/badge.svg)](https://github.com/yuzono/tachiyomi-extensions/actions/workflows/build_push.yml) | [![Updated](https://img.shields.io/github/actions/workflow/status/yuzono/tachiyomi-extensions/auto_cherry_pick.yml?label=Updated&labelColor=27303D)](https://github.com/yuzono/tachiyomi-extensions/actions/workflows/auto_cherry_pick.yml) | [![Install](https://img.shields.io/badge/Click%20here%20to%20install%20repo-gray?style=flat&labelColor=red)](https://intradeus.github.io/http-protocol-redirector/?r=tachiyomi://add-repo?url=https://raw.githubusercontent.com/yuzono/manga-repo/repo/index.min.json) |
# ![app icon](./.github/readme-images/app-icon.png)Tachiyomi Extensions # Komikku / Mihon / Tachiyomi Extensions
Tachiyomi is a free and open source manga reader for Android 6.0 and above.
This repository contains the available extension catalogues for the [Tachiyomi](https://github.com/tachiyomiorg/tachiyomi) app. This repository contains extension catalogues which are compatible with [Komikku](https://github.com/komikku-app/komikku) and Mihon / Tachiyomi or other forks.
# Usage This repository automatically merges any updates from [Keiyoushi](https://github.com/keiyoushi/extensions-source) every 6 hours to have the best of community contributions. Beside from that, it has a few of my developed extensions or some improvements. Enjoy!
Extension sources can be downloaded, installed, and uninstalled via the main Tachiyomi app. They are installed and uninstalled like regular apps, in `.apk` format. Some extensions from this repo provide better support for Komikku's `Suggestions` feature.
## Downloads ## Recommend App
If you prefer to directly download the APK files, they are available via https://tachiyomi.org/extensions/ or directly in this GitHub repository in the [`repo` branch](https://github.com/tachiyomiorg/tachiyomi-extensions/tree/repo/apk). ### [Komikku](https://github.com/komikku-app/komikku)
### [Mihon](https://github.com/mihonapp/mihon)
## How to add the repo
**If you are new to repository/extensions, please read the [Yūzōnō Getting Started guide](https://yuzono.github.io/docs/guides/getting-started#adding-the-extension-repo) first.**
* You can add our repo by visiting the [Yūzōnō Website](https://yuzono.github.io/add-repo)
* Otherwise, copy & paste the following URL:
```html
https://raw.githubusercontent.com/yuzono/manga-repo/repo/index.min.json
```
# Requests # Requests
Source requests here are meant as up-for-grabs for any developer, thus it's impossible to provide a time estimation for any of them. Furthermore, some sites are impossible to do, usually because of various technical reasons. To request a new source or bug fix, [create an issue](https://github.com/yuzono/tachiyomi-extensions/issues/new/choose).
Please note that creating an issue does not mean that the source will be added or fixed in a timely
fashion, because the work is volunteer-based. Some sources may also be impossible to do or prohibitively
difficult to maintain.
If you would like to see a request fulfilled and have the necessary skills to do so, consider contributing!
Issues are up-for-grabs for any developer if there is no assigned user already.
# Contributing # Contributing
Contributions are welcome! Contributions are welcome!
Check out the repo's [issue backlog](https://github.com/tachiyomiorg/tachiyomi-extensions/issues) for source requests and bug reports. Check out the repo's [issue backlog](https://github.com/yuzono/tachiyomi-extensions/issues) for source requests and bug reports.
To get started with development, see [CONTRIBUTING.md](./CONTRIBUTING.md). To get started with development, see [CONTRIBUTING.md](./CONTRIBUTING.md).
@@ -31,20 +50,25 @@ It might also be good to read our [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md).
## License ## License
Copyright 2015 Javier Tomás Copyright 2015 Javier Tomás
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
## Disclaimer ## Disclaimer
This project does not have any affiliation with the content providers available.
This project is not affiliated with Komikku/Mihon/Tachiyomi. Don't ask for help about these extensions at the
official support means of Komikku/Mihon/Tachiyomi. All credits to the codebase goes to the original contributors.
The developer of this application does not have any affiliation with the content providers available. The developer of this application does not have any affiliation with the content providers available.

View File

@@ -1,68 +0,0 @@
**There is no timetable on when or if a source request may be filled (also applies to bug reports and enhancement requests).**
### In General the following sources that won't be added as an extension
- In general heavily paywalled sites
- Sources that require cracking some app's source code (realistically, no one's going to put in the effort to do it)
- Sources that are known for filling a lot of DMCA complaints over repositories on GitHub
Here is a list of known sources that were removed.
## Removed sources
### Too difficult to maintain
- Anchira https://github.com/tachiyomiorg/tachiyomi-extensions/pull/19149
- Bakai https://github.com/tachiyomiorg/tachiyomi-extensions/pull/17890
- Blackout Comics and Izakaya https://github.com/tachiyomiorg/tachiyomi-extensions/pull/18500
- ColaManhua (COLA漫画) https://github.com/tachiyomiorg/tachiyomi-extensions/pull/11445
- Comikey https://github.com/tachiyomiorg/tachiyomi-extensions/pull/11971
- Constellar Scans https://github.com/tachiyomiorg/tachiyomi-extensions/pull/17277
- CopyManga (拷贝漫画) https://github.com/tachiyomiorg/tachiyomi-extensions/pull/12376
- Cứu Truyện https://github.com/tachiyomiorg/tachiyomi-extensions/pull/16654
- Hentai Kai https://github.com/tachiyomiorg/tachiyomi-extensions/issues/9999
- Hitomi.la https://github.com/tachiyomiorg/tachiyomi-extensions/pull/11613
- HQ Dragon https://github.com/tachiyomiorg/tachiyomi-extensions/pull/7065
- Japscan https://github.com/tachiyomiorg/tachiyomi-extensions/pull/17892
- Koushoku https://github.com/tachiyomiorg/tachiyomi-extensions/pull/13329
- LeerCapitulo https://github.com/tachiyomiorg/tachiyomi-extensions/pull/16255
- Mangá Host https://github.com/tachiyomiorg/tachiyomi-extensions/pull/7065
- Mangá Livre and Leitor.net https://github.com/tachiyomiorg/tachiyomi-extensions/pull/8679
- MangaDig https://github.com/tachiyomiorg/tachiyomi-extensions/pull/14974
- Mangas.pw (Mangas.in) https://github.com/tachiyomiorg/tachiyomi-extensions/pull/9489
- MangaYabu! https://github.com/tachiyomiorg/tachiyomi-extensions/pull/9336
- ManhuaScan https://github.com/tachiyomiorg/tachiyomi-extensions/pull/7129
- ManhwaHot https://github.com/tachiyomiorg/tachiyomi-extensions/pull/7129
- Mode Scanlator https://github.com/tachiyomiorg/tachiyomi-extensions/pull/17865
- Neox Scanlator https://github.com/tachiyomiorg/tachiyomi-extensions/pull/12695
- Reaper Scans (EN) https://github.com/tachiyomiorg/tachiyomi-extensions/pull/16819
- SuperMangás and SuperHentais https://github.com/tachiyomiorg/tachiyomi-extensions/pull/6348
- TopToon+/Day Comics https://github.com/tachiyomiorg/tachiyomi-extensions/pull/10851
- Tsuki Mangás https://github.com/tachiyomiorg/tachiyomi-extensions/pull/8609
- Union Mangás https://github.com/tachiyomiorg/tachiyomi-extensions/pull/7065
- YES Mangás https://github.com/tachiyomiorg/tachiyomi-extensions/pull/7065
### Requested removal by the scanlator team
- ARES Manga https://github.com/tachiyomiorg/tachiyomi-extensions/issues/15396
- Astra Scans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/13845
- Dat-Gar Scan https://github.com/tachiyomiorg/tachiyomi-extensions/issues/18441
- Gourmet Scans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/6192
- Hikari Scans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/6611
- Hunter Scans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/12392
- JuinJutsuReader https://github.com/tachiyomiorg/tachiyomi-extensions/issues/2958
- Knightnoscanlation https://github.com/tachiyomiorg/tachiyomi-extensions/issues/4240
- KomikTap/KomikTap.in https://github.com/tachiyomiorg/tachiyomi-extensions/issues/6133
- Luminous Scans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/9923
- MangaPro https://github.com/tachiyomiorg/tachiyomi-extensions/issues/13989
- MangaSY https://github.com/tachiyomiorg/tachiyomi-extensions/issues/12007
- Mangawow https://github.com/tachiyomiorg/tachiyomi-extensions/issues/5367
- MHScans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/15319
- Mono Manga https://github.com/tachiyomiorg/tachiyomi-extensions/issues/17634
- Moon Daisy Scans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/17929
- NarTag https://github.com/tachiyomiorg/tachiyomi-extensions/issues/8038
- Plot-twistnf-scans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/4242
- Realm Scans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/15586
- Remangas https://github.com/tachiyomiorg/tachiyomi-extensions/issues/18807
- Reset Scans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/13168
- SetsuScans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/11040
- ShinobiScans https://github.com/tachiyomiorg/tachiyomi-extensions/issues/14457
- XXX Yaoi https://github.com/tachiyomiorg/tachiyomi-extensions/issues/9535

View File

@@ -1,17 +1,3 @@
buildscript {
repositories {
mavenCentral()
google()
maven(url = "https://plugins.gradle.org/m2/")
}
dependencies {
classpath(libs.gradle.agp)
classpath(libs.gradle.kotlin)
classpath(libs.gradle.serialization)
classpath(libs.gradle.kotlinter)
}
}
allprojects { allprojects {
repositories { repositories {
mavenCentral() mavenCentral()
@@ -19,7 +5,3 @@ allprojects {
maven(url = "https://jitpack.io") maven(url = "https://jitpack.io")
} }
} }
tasks.register<Delete>("clean") {
delete(rootProject.layout.buildDirectory.asFile.get())
}

View File

@@ -3,5 +3,14 @@ plugins {
} }
repositories { repositories {
gradlePluginPortal()
mavenCentral() mavenCentral()
google()
}
dependencies {
implementation(libs.gradle.agp)
implementation(libs.gradle.kotlin)
implementation(libs.gradle.serialization)
implementation(libs.gradle.kotlinter)
} }

View File

@@ -1,6 +1,5 @@
object AndroidConfig { object AndroidConfig {
const val compileSdk = 34 const val compileSdk = 34
const val minSdk = 21 const val minSdk = 21
@Suppress("UNUSED")
const val targetSdk = 34 const val targetSdk = 34
} }

View File

@@ -1,7 +1,18 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlinx-serialization'
apply plugin: 'org.jmailen.kotlinter' apply plugin: 'org.jmailen.kotlinter'
assert !ext.has("pkgNameSuffix")
assert !ext.has("libVersion")
assert extName.chars().max().asInt < 0x180 : "Extension name should be romanized"
Project theme = ext.has("themePkg") ? project(":lib-multisrc:$themePkg") : null
if (theme != null) evaluationDependsOn(theme.path)
android { android {
compileSdkVersion AndroidConfig.compileSdk compileSdk AndroidConfig.compileSdk
namespace "eu.kanade.tachiyomi.extension" namespace "eu.kanade.tachiyomi.extension"
sourceSets { sourceSets {
@@ -11,38 +22,35 @@ android {
res.srcDirs = ['res'] res.srcDirs = ['res']
assets.srcDirs = ['assets'] assets.srcDirs = ['assets']
} }
release {
manifest.srcFile "AndroidManifest.xml"
}
debug {
manifest.srcFile "AndroidManifest.xml"
}
} }
defaultConfig { defaultConfig {
minSdkVersion AndroidConfig.minSdk minSdk AndroidConfig.minSdk
targetSdkVersion AndroidConfig.targetSdk targetSdk AndroidConfig.targetSdk
applicationIdSuffix pkgNameSuffix applicationIdSuffix project.parent.name + "." + project.name
versionCode extVersionCode Integer kmkVersionCode = project.ext.find("kmkVersionCode") ?: 0
versionName project.ext.properties.getOrDefault("libVersion", "1.4") + ".$extVersionCode" Integer kmkBaseVersionCode = theme == null ? 0 : theme.ext.find("kmkBaseVersionCode") ?: 0
setProperty("archivesBaseName", "tachiyomi-$pkgNameSuffix-v$versionName") versionCode theme == null ? extVersionCode + kmkVersionCode : theme.baseVersionCode + overrideVersionCode + kmkBaseVersionCode + kmkVersionCode
def readmes = project.projectDir.listFiles({ File file -> versionName "1.4.$versionCode"
file.name == "README.md" || file.name == "CHANGELOG.md" base {
} as FileFilter) archivesName = "tachiyomi-$applicationIdSuffix-v$versionName"
def hasReadme = readmes != null && readmes.any { File file ->
file.name.startsWith("README")
}
def hasChangelog = readmes != null && readmes.any { File file ->
file.name.startsWith("CHANGELOG")
} }
assert extClass.startsWith(".")
manifestPlaceholders = [ manifestPlaceholders = [
appName : "Tachiyomi: $extName", appName : "Tachiyomi: $extName",
extClass: extClass, extClass: extClass,
extFactory: project.ext.properties.getOrDefault("extFactory", ""), nsfw : project.ext.find("isNsfw") ? 1 : 0,
nsfw: project.ext.properties.getOrDefault("isNsfw", false) ? 1 : 0,
hasReadme: hasReadme ? 1 : 0,
hasChangelog: hasChangelog ? 1 : 0,
] ]
String baseUrl = project.ext.find("baseUrl") ?: ""
if (theme != null && !baseUrl.isEmpty()) {
def split = baseUrl.split("://")
assert split.length == 2
def path = split[1].split("/")
manifestPlaceholders += [
SOURCEHOST : path[0],
SOURCESCHEME: split[0],
]
}
} }
signingConfigs { signingConfigs {
@@ -58,6 +66,7 @@ android {
release { release {
signingConfig signingConfigs.release signingConfig signingConfigs.release
minifyEnabled false minifyEnabled false
vcsInfo.include false
} }
} }
@@ -66,20 +75,20 @@ android {
} }
buildFeatures { buildFeatures {
// Disable unused AGP features buildConfig true
aidl false }
renderScript false
resValues false packaging {
shaders false resources.excludes.add("kotlin-tooling-metadata.json")
} }
compileOptions { compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8 sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_17
} }
kotlinOptions { kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString() jvmTarget = JavaVersion.VERSION_17.toString()
freeCompilerArgs += "-opt-in=kotlinx.serialization.ExperimentalSerializationApi" freeCompilerArgs += "-opt-in=kotlinx.serialization.ExperimentalSerializationApi"
} }
@@ -92,14 +101,29 @@ android {
} }
} }
repositories {
mavenCentral()
}
dependencies { dependencies {
if (theme != null) implementation(theme) // Overrides core launcher icons
implementation(project(":core")) implementation(project(":core"))
compileOnly(libs.bundles.common) compileOnly(libs.bundles.common)
implementation(project(":utils"))
} }
preBuild.dependsOn(lintKotlin) tasks.register("writeManifestFile") {
lintKotlin.dependsOn(formatKotlin) doLast {
def manifest = android.sourceSets.getByName("main").manifest
if (!manifest.srcFile.exists()) {
File tempFile = layout.buildDirectory.get().file("tempAndroidManifest.xml").getAsFile()
if (!tempFile.exists()) {
tempFile.withWriter {
it.write('<?xml version="1.0" encoding="utf-8"?>\n<manifest />\n')
}
}
manifest.srcFile(tempFile.path)
}
}
}
preBuild.dependsOn(writeManifestFile, lintKotlin)
if (System.getenv("CI") != "true") {
lintKotlin.dependsOn(formatKotlin)
}

View File

@@ -6,10 +6,7 @@
<application android:icon="@mipmap/ic_launcher" android:allowBackup="false" android:label="${appName}"> <application android:icon="@mipmap/ic_launcher" android:allowBackup="false" android:label="${appName}">
<meta-data android:name="tachiyomi.extension.class" android:value="${extClass}" /> <meta-data android:name="tachiyomi.extension.class" android:value="${extClass}" />
<meta-data android:name="tachiyomi.extension.factory" android:value="${extFactory}" />
<meta-data android:name="tachiyomi.extension.nsfw" android:value="${nsfw}" /> <meta-data android:name="tachiyomi.extension.nsfw" android:value="${nsfw}" />
<meta-data android:name="tachiyomi.extension.hasReadme" android:value="${hasReadme}" />
<meta-data android:name="tachiyomi.extension.hasChangelog" android:value="${hasChangelog}" />
</application> </application>

View File

@@ -9,9 +9,8 @@ android {
minSdk = AndroidConfig.minSdk minSdk = AndroidConfig.minSdk
} }
namespace = "eu.kanade.tachiyomi.extension" namespace = "eu.kanade.tachiyomi.extension.core"
@Suppress("UnstableApiUsage")
sourceSets { sourceSets {
named("main") { named("main") {
manifest.srcFile("AndroidManifest.xml") manifest.srcFile("AndroidManifest.xml")
@@ -19,9 +18,8 @@ android {
} }
} }
libraryVariants.all { buildFeatures {
generateBuildConfigProvider?.configure { resValues = false
enabled = false shaders = false
}
} }
} }

View File

@@ -21,3 +21,7 @@ org.gradle.caching=true
# Enable AndroidX dependencies # Enable AndroidX dependencies
android.useAndroidX=true android.useAndroidX=true
android.enableBuildConfigAsBytecode=true
android.defaults.buildfeatures.resvalues=false
android.defaults.buildfeatures.shaders=false

View File

@@ -2,14 +2,15 @@
kotlin_version = "1.7.21" kotlin_version = "1.7.21"
coroutines_version = "1.6.4" coroutines_version = "1.6.4"
serialization_version = "1.4.0" serialization_version = "1.4.0"
coreVersion = "1.16.0"
[libraries] [libraries]
gradle-agp = { module = "com.android.tools.build:gradle", version = "7.4.2" } gradle-agp = { module = "com.android.tools.build:gradle", version = "8.10.1" }
gradle-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin_version" } gradle-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin_version" }
gradle-serialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kotlin_version" } gradle-serialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kotlin_version" }
gradle-kotlinter = { module = "org.jmailen.gradle:kotlinter-gradle", version = "3.13.0" } gradle-kotlinter = { module = "org.jmailen.gradle:kotlinter-gradle", version = "3.13.0" }
tachiyomi-lib = { module = "com.github.tachiyomiorg:extensions-lib", version = "1.4.2" } tachiyomi-lib = { module = "com.github.komikku-app:extensions-lib", version = "1.7.1" }
kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8", version.ref = "kotlin_version" } kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8", version.ref = "kotlin_version" }
kotlin-protobuf = { module = "org.jetbrains.kotlinx:kotlinx-serialization-protobuf", version.ref = "serialization_version" } kotlin-protobuf = { module = "org.jetbrains.kotlinx:kotlinx-serialization-protobuf", version.ref = "serialization_version" }
@@ -18,11 +19,12 @@ kotlin-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", ver
coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines_version" } coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines_version" }
coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines_version" } coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines_version" }
injekt-core = { module = "com.github.inorichi.injekt:injekt-core", version = "65b0440" } injekt-core = { module = "com.github.null2264.injekt:injekt-core", version = "4135455a2a" }
rxjava = { module = "io.reactivex:rxjava", version = "1.3.8" } rxjava = { module = "io.reactivex:rxjava", version = "1.3.8" }
jsoup = { module = "org.jsoup:jsoup", version = "1.15.1" } jsoup = { module = "org.jsoup:jsoup", version = "1.15.1" }
okhttp = { module = "com.squareup.okhttp3:okhttp", version = "5.0.0-alpha.11" } okhttp = { module = "com.squareup.okhttp3:okhttp", version = "5.0.0-alpha.11" }
quickjs = { module = "app.cash.quickjs:quickjs-android", version = "0.9.2" } quickjs = { module = "app.cash.quickjs:quickjs-android", version = "0.9.2" }
core = { group = "androidx.core", name = "core", version.ref = "coreVersion" }
[bundles] [bundles]
common = ["kotlin-stdlib", "coroutines-core", "coroutines-android", "injekt-core", "rxjava", "kotlin-protobuf", "kotlin-json", "jsoup", "okhttp", "tachiyomi-lib", "quickjs"] common = ["kotlin-stdlib", "coroutines-core", "coroutines-android", "injekt-core", "rxjava", "kotlin-protobuf", "kotlin-json", "jsoup", "okhttp", "tachiyomi-lib", "quickjs"]

Binary file not shown.

View File

@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

33
gradlew vendored
View File

@@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
# #
@@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # 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. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@@ -83,10 +85,8 @@ done
# This is normally unused # This is normally unused
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # 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
# 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"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -133,10 +133,13 @@ location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 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 Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
@@ -144,7 +147,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045 # shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
@@ -152,7 +155,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045 # shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@@ -197,11 +200,15 @@ if "$cygwin" || "$msys" ; then
done done
fi fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
# shell script including quotes and variable substitutions, so put them in DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded. # 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 -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \

186
gradlew.bat vendored
View File

@@ -1,92 +1,94 @@
@rem @rem
@rem Copyright 2015 the original author or authors. @rem Copyright 2015 the original author or authors.
@rem @rem
@rem Licensed under the Apache License, Version 2.0 (the "License"); @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 not use this file except in compliance with the License.
@rem You may obtain a copy of the License at @rem You may obtain a copy of the License at
@rem @rem
@rem https://www.apache.org/licenses/LICENSE-2.0 @rem https://www.apache.org/licenses/LICENSE-2.0
@rem @rem
@rem Unless required by applicable law or agreed to in writing, software @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 distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@if "%DEBUG%"=="" @echo off @rem
@rem ##########################################################################
@rem @if "%DEBUG%"=="" @echo off
@rem Gradle startup script for Windows @rem ##########################################################################
@rem @rem
@rem ########################################################################## @rem Gradle startup script for Windows
@rem
@rem Set local scope for the variables with windows NT shell @rem ##########################################################################
if "%OS%"=="Windows_NT" setlocal
@rem Set local scope for the variables with windows NT shell
set DIRNAME=%~dp0 if "%OS%"=="Windows_NT" setlocal
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused set DIRNAME=%~dp0
set APP_BASE_NAME=%~n0 if "%DIRNAME%"=="" set DIRNAME=.
set APP_HOME=%DIRNAME% @rem This is normally unused
set APP_BASE_NAME=%~n0
@rem Resolve any "." and ".." in APP_HOME to make it shorter. set APP_HOME=%DIRNAME%
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
@rem Find java.exe set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
if defined JAVA_HOME goto findJavaFromJavaHome
@rem Find java.exe
set JAVA_EXE=java.exe if defined JAVA_HOME goto findJavaFromJavaHome
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
echo. if %ERRORLEVEL% equ 0 goto execute
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo location of your Java installation. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
goto fail echo location of your Java installation. 1>&2
:findJavaFromJavaHome goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe :findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
if exist "%JAVA_EXE%" goto execute set JAVA_EXE=%JAVA_HOME%/bin/java.exe
echo. if exist "%JAVA_EXE%" goto execute
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo location of your Java installation. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
goto fail echo location of your Java installation. 1>&2
:execute goto fail
@rem Setup the command line
:execute
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @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 %*
@rem Execute Gradle
:end "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd :end
@rem End local scope for the variables with windows NT shell
:fail if %ERRORLEVEL% equ 0 goto mainEnd
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! :fail
set EXIT_CODE=%ERRORLEVEL% rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
if %EXIT_CODE% equ 0 set EXIT_CODE=1 rem the _cmd.exe /c_ return code!
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% set EXIT_CODE=%ERRORLEVEL%
exit /b %EXIT_CODE% if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
:mainEnd exit /b %EXIT_CODE%
if "%OS%"=="Windows_NT" endlocal
:mainEnd
:omega if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -133,4 +133,4 @@
<option name="CONTINUATION_INDENT_SIZE" value="4" /> <option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions> </indentOptions>
</codeStyleSettings> </codeStyleSettings>
</code_scheme> </code_scheme>

View File

@@ -0,0 +1,45 @@
package eu.kanade.tachiyomi.multisrc.gmanga
import android.util.Base64
import java.security.MessageDigest
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
fun decrypt(responseData: String): String {
val enc = responseData.split("|")
val secretKey = enc[3].sha256().hexStringToByteArray()
return enc[0].aesDecrypt(secretKey, enc[2])
}
private fun String.hexStringToByteArray(): ByteArray {
val len = length
val data = ByteArray(len / 2)
var i = 0
while (i < len) {
data[i / 2] = (
(Character.digit(this[i], 16) shl 4) +
Character.digit(this[i + 1], 16)
).toByte()
i += 2
}
return data
}
private fun String.sha256(): String {
return MessageDigest
.getInstance("SHA-256")
.digest(toByteArray())
.fold("") { str, it -> str + "%02x".format(it) }
}
private fun String.aesDecrypt(secretKey: ByteArray, ivString: String): String {
val c = Cipher.getInstance("AES/CBC/PKCS5Padding")
val sk = SecretKeySpec(secretKey, "AES")
val iv = IvParameterSpec(Base64.decode(ivString.toByteArray(Charsets.UTF_8), Base64.DEFAULT))
c.init(Cipher.DECRYPT_MODE, sk, iv)
val byteStr = Base64.decode(toByteArray(Charsets.UTF_8), Base64.DEFAULT)
return String(c.doFinal(byteStr))
}

View File

@@ -0,0 +1,41 @@
package eu.kanade.tachiyomi.multisrc.mangaworld
import eu.kanade.tachiyomi.network.GET
import okhttp3.Cookie
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
class CookieRedirectInterceptor(private val client: OkHttpClient) : Interceptor {
private val cookieRegex = Regex("""document\.cookie="(MWCookie[^"]+)""")
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val response = chain.proceed(request)
val contentType = response.header("content-type")
if (contentType != null && contentType.startsWith("image/", ignoreCase = true)) {
return response
}
// ignore requests that already have completed the JS challenge
if (response.headers["vary"] != null) return response
val content = response.body.string()
val results = cookieRegex.find(content)
?: return response.newBuilder().body(content.toResponseBody(response.body.contentType())).build()
val (cookieString) = results.destructured
return chain.proceed(loadCookie(request, cookieString))
}
private fun loadCookie(request: Request, cookieString: String): Request {
val cookie = Cookie.parse(request.url, cookieString)!!
client.cookieJar.saveFromResponse(request.url, listOf(cookie))
val headers = request.headers.newBuilder()
.add("Cookie", cookie.toString())
.build()
return GET(request.url, headers)
}
}

View File

@@ -0,0 +1,3 @@
plugins {
id("lib-android")
}

View File

@@ -0,0 +1,59 @@
package eu.kanade.tachiyomi.lib.cookieinterceptor
import android.webkit.CookieManager
import okhttp3.Interceptor
import okhttp3.Response
class CookieInterceptor(
private val domain: String,
private val cookies: List<Pair<String, String>>
) : Interceptor {
constructor(domain: String, cookie: Pair<String, String>) : this(domain, listOf(cookie))
init {
val url = "https://$domain/"
cookies.forEach {
val cookie = "${it.first}=${it.second}; Domain=$domain; Path=/"
setCookie(url, cookie)
}
}
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
if (!request.url.host.endsWith(domain)) return chain.proceed(request)
val cookieList = request.header("Cookie")?.split("; ") ?: emptyList()
if (cookies.all { (key, value) -> "$key=$value" in cookieList })
return chain.proceed(request)
cookies.forEach { (key, value) ->
setCookie("https://$domain/", "$key=$value; Domain=$domain; Path=/")
}
val newCookie = buildList(cookieList.size + cookies.size) {
cookieList.filterNotTo(this) { existing ->
cookies.any { (key, _) ->
existing.startsWith("$key=")
}
}
cookies.forEach { (key, value) ->
add("$key=$value")
}
}.joinToString("; ")
val newRequest = request.newBuilder()
.header("Cookie", newCookie)
.build()
return chain.proceed(newRequest)
}
private val cookieManager by lazy { CookieManager.getInstance() }
private fun setCookie(url: String, value: String) {
try {
cookieManager.setCookie(url, value)
} catch (_: Exception) { }
}
}

View File

@@ -1,22 +1,3 @@
plugins { plugins {
id("com.android.library") id("lib-android")
kotlin("android")
}
android {
compileSdk = AndroidConfig.compileSdk
defaultConfig {
minSdk = AndroidConfig.minSdk
}
namespace = "eu.kanade.tachiyomi.lib.cryptoaes"
}
repositories {
mavenCentral()
}
dependencies {
compileOnly(libs.kotlin.stdlib)
} }

View File

@@ -5,6 +5,7 @@ import android.util.Base64
import java.security.MessageDigest import java.security.MessageDigest
import java.util.Arrays import java.util.Arrays
import javax.crypto.Cipher import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec import javax.crypto.spec.SecretKeySpec

View File

@@ -1,24 +1,3 @@
plugins { plugins {
id("com.android.library") id("lib-android")
kotlin("android")
}
android {
compileSdk = AndroidConfig.compileSdk
defaultConfig {
minSdk = AndroidConfig.minSdk
}
namespace = "eu.kanade.tachiyomi.lib.dataimage"
}
repositories {
mavenCentral()
}
dependencies {
compileOnly(libs.kotlin.stdlib)
compileOnly(libs.okhttp)
compileOnly(libs.jsoup)
} }

View File

@@ -1,22 +1,3 @@
plugins { plugins {
id("com.android.library") id("lib-android")
kotlin("android")
}
android {
compileSdk = AndroidConfig.compileSdk
defaultConfig {
minSdk = AndroidConfig.minSdk
}
namespace = "eu.kanade.tachiyomi.lib.i18n"
}
repositories {
mavenCentral()
}
dependencies {
compileOnly(libs.kotlin.stdlib)
} }

View File

@@ -0,0 +1,3 @@
plugins {
id("lib-android")
}

View File

@@ -0,0 +1,294 @@
package eu.kanade.tachiyomi.lib.lzstring
typealias getCharFromIntFn = (it: Int) -> String
typealias getNextValueFn = (it: Int) -> Int
/**
* Reimplementation of [lz-string](https://github.com/pieroxy/lz-string) compression/decompression.
*/
object LZString {
private fun compress(
uncompressed: String,
bitsPerChar: Int,
getCharFromInt: getCharFromIntFn,
): String {
val context = CompressionContext(uncompressed.length, bitsPerChar, getCharFromInt)
for (ii in uncompressed.indices) {
context.c = uncompressed[ii].toString()
if (!context.dictionary.containsKey(context.c)) {
context.dictionary[context.c] = context.dictSize++
context.dictionaryToCreate[context.c] = true
}
context.wc = context.w + context.c
if (context.dictionary.containsKey(context.wc)) {
context.w = context.wc
continue
}
context.outputCodeForW()
context.decrementEnlargeIn()
context.dictionary[context.wc] = context.dictSize++
context.w = context.c
}
if (context.w.isNotEmpty()) {
context.outputCodeForW()
context.decrementEnlargeIn()
}
// Mark the end of the stream
context.value = 2
for (i in 0 until context.numBits) {
context.dataVal = (context.dataVal shl 1) or (context.value and 1)
context.appendDataOrAdvancePosition()
context.value = context.value shr 1
}
while (true) {
context.dataVal = context.dataVal shl 1
if (context.dataPosition == bitsPerChar - 1) {
context.data.append(getCharFromInt(context.dataVal))
break
}
context.dataPosition++
}
return context.data.toString()
}
private fun decompress(length: Int, resetValue: Int, getNextValue: getNextValueFn): String {
val dictionary = mutableListOf<String>()
val result = StringBuilder()
val data = DecompressionContext(resetValue, getNextValue)
var enlargeIn = 4
var numBits = 3
var entry: String
var c: Char? = null
for (i in 0 until 3) {
dictionary.add(i.toString())
}
data.loopUntilMaxPower()
when (data.bits) {
0 -> {
data.bits = 0
data.maxPower = 1 shl 8
data.power = 1
data.loopUntilMaxPower()
c = data.bits.toChar()
}
1 -> {
data.bits = 0
data.maxPower = 1 shl 16
data.power = 1
data.loopUntilMaxPower()
c = data.bits.toChar()
}
2 -> throw IllegalArgumentException("Invalid LZString")
}
if (c == null) {
throw Exception("No character found")
}
dictionary.add(c.toString())
var w = c.toString()
result.append(c.toString())
while (true) {
if (data.index > length) {
throw IllegalArgumentException("Invalid LZString")
}
data.bits = 0
data.maxPower = 1 shl numBits
data.power = 1
data.loopUntilMaxPower()
var cc = data.bits
when (data.bits) {
0 -> {
data.bits = 0
data.maxPower = 1 shl 8
data.power = 1
data.loopUntilMaxPower()
dictionary.add(data.bits.toChar().toString())
cc = dictionary.size - 1
enlargeIn--
}
1 -> {
data.bits = 0
data.maxPower = 1 shl 16
data.power = 1
data.loopUntilMaxPower()
dictionary.add(data.bits.toChar().toString())
cc = dictionary.size - 1
enlargeIn--
}
2 -> return result.toString()
}
if (enlargeIn == 0) {
enlargeIn = 1 shl numBits
numBits++
}
entry = if (cc < dictionary.size) {
dictionary[cc]
} else {
if (cc == dictionary.size) {
w + w[0]
} else {
throw Exception("Invalid LZString")
}
}
result.append(entry)
dictionary.add(w + entry[0])
enlargeIn--
w = entry
if (enlargeIn == 0) {
enlargeIn = 1 shl numBits
numBits++
}
}
}
private const val base64KeyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
fun compressToBase64(input: String): String =
compress(input, 6) { base64KeyStr[it].toString() }.let {
return when (it.length % 4) {
0 -> it
1 -> "$it==="
2 -> "$it=="
3 -> "$it="
else -> throw IllegalStateException("Modulo of 4 should not exceed 3.")
}
}
fun decompressFromBase64(input: String): String =
decompress(input.length, 32) {
base64KeyStr.indexOf(input[it])
}
}
private data class DecompressionContext(
val resetValue: Int,
val getNextValue: getNextValueFn,
var value: Int = getNextValue(0),
var position: Int = resetValue,
var index: Int = 1,
var bits: Int = 0,
var maxPower: Int = 1 shl 2,
var power: Int = 1,
) {
fun loopUntilMaxPower() {
while (power != maxPower) {
val resb = value and position
position = position shr 1
if (position == 0) {
position = resetValue
value = getNextValue(index++)
}
bits = bits or ((if (resb > 0) 1 else 0) * power)
power = power shl 1
}
}
}
private data class CompressionContext(
val uncompressedLength: Int,
val bitsPerChar: Int,
val getCharFromInt: getCharFromIntFn,
var value: Int = 0,
val dictionary: MutableMap<String, Int> = HashMap(),
val dictionaryToCreate: MutableMap<String, Boolean> = HashMap(),
var c: String = "",
var wc: String = "",
var w: String = "",
var enlargeIn: Int = 2, // Compensate for the first entry which should not count
var dictSize: Int = 3,
var numBits: Int = 2,
val data: StringBuilder = StringBuilder(uncompressedLength / 3),
var dataVal: Int = 0,
var dataPosition: Int = 0,
) {
fun appendDataOrAdvancePosition() {
if (dataPosition == bitsPerChar - 1) {
dataPosition = 0
data.append(getCharFromInt(dataVal))
dataVal = 0
} else {
dataPosition++
}
}
fun decrementEnlargeIn() {
enlargeIn--
if (enlargeIn == 0) {
enlargeIn = 1 shl numBits
numBits++
}
}
// Output the code for W.
fun outputCodeForW() {
if (dictionaryToCreate.containsKey(w)) {
if (w[0].code < 256) {
for (i in 0 until numBits) {
dataVal = dataVal shl 1
appendDataOrAdvancePosition()
}
value = w[0].code
for (i in 0 until 8) {
dataVal = (dataVal shl 1) or (value and 1)
appendDataOrAdvancePosition()
value = value shr 1
}
} else {
value = 1
for (i in 0 until numBits) {
dataVal = (dataVal shl 1) or value
appendDataOrAdvancePosition()
value = 0
}
value = w[0].code
for (i in 0 until 16) {
dataVal = (dataVal shl 1) or (value and 1)
appendDataOrAdvancePosition()
value = value shr 1
}
}
decrementEnlargeIn()
dictionaryToCreate.remove(w)
} else {
value = dictionary[w]!!
for (i in 0 until numBits) {
dataVal = (dataVal shl 1) or (value and 1)
appendDataOrAdvancePosition()
value = value shr 1
}
}
}
}

View File

@@ -1,23 +1,3 @@
plugins { plugins {
id("com.android.library") id("lib-android")
kotlin("android")
id("kotlinx-serialization")
}
android {
compileSdk = AndroidConfig.compileSdk
defaultConfig {
minSdk = AndroidConfig.minSdk
}
namespace = "eu.kanade.tachiyomi.lib.randomua"
}
repositories {
mavenCentral()
}
dependencies {
compileOnly(libs.bundles.common)
} }

View File

@@ -85,7 +85,7 @@ private class RandomUserAgentInterceptor(
} }
companion object { companion object {
private const val UA_DB_URL = "https://tachiyomiorg.github.io/user-agents/user-agents.json" private const val UA_DB_URL = "https://keiyoushi.github.io/user-agents/user-agents.json"
} }
} }

View File

@@ -8,9 +8,9 @@ import androidx.preference.PreferenceScreen
import okhttp3.Headers import okhttp3.Headers
/** /**
* Helper function to return UserAgentType based on SharedPreference value * Helper function to return UserAgentType based on SharedPreference value
*/ */
fun SharedPreferences.getPrefUAType(): UserAgentType { fun SharedPreferences.getPrefUAType(): UserAgentType {
return when (getString(PREF_KEY_RANDOM_UA, "off")) { return when (getString(PREF_KEY_RANDOM_UA, "off")) {
"mobile" -> UserAgentType.MOBILE "mobile" -> UserAgentType.MOBILE
@@ -34,7 +34,9 @@ fun SharedPreferences.getPrefCustomUA(): String? {
fun addRandomUAPreferenceToScreen( fun addRandomUAPreferenceToScreen(
screen: PreferenceScreen, screen: PreferenceScreen,
) { ) {
ListPreference(screen.context).apply { val context = screen.context
ListPreference(context).apply {
key = PREF_KEY_RANDOM_UA key = PREF_KEY_RANDOM_UA
title = TITLE_RANDOM_UA title = TITLE_RANDOM_UA
entries = RANDOM_UA_ENTRIES entries = RANDOM_UA_ENTRIES
@@ -43,28 +45,27 @@ fun addRandomUAPreferenceToScreen(
setDefaultValue("off") setDefaultValue("off")
}.also(screen::addPreference) }.also(screen::addPreference)
EditTextPreference(screen.context).apply { EditTextPreference(context).apply {
key = PREF_KEY_CUSTOM_UA key = PREF_KEY_CUSTOM_UA
title = TITLE_CUSTOM_UA title = TITLE_CUSTOM_UA
summary = CUSTOM_UA_SUMMARY summary = CUSTOM_UA_SUMMARY
setOnPreferenceChangeListener { _, newValue -> setOnPreferenceChangeListener { _, newValue ->
try { try {
Headers.Builder().add("User-Agent", newValue as String).build() Headers.headersOf("User-Agent", newValue as String)
true true
} catch (e: IllegalArgumentException) { } catch (e: IllegalArgumentException) {
Toast.makeText(screen.context, "User Agent invalid${e.message}", Toast.LENGTH_LONG).show() Toast.makeText(context, "Invalid user agent string: ${e.message}", Toast.LENGTH_LONG).show()
false false
} }
} }
}.also(screen::addPreference) }.also(screen::addPreference)
} }
const val TITLE_RANDOM_UA = "Random User-Agent (Requires Restart)" const val TITLE_RANDOM_UA = "Random user agent string (requires restart)"
const val PREF_KEY_RANDOM_UA = "pref_key_random_ua_" const val PREF_KEY_RANDOM_UA = "pref_key_random_ua_"
val RANDOM_UA_ENTRIES = arrayOf("OFF", "Desktop", "Mobile") val RANDOM_UA_ENTRIES = arrayOf("OFF", "Desktop", "Mobile")
val RANDOM_UA_VALUES = arrayOf("off", "desktop", "mobile") val RANDOM_UA_VALUES = arrayOf("off", "desktop", "mobile")
const val TITLE_CUSTOM_UA = "Custom User-Agent (Requires Restart)" const val TITLE_CUSTOM_UA = "Custom user agent string (requires restart)"
const val PREF_KEY_CUSTOM_UA = "pref_key_custom_ua_" const val PREF_KEY_CUSTOM_UA = "pref_key_custom_ua_"
const val CUSTOM_UA_SUMMARY = "Leave blank to use application default user-agent (IGNORED if Random User-Agent is enabled)" const val CUSTOM_UA_SUMMARY = "Leave blank to use the default user agent string (ignored if random user agent string is enabled)"

View File

@@ -0,0 +1,7 @@
plugins {
id("lib-android")
}
dependencies {
implementation(project(":lib:textinterceptor"))
}

View File

@@ -0,0 +1,70 @@
package eu.kanade.tachiyomi.lib.speedbinb
private const val URLSAFE_BASE64_LOOKUP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
internal fun determineKeyPair(src: String?, ptbl: List<String>, ctbl: List<String>): Pair<String, String> {
val i = mutableListOf(0, 0)
if (src != null) {
val filename = src.substringAfterLast("/")
for (e in filename.indices) {
i[e % 2] = i[e % 2] + filename[e].code
}
i[0] = i[0] % 8
i[1] = i[1] % 8
}
return Pair(ptbl[i[0]], ctbl[i[1]])
}
internal fun decodeScrambleTable(cid: String, sharedKey: String, table: String): String {
val r = "$cid:$sharedKey"
var e = r.toCharArray()
.map { it.code }
.reduceIndexed { index, acc, i -> acc + (i shl index % 16) } and 2147483647
if (e == 0) {
e = 0x12345678
}
return buildString(table.length) {
for (s in table.indices) {
e = e ushr 1 xor (1210056708 and -(1 and e))
append(((table[s].code - 32 + e) % 94 + 32).toChar())
}
}
}
internal fun generateSharedKey(cid: String): String {
val randomChars = randomChars(16)
val cidRepeatCount = (16 + cid.length - 1) / cid.length
val unk1 = buildString(cid.length * cidRepeatCount) {
for (i in 0 until cidRepeatCount) {
append(cid)
}
}
val unk2 = unk1.substring(0, 16)
val unk3 = unk1.substring(unk1.length - 16, unk1.length)
var s = 0
var h = 0
var u = 0
return buildString(randomChars.length * 2) {
for (i in randomChars.indices) {
s = s xor randomChars[i].code
h = h xor unk2[i].code
u = u xor unk3[i].code
append(randomChars[i])
append(URLSAFE_BASE64_LOOKUP[(s + h + u) and 63])
}
}
}
private fun randomChars(length: Int) = buildString(length) {
for (i in 0 until length) {
append(URLSAFE_BASE64_LOOKUP.random())
}
}

View File

@@ -0,0 +1,102 @@
package eu.kanade.tachiyomi.lib.speedbinb
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
private val COORD_REGEX = Regex("""^i:(\d+),(\d+)\+(\d+),(\d+)>(\d+),(\d+)$""")
@Serializable
class BibContentInfo(
val result: Int,
val items: List<BibContentItem>,
)
@Serializable
class BibContentItem(
@SerialName("ContentID") val contentId: String,
@SerialName("ContentsServer") val contentServer: String,
@SerialName("ServerType") val serverType: Int,
val stbl: String,
val ttbl: String,
val ptbl: String,
val ctbl: String,
@SerialName("p") val requestToken: String? = null,
@SerialName("ViewMode") val viewMode: Int,
@SerialName("ContentDate") val contentDate: String? = null,
@SerialName("ShopURL") val shopUrl: String? = null,
) {
fun getSbcUrl(readerUrl: HttpUrl, cid: String) =
contentServer.toHttpUrl().newBuilder().apply {
when (serverType) {
ServerType.DIRECT -> addPathSegment("content.js")
ServerType.REST -> addPathSegment("content")
ServerType.SBC -> {
addPathSegment("sbcGetCntnt.php")
setQueryParameter("cid", cid)
requestToken?.let { setQueryParameter("p", it) }
setQueryParameter("q", "1")
setQueryParameter("vm", viewMode.toString())
setQueryParameter("dmytime", contentDate ?: System.currentTimeMillis().toString())
copyKeyParametersFrom(readerUrl)
}
else -> throw UnsupportedOperationException("Unsupported ServerType value $serverType")
}
}.toString()
}
object ServerType {
const val SBC = 0
const val DIRECT = 1
const val REST = 2
}
object ViewMode {
const val COMMERCIAL = 1
const val NON_MEMBER_TRIAL = 2
const val MEMBER_TRIAL = 3
}
@Serializable
class PtImg(
@SerialName("ptimg-version") val ptImgVersion: Int,
val resources: PtImgResources,
val views: List<PtImgViews>,
) {
val translations by lazy {
views[0].coords.map { coord ->
val v = COORD_REGEX.matchEntire(coord)!!.groupValues.drop(1).map { it.toInt() }
PtImgTranslation(v[0], v[1], v[2], v[3], v[4], v[5])
}
}
}
@Serializable
class PtImgResources(
val i: PtImgImage,
)
@Serializable
class PtImgImage(
val src: String,
val width: Int,
val height: Int,
)
@Serializable
class PtImgViews(
val width: Int,
val height: Int,
val coords: Array<String>,
)
class PtImgTranslation(val xsrc: Int, val ysrc: Int, val width: Int, val height: Int, val xdest: Int, val ydest: Int)
@Serializable
class SBCContent(
@SerialName("SBCVersion") val sbcVersion: String,
val result: Int,
val ttx: String,
@SerialName("ImageClass") val imageClass: String? = null,
)

View File

@@ -0,0 +1,85 @@
package eu.kanade.tachiyomi.lib.speedbinb
import android.graphics.BitmapFactory
import eu.kanade.tachiyomi.lib.speedbinb.descrambler.PtBinbDescramblerA
import eu.kanade.tachiyomi.lib.speedbinb.descrambler.PtBinbDescramblerF
import eu.kanade.tachiyomi.lib.speedbinb.descrambler.PtImgDescrambler
import eu.kanade.tachiyomi.lib.textinterceptor.TextInterceptor
import eu.kanade.tachiyomi.lib.textinterceptor.TextInterceptorHelper
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.io.IOException
class SpeedBinbInterceptor(private val json: Json) : Interceptor {
private val textInterceptor by lazy { TextInterceptor() }
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val host = request.url.host
val filename = request.url.pathSegments.last()
val fragment = request.url.fragment
return when {
host == TextInterceptorHelper.HOST -> textInterceptor.intercept(chain)
filename.endsWith(".ptimg.json") -> interceptPtImg(chain, request)
fragment == null -> chain.proceed(request)
fragment.startsWith("ptbinb,") -> interceptPtBinB(chain, request)
else -> chain.proceed(request)
}
}
private fun interceptPtImg(chain: Interceptor.Chain, request: Request): Response {
val response = chain.proceed(request)
val metadata = json.decodeFromString<PtImg>(response.body.string())
val imageUrl = request.url.newBuilder()
.setPathSegment(request.url.pathSize - 1, metadata.resources.i.src)
.build()
val imageResponse = chain.proceed(
request.newBuilder().url(imageUrl).build(),
)
if (metadata.translations.isEmpty()) {
return imageResponse
}
val image = BitmapFactory.decodeStream(imageResponse.body.byteStream())
val descrambler = PtImgDescrambler(metadata)
return imageResponse.newBuilder()
.body(descrambler.descrambleImage(image)!!.toResponseBody(JPEG_MEDIA_TYPE))
.build()
}
private fun interceptPtBinB(chain: Interceptor.Chain, request: Request): Response {
val response = chain.proceed(request)
val fragment = request.url.fragment!!
val (s, u) = fragment.removePrefix("ptbinb,").split(",", limit = 2)
if (s.isEmpty() && u.isEmpty()) {
return response
}
val imageData = response.body.bytes()
val image = BitmapFactory.decodeByteArray(imageData, 0, imageData.size)
val descrambler = if (s[0] == '=' && u[0] == '=') {
PtBinbDescramblerF(s, u, image.width, image.height)
} else if (NUMERIC_CHARACTERS.contains(s[0]) && NUMERIC_CHARACTERS.contains(u[0])) {
PtBinbDescramblerA(s, u, image.width, image.height)
} else {
throw IOException("Cannot select descrambler for key pair s=$s, u=$u")
}
val descrambled = descrambler.descrambleImage(image) ?: imageData
return response.newBuilder()
.body(descrambled.toResponseBody(JPEG_MEDIA_TYPE))
.build()
}
}
private const val NUMERIC_CHARACTERS = "0123456789"
private val JPEG_MEDIA_TYPE = "image/jpeg".toMediaType()

View File

@@ -0,0 +1,197 @@
package eu.kanade.tachiyomi.lib.speedbinb
import eu.kanade.tachiyomi.lib.textinterceptor.TextInterceptorHelper
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.util.asJsoup
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Response
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
/**
* SpeedBinb is a reader for various Japanese manga sites.
*
* Versions (`SpeedBinb.VERSION` in DevTools console):
* - Minimum version tested: `1.6650.0001`
* - Maximum version tested: `1.6930.1101`
*
* These versions are only for reference purposes, and does not reflect the actual range
* of versions this class can scrape.
*/
class SpeedBinbReader(
private val client: OkHttpClient,
private val headers: Headers,
private val json: Json,
private val highQualityMode: Boolean = false,
) {
private val isInterceptorAdded by lazy {
client.interceptors.filterIsInstance<SpeedBinbInterceptor>().isNotEmpty()
}
fun pageListParse(response: Response): List<Page> =
pageListParse(response.asJsoup())
fun pageListParse(document: Document): List<Page> {
// We throw here instead of in the `init {}` block because extensions that fail
// to load just mysteriously disappears from the extension list, no errors no nothing.
if (!isInterceptorAdded) {
throw Exception("SpeedBinbInterceptor was not added to the client.")
}
val readerUrl = document.location().toHttpUrl()
val content = document.selectFirst("#content")!!
if (!content.hasAttr("data-ptbinb")) {
return content.select("[data-ptimg]").mapIndexed { i, it ->
Page(i, imageUrl = it.absUrl("data-ptimg"))
}
}
val cid = content.attr("data-ptbinb-cid")
.ifEmpty { readerUrl.queryParameter("cid") }
?: throw Exception("Could not find chapter ID")
val sharedKey = generateSharedKey(cid)
val contentInfoUrl = content.absUrl("data-ptbinb").toHttpUrl().newBuilder()
.copyKeyParametersFrom(readerUrl)
.setQueryParameter("cid", cid)
.setQueryParameter("k", sharedKey)
.setQueryParameter("dmytime", System.currentTimeMillis().toString())
.build()
val contentInfo = client.newCall(GET(contentInfoUrl, headers)).execute().parseAs<BibContentInfo>()
if (contentInfo.result != 1) {
throw Exception("Failed to execute bibGetCntntInfo API.")
}
if (contentInfo.items.isEmpty()) {
throw Exception("There is no item.")
}
val contentItem = contentInfo.items[0]
val ctbl = json.decodeFromString<List<String>>(decodeScrambleTable(cid, sharedKey, contentItem.ctbl))
val ptbl = json.decodeFromString<List<String>>(decodeScrambleTable(cid, sharedKey, contentItem.ptbl))
val sbcUrl = contentItem.getSbcUrl(readerUrl, cid)
val sbcData = client.newCall(GET(sbcUrl, headers)).execute().body.string().let {
val raw = if (contentItem.serverType == ServerType.DIRECT) {
it.substringAfter("DataGet_Content(").substringBeforeLast(")")
} else {
it
}
json.decodeFromString<SBCContent>(raw)
}
if (sbcData.result != 1) {
throw Exception("Failed to fetch content")
}
val isSingleQuality = sbcData.imageClass == "singlequality"
val ttx = Jsoup.parseBodyFragment(sbcData.ttx, document.location())
val pageBaseUrl = when (contentItem.serverType) {
ServerType.DIRECT, ServerType.REST -> contentItem.contentServer
ServerType.SBC -> sbcUrl.replaceFirst("/sbcGetCntnt.php", "/sbcGetImg.php")
else -> throw UnsupportedOperationException("Unsupported ServerType value ${contentItem.serverType}")
}.toHttpUrl()
val pages = ttx.select("t-case:first-of-type t-img").mapIndexed { i, it ->
val src = it.attr("src")
val keyPair = determineKeyPair(src, ptbl, ctbl)
val fragment = "ptbinb,${keyPair.first},${keyPair.second}"
val imageUrl = pageBaseUrl.newBuilder()
.buildImageUrl(
readerUrl,
src,
contentItem,
isSingleQuality,
highQualityMode,
)
.fragment(fragment)
.toString()
Page(i, imageUrl = imageUrl)
}.toMutableList()
// This is probably the silliest use of TextInterceptor ever.
//
// If chapter purchases are enabled, and there's a link to purchase the current chapter,
// we add in the purchase URL as the last page.
val buyIconPosition = document.selectFirst("script:containsData(Config.LoginBuyIconPosition)")
?.data()
?.substringAfter("Config.LoginBuyIconPosition=")
?.substringBefore(";")
?.trim()
?: "-1"
val enableBuying = buyIconPosition != "-1"
if (enableBuying && contentItem.viewMode != ViewMode.COMMERCIAL && !contentItem.shopUrl.isNullOrEmpty()) {
pages.add(
Page(pages.size, imageUrl = TextInterceptorHelper.createUrl("", "購入: ${contentItem.shopUrl}")),
)
}
return pages
}
private inline fun <reified T> Response.parseAs(): T =
json.decodeFromString(body.string())
}
private fun HttpUrl.Builder.buildImageUrl(
readerUrl: HttpUrl,
src: String,
contentItem: BibContentItem,
isSingleQuality: Boolean,
highQualityMode: Boolean,
) = apply {
when (contentItem.serverType) {
ServerType.DIRECT -> {
val filename = when {
isSingleQuality -> "M.jpg"
highQualityMode -> "M_H.jpg"
else -> "M_L.jpg"
}
addPathSegments(src)
addPathSegment(filename)
contentItem.contentDate?.let { setQueryParameter("dmytime", it) }
}
ServerType.REST -> {
addPathSegment("img")
addPathSegments(src)
if (!isSingleQuality && !highQualityMode) {
setQueryParameter("q", "1")
}
contentItem.contentDate?.let { setQueryParameter("dmytime", it) }
copyKeyParametersFrom(readerUrl)
}
ServerType.SBC -> {
setQueryParameter("src", src)
contentItem.requestToken?.let { setQueryParameter("p", it) }
if (!isSingleQuality) {
setQueryParameter("q", if (highQualityMode) "0" else "1")
}
setQueryParameter("vm", contentItem.viewMode.toString())
contentItem.contentDate?.let { setQueryParameter("dmytime", it) }
copyKeyParametersFrom(readerUrl)
}
else -> throw UnsupportedOperationException("Unsupported ServerType value ${contentItem.serverType}")
}
}
internal fun HttpUrl.Builder.copyKeyParametersFrom(url: HttpUrl): HttpUrl.Builder {
for (i in 0..9) {
url.queryParameter("u$i")?.let {
setQueryParameter("u$i", it)
}
}
return this
}

View File

@@ -0,0 +1,301 @@
package eu.kanade.tachiyomi.lib.speedbinb.descrambler
import eu.kanade.tachiyomi.lib.speedbinb.PtImgTranslation
private val PTBINBF_REGEX = Regex("""^=([0-9]+)-([0-9]+)([-+])([0-9]+)-([-_0-9A-Za-z]+)$""")
private const val PTBINBF_CHAR_LOOKUP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
private const val PTBINBA_CHAR_LOOKUP = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"
abstract class PtBinbDescrambler(
val s: String,
val u: String,
val width: Int,
val height: Int,
) : SpeedBinbDescrambler()
class PtBinbDescramblerF(s: String, u: String, width: Int, height: Int) : PtBinbDescrambler(s, u, width, height) {
private var widthPieces: Int = 0
private var heightPieces: Int = 0
private var piecePadding: Int = 0
private lateinit var hDstPosLookup: List<Int>
private lateinit var wDstPosLookup: List<Int>
private lateinit var hPosLookup: List<Int>
private lateinit var wPosLookup: List<Int>
private var pieceDest: List<Int>? = null
init {
// Kotlin init blocks don't allow early returns...
init()
}
private fun init() {
val srcData = PTBINBF_REGEX.matchEntire(s)?.groupValues
val dstData = PTBINBF_REGEX.matchEntire(u)?.groupValues
if (
dstData == null ||
srcData == null ||
dstData[1] != srcData[1] ||
dstData[2] != srcData[2] ||
dstData[4] != srcData[4] ||
dstData[3] != "+" ||
srcData[3] != "-"
) {
return
}
widthPieces = dstData[1].toInt()
heightPieces = dstData[2].toInt()
piecePadding = dstData[4].toInt()
if (widthPieces < 8 || heightPieces < 8 || widthPieces * heightPieces < 64) {
return
}
val e = widthPieces + heightPieces + widthPieces * heightPieces
if (dstData[5].length != e || srcData[5].length != e) {
return
}
val srcTnp = decodePieceData(srcData[5])
val dstTnp = decodePieceData(dstData[5])
hDstPosLookup = dstTnp.hPos
wDstPosLookup = dstTnp.wPos
hPosLookup = srcTnp.hPos
wPosLookup = srcTnp.wPos
pieceDest = buildList(widthPieces * heightPieces) {
for (i in 0 until widthPieces * heightPieces) {
add(dstTnp.pieces[srcTnp.pieces[i]])
}
}
}
override fun isScrambled() =
pieceDest != null
override fun canDescramble(): Boolean {
val i = 2 * widthPieces * piecePadding
val n = 2 * heightPieces * piecePadding
return width >= 64 + i && height >= 64 + n && width * height >= (320 + i) * (320 + n)
}
override fun getCanvasDimensions(): Pair<Int, Int> {
return if (canDescramble()) {
Pair(
width - 2 * widthPieces * piecePadding,
height - 2 * heightPieces * piecePadding,
)
} else {
Pair(width, height)
}
}
override fun getDescrambleCoords(): List<PtImgTranslation> {
val pieceDest = this.pieceDest
if (!isScrambled() || pieceDest == null) {
return emptyList()
}
if (!canDescramble()) {
return listOf(
PtImgTranslation(0, 0, width, height, 0, 0),
)
}
val canvasWidth = width - 2 * widthPieces * piecePadding
val canvasHeight = height - 2 * heightPieces * piecePadding
val pieceWidth = (canvasWidth + widthPieces - 1).div(widthPieces)
val remainderWidth = canvasWidth - (widthPieces - 1) * pieceWidth
val pieceHeight = (canvasHeight + heightPieces - 1).div(heightPieces)
val remainderHeight = canvasHeight - (heightPieces - 1) * pieceHeight
return buildList(widthPieces * heightPieces) {
for (o in 0 until widthPieces * heightPieces) {
val hPos = o % widthPieces
val wPos = o.div(widthPieces)
val hDstPos = pieceDest[o] % widthPieces
val wDstPos = pieceDest[o].div(widthPieces)
add(
PtImgTranslation(
xsrc = piecePadding + hPos * (pieceWidth + 2 * piecePadding) + if (hPosLookup[wPos] < hPos) remainderWidth - pieceWidth else 0,
ysrc = piecePadding + wPos * (pieceHeight + 2 * piecePadding) + if (wPosLookup[hPos] < wPos) remainderHeight - pieceHeight else 0,
width = if (hPosLookup[wPos] == hPos) remainderWidth else pieceWidth,
height = if (wPosLookup[hPos] == wPos) remainderHeight else pieceHeight,
xdest = hDstPos * pieceWidth + if (hDstPosLookup[wDstPos] < hDstPos) remainderWidth - pieceWidth else 0,
ydest = wDstPos * pieceHeight + if (wDstPosLookup[hDstPos] < wDstPos) remainderHeight - pieceHeight else 0,
),
)
}
}
}
private fun decodePieceData(key: String): TNP {
val wPos = buildList(widthPieces) {
for (i in 0 until widthPieces) {
add(PTBINBF_CHAR_LOOKUP.indexOf(key[i]))
}
}
val hPos = buildList(heightPieces) {
for (i in 0 until heightPieces) {
add(PTBINBF_CHAR_LOOKUP.indexOf(key[widthPieces + i]))
}
}
val pieces = buildList(widthPieces * heightPieces) {
for (i in 0 until widthPieces * heightPieces) {
add(PTBINBF_CHAR_LOOKUP.indexOf(key[widthPieces + heightPieces + i]))
}
}
return TNP(wPos, hPos, pieces)
}
private class TNP(val wPos: List<Int>, val hPos: List<Int>, val pieces: List<Int>)
}
class PtBinbDescramblerA(s: String, u: String, width: Int, height: Int) : PtBinbDescrambler(s, u, width, height) {
private var srcPieces: PieceCollection? = null
private var dstPieces: PieceCollection? = null
init {
val srcPieces = calculatePieces(u)
val dstPieces = calculatePieces(s)
if (
srcPieces != null &&
dstPieces != null &&
srcPieces.ndx == dstPieces.ndx &&
srcPieces.ndy == dstPieces.ndy
) {
this.srcPieces = srcPieces
this.dstPieces = dstPieces
}
}
override fun isScrambled() =
srcPieces != null && dstPieces != null
override fun canDescramble(): Boolean =
width >= 64 && height >= 64 && width * height >= 102400
override fun getCanvasDimensions(): Pair<Int, Int> =
Pair(width, height)
override fun getDescrambleCoords(): List<PtImgTranslation> {
if (!isScrambled()) {
return emptyList()
}
if (!canDescramble()) {
return listOf(
PtImgTranslation(0, 0, width, height, 0, 0),
)
}
val srcPieces = this.srcPieces!!
val dstPieces = this.dstPieces!!
return buildList(srcPieces.piece.size + 2) {
val n = width - width % 8
val pieceWidth = (n - 1).div(7) - (n - 1).div(7) % 8
val e = n - 7 * pieceWidth
val s = height - height % 8
val pieceHeight = (s - 1).div(7) - (s - 1).div(7) % 8
val u = s - 7 * pieceHeight
for (i in srcPieces.piece.indices) {
val src = srcPieces.piece[i]
val dst = dstPieces.piece[i]
add(
PtImgTranslation(
xsrc = src.x.div(2) * pieceWidth + src.x % 2 * e,
ysrc = src.y.div(2) * pieceHeight + src.y % 2 * u,
width = src.w.div(2) * pieceWidth + src.w % 2 * e,
height = src.h.div(2) * pieceHeight + src.h % 2 * u,
xdest = dst.x.div(2) * pieceWidth + dst.x % 2 * e,
ydest = dst.y.div(2) * pieceHeight + dst.y % 2 * u,
),
)
}
val l = pieceWidth * (srcPieces.ndx - 1) + e
val v = pieceHeight * (srcPieces.ndy - 1) + u
if (l < width) {
add(
PtImgTranslation(l, 0, width - l, v, l, 0),
)
}
if (v < height) {
add(
PtImgTranslation(0, v, width, height - v, 0, v),
)
}
}
}
private fun calculatePieces(key: String): PieceCollection? {
if (key.isEmpty()) {
return null
}
val parts = key.split("-")
if (parts.size != 3) {
return null
}
val ndx = parts[0].toInt()
val ndy = parts[1].toInt()
val e = parts[2]
if (ndx * ndy * 2 != e.length) {
return null
}
val pieces = buildList(ndx * ndy) {
val a = (ndx - 1) * (ndy - 1) - 1
val f = ndx - 1 + a
val c = ndy - 1 + f
val l = 1 + c
var w = 0
var h = 0
for (d in 0 until ndx * ndy) {
val x = PTBINBA_CHAR_LOOKUP.indexOf(e[2 * d])
val y = PTBINBA_CHAR_LOOKUP.indexOf(e[2 * d + 1])
if (d <= a) {
h = 2
w = 2
} else if (d <= f) {
h = 1
w = 2
} else if (d <= c) {
h = 2
w = 1
} else if (d <= l) {
h = 1
w = 1
}
add(Piece(x, y, w, h))
}
}
return PieceCollection(ndx, ndy, pieces)
}
private class Piece(val x: Int, val y: Int, val w: Int, val h: Int)
private class PieceCollection(val ndx: Int, val ndy: Int, val piece: List<Piece>)
}

View File

@@ -0,0 +1,13 @@
package eu.kanade.tachiyomi.lib.speedbinb.descrambler
import eu.kanade.tachiyomi.lib.speedbinb.PtImg
class PtImgDescrambler(private val metadata: PtImg) : SpeedBinbDescrambler() {
override fun isScrambled() = metadata.translations.isNotEmpty()
override fun canDescramble() = metadata.translations.isNotEmpty()
override fun getCanvasDimensions() = Pair(metadata.views[0].width, metadata.views[0].height)
override fun getDescrambleCoords() = metadata.translations
}

View File

@@ -0,0 +1,37 @@
package eu.kanade.tachiyomi.lib.speedbinb.descrambler
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Rect
import eu.kanade.tachiyomi.lib.speedbinb.PtImgTranslation
import java.io.ByteArrayOutputStream
abstract class SpeedBinbDescrambler {
abstract fun isScrambled(): Boolean
abstract fun canDescramble(): Boolean
abstract fun getCanvasDimensions(): Pair<Int, Int>
abstract fun getDescrambleCoords(): List<PtImgTranslation>
open fun descrambleImage(image: Bitmap): ByteArray? {
if (!isScrambled()) {
return null
}
val (width, height) = getCanvasDimensions()
val result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(result)
getDescrambleCoords().forEach {
val src = Rect(it.xsrc, it.ysrc, it.xsrc + it.width, it.ysrc + it.height)
val dst = Rect(it.xdest, it.ydest, it.xdest + it.width, it.ydest + it.height)
canvas.drawBitmap(image, src, dst, null)
}
return ByteArrayOutputStream()
.also {
result.compress(Bitmap.CompressFormat.JPEG, 90, it)
}
.toByteArray()
}
}

View File

@@ -1,22 +1,3 @@
plugins { plugins {
id("com.android.library") id("lib-android")
kotlin("android")
}
android {
compileSdk = AndroidConfig.compileSdk
defaultConfig {
minSdk = AndroidConfig.minSdk
}
namespace = "eu.kanade.tachiyomi.lib.synchrony"
}
repositories {
mavenCentral()
}
dependencies {
compileOnly(libs.bundles.common)
} }

File diff suppressed because one or more lines are too long

View File

@@ -39,4 +39,4 @@ object Deobfuscator {
} }
// Update this when the script is updated! // Update this when the script is updated!
private const val SCRIPT_NAME = "synchrony-v2.4.2.1.js" private const val SCRIPT_NAME = "synchrony-v2.4.5.1.js"

View File

@@ -1,23 +1,3 @@
plugins { plugins {
id("com.android.library") id("lib-android")
kotlin("android")
}
android {
compileSdk = AndroidConfig.compileSdk
defaultConfig {
minSdk = AndroidConfig.minSdk
}
namespace = "eu.kanade.tachiyomi.lib.textinterceptor"
}
repositories {
mavenCentral()
}
dependencies {
compileOnly(libs.kotlin.stdlib)
compileOnly(libs.okhttp)
} }

View File

@@ -18,69 +18,73 @@ import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody import okhttp3.ResponseBody.Companion.toResponseBody
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
// Designer values:
private const val WIDTH: Int = 1000
private const val X_PADDING: Float = 50f
private const val Y_PADDING: Float = 25f
private const val HEADING_FONT_SIZE: Float = 36f
private const val BODY_FONT_SIZE: Float = 30f
private const val SPACING_MULT: Float = 1.1f
private const val SPACING_ADD: Float = 2f
// No need to touch this one:
private const val HOST = TextInterceptorHelper.HOST
class TextInterceptor : Interceptor { class TextInterceptor : Interceptor {
// With help from: // With help from:
// https://github.com/tachiyomiorg/tachiyomi-extensions/pull/13304#issuecomment-1234532897 // https://github.com/tachiyomiorg/tachiyomi-extensions/pull/13304#issuecomment-1234532897
// https://medium.com/over-engineering/drawing-multiline-text-to-canvas-on-android-9b98f0bfa16a // https://medium.com/over-engineering/drawing-multiline-text-to-canvas-on-android-9b98f0bfa16a
companion object {
// Designer values:
private const val WIDTH: Int = 1000
private const val X_PADDING: Float = 50f
private const val Y_PADDING: Float = 25f
private const val HEADING_FONT_SIZE: Float = 36f
private const val BODY_FONT_SIZE: Float = 30f
private const val SPACING_MULT: Float = 1.1f
private const val SPACING_ADD: Float = 2f
// No need to touch this one:
private const val HOST = TextInterceptorHelper.HOST
}
override fun intercept(chain: Interceptor.Chain): Response { override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request() val request = chain.request()
val url = request.url val url = request.url
if (url.host != HOST) return chain.proceed(request) if (url.host != HOST) return chain.proceed(request)
val creator = textFixer("Author's Notes from ${url.pathSegments[0]}") val heading = url.pathSegments[0].takeIf { it.isNotEmpty() }?.let {
val story = textFixer(url.pathSegments[1]) val title = textFixer(url.pathSegments[0])
// Heading // Heading
val paintHeading = TextPaint().apply { val paintHeading = TextPaint().apply {
color = Color.BLACK color = Color.BLACK
textSize = HEADING_FONT_SIZE textSize = HEADING_FONT_SIZE
typeface = Typeface.DEFAULT_BOLD typeface = Typeface.DEFAULT_BOLD
isAntiAlias = true isAntiAlias = true
}
@Suppress("DEPRECATION")
StaticLayout(
title, paintHeading, (WIDTH - 2 * X_PADDING).toInt(),
Layout.Alignment.ALIGN_NORMAL, SPACING_MULT, SPACING_ADD, true
)
} }
@Suppress("DEPRECATION") val body = url.pathSegments[1].takeIf { it.isNotEmpty() }?.let {
val heading = StaticLayout( val story = textFixer(it)
creator, paintHeading, (WIDTH - 2 * X_PADDING).toInt(),
Layout.Alignment.ALIGN_NORMAL, SPACING_MULT, SPACING_ADD, true
)
// Body // Body
val paintBody = TextPaint().apply { val paintBody = TextPaint().apply {
color = Color.BLACK color = Color.BLACK
textSize = BODY_FONT_SIZE textSize = BODY_FONT_SIZE
typeface = Typeface.DEFAULT typeface = Typeface.DEFAULT
isAntiAlias = true isAntiAlias = true
}
@Suppress("DEPRECATION")
StaticLayout(
story, paintBody, (WIDTH - 2 * X_PADDING).toInt(),
Layout.Alignment.ALIGN_NORMAL, SPACING_MULT, SPACING_ADD, true
)
} }
@Suppress("DEPRECATION")
val body = StaticLayout(
story, paintBody, (WIDTH - 2 * X_PADDING).toInt(),
Layout.Alignment.ALIGN_NORMAL, SPACING_MULT, SPACING_ADD, true
)
// Image building // Image building
val imgHeight: Int = (heading.height + body.height + 2 * Y_PADDING).toInt() val headingHeight = heading?.height ?: 0
val bodyHeight = body?.height ?: 0
val imgHeight: Int = (headingHeight + bodyHeight + 2 * Y_PADDING).toInt()
val bitmap: Bitmap = Bitmap.createBitmap(WIDTH, imgHeight, Bitmap.Config.ARGB_8888) val bitmap: Bitmap = Bitmap.createBitmap(WIDTH, imgHeight, Bitmap.Config.ARGB_8888)
Canvas(bitmap).apply { Canvas(bitmap).apply {
drawColor(Color.WHITE) drawColor(Color.WHITE)
heading.draw(this, X_PADDING, Y_PADDING) heading?.draw(this, X_PADDING, Y_PADDING)
body.draw(this, X_PADDING, Y_PADDING + heading.height.toFloat()) body?.draw(this, X_PADDING, Y_PADDING + headingHeight.toFloat())
} }
// Image converting & returning // Image converting & returning
@@ -119,7 +123,7 @@ object TextInterceptorHelper {
const val HOST = "tachiyomi-lib-textinterceptor" const val HOST = "tachiyomi-lib-textinterceptor"
fun createUrl(creator: String, text: String): String { fun createUrl(title: String, text: String): String {
return "http://$HOST/" + Uri.encode(creator) + "/" + Uri.encode(text) return "http://$HOST/" + Uri.encode(title) + "/" + Uri.encode(text)
} }
} }

View File

@@ -1,12 +1,3 @@
plugins { plugins {
`java-library` id("lib-android")
kotlin("jvm")
}
repositories {
mavenCentral()
}
dependencies {
compileOnly(libs.kotlin.stdlib)
} }

View File

@@ -0,0 +1,7 @@
plugins {
id("lib-android")
}
dependencies {
compileOnly("com.github.tachiyomiorg:image-decoder:e08e9be535")
}

View File

@@ -1,96 +1,40 @@
/**
* Add or remove modules to load as needed for local development here.
*/
loadAllIndividualExtensions()
// loadIndividualExtension("all", "mangadex")
/**
* ===================================== COMMON CONFIGURATION ======================================
*/
include(":core") include(":core")
include(":utils")
// Load all modules under /lib // Load all modules under /lib
File(rootDir, "lib").eachDir { File(rootDir, "lib").eachDir { include("lib:${it.name}") }
val libName = it.name
include(":lib-$libName")
project(":lib-$libName").projectDir = File("lib/$libName")
}
if (System.getenv("CI") == null || System.getenv("CI_MODULE_GEN") == "true") { // Load all modules under /lib-multisrc
// Local development (full project build) File(rootDir, "lib-multisrc").eachDir { include("lib-multisrc:${it.name}") }
include(":multisrc")
project(":multisrc").projectDir = File("multisrc")
/**
* Add or remove modules to load as needed for local development here.
* To generate multisrc extensions first, run the `:multisrc:generateExtensions` task first.
*/
loadAllIndividualExtensions()
loadAllGeneratedMultisrcExtensions()
// loadIndividualExtension("all", "mangadex")
// loadGeneratedMultisrcExtension("en", "guya")
} else {
// Running in CI (GitHub Actions)
val isMultisrc = System.getenv("CI_MULTISRC") == "true"
val chunkSize = System.getenv("CI_CHUNK_SIZE").toInt()
val chunk = System.getenv("CI_CHUNK_NUM").toInt()
if (isMultisrc) {
include(":multisrc")
project(":multisrc").projectDir = File("multisrc")
// Loads generated extensions from multisrc
File(rootDir, "generated-src").getChunk(chunk, chunkSize)?.forEach {
val name = ":extensions:multisrc:${it.parentFile.name}:${it.name}"
println(name)
include(name)
project(name).projectDir = File("generated-src/${it.parentFile.name}/${it.name}")
}
} else {
// Loads individual extensions
File(rootDir, "src").getChunk(chunk, chunkSize)?.forEach {
val name = ":extensions:individual:${it.parentFile.name}:${it.name}"
println(name)
include(name)
project(name).projectDir = File("src/${it.parentFile.name}/${it.name}")
}
}
}
/**
* ======================================== HELPER FUNCTION ========================================
*/
fun loadAllIndividualExtensions() { fun loadAllIndividualExtensions() {
File(rootDir, "src").eachDir { dir -> File(rootDir, "src").eachDir { dir ->
dir.eachDir { subdir -> dir.eachDir { subdir ->
val name = ":extensions:individual:${dir.name}:${subdir.name}" include("src:${dir.name}:${subdir.name}")
include(name)
project(name).projectDir = File("src/${dir.name}/${subdir.name}")
}
}
}
fun loadAllGeneratedMultisrcExtensions() {
File(rootDir, "generated-src").eachDir { dir ->
dir.eachDir { subdir ->
val name = ":extensions:multisrc:${dir.name}:${subdir.name}"
include(name)
project(name).projectDir = File("generated-src/${dir.name}/${subdir.name}")
} }
} }
} }
fun loadIndividualExtension(lang: String, name: String) { fun loadIndividualExtension(lang: String, name: String) {
val projectName = ":extensions:individual:$lang:$name" include("src:${lang}:${name}")
include(projectName)
project(projectName).projectDir = File("src/${lang}/${name}")
}
fun loadGeneratedMultisrcExtension(lang: String, name: String) {
val projectName = ":extensions:multisrc:$lang:$name"
include(projectName)
project(projectName).projectDir = File("generated-src/${lang}/${name}")
}
fun File.getChunk(chunk: Int, chunkSize: Int): List<File>? {
return listFiles()
// Lang folder
?.filter { it.isDirectory }
// Extension subfolders
?.mapNotNull { dir -> dir.listFiles()?.filter { it.isDirectory } }
?.flatten()
?.sortedBy { it.name }
?.chunked(chunkSize)
?.get(chunk)
} }
fun File.eachDir(block: (File) -> Unit) { fun File.eachDir(block: (File) -> Unit) {
listFiles()?.filter { it.isDirectory }?.forEach { block(it) } val files = listFiles() ?: return
for (file in files) {
if (file.isDirectory && file.name != ".gradle" && file.name != "build") {
block(file)
}
}
} }

View File

@@ -1,2 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest /> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="eu.kanade.tachiyomi.permission.READ_SOURCES" />
<uses-permission android:name="eu.kanade.tachiyomi.permission.WRITE_SOURCES" />
<application
android:usesCleartextTraffic="true" />
</manifest>

View File

@@ -1,93 +0,0 @@
## 1.3.13
### Fixed
* Fixed 'null cannot be cast to non-null type' exception
## 1.3.12
### Features
* Migrate filters to v2
* Implemented smartFilters
* Added localization support
### Fixed
* Fixed publication status not showing
## 1.3.10
### Features
* API Change for Kavita v0.7.2
## 1.3.9
### Features
* Added pdf support
## 1.3.8
### Fix
* Fixed `Expected URL scheme 'http' or 'https` when downloading
## 1.3.7
### Features
* New Sort filter: Time to read
* New Filter: Year release filter
### Fix
* Filters can now be used together with search
* Epub and pdfs no longer show in format filter (currently not supported)
## 1.3.6
### Fix
* Fixed "lateinit property title not initialized"
## 1.3.5
### Features
* Ignore DOH
* Added sort option `Item Added`
* Latest button now shows latest `Item Added`
## 1.3.4
### Features
* Exclude from bulk update warnings
## 1.2.3
### Fix
* Fixed Rating filter
* Fixed Chapter list not sorting correctly
* Fixed search
* Fixed manga details not showing correctly
* Fixed filters not populating if account was not admin
### Features
* The extension is now ready to implement tracking.
* Min required version for the extension to work properly: `v0.5.1.1`
## 1.2.2
### Features
* Add `CHANGELOG.md` & `README.md`
## 1.2.1
### Features
* first version

View File

@@ -1,37 +1,41 @@
# Kavita # Komga
Table of Content Table of Content
- [FAQ](#FAQ) - [FAQ](#FAQ)
- [Why do I see no manga?](#why-do-i-see-no-manga) - [Why do I see no manga?](#why-do-i-see-no-manga)
- [Where can I get more information about Kavita?](#where-can-i-get-more-information-about-kavita) - [Where can I get more information about Komga?](#where-can-i-get-more-information-about-komga)
- [The Kavita extension stopped working?](#the-kavita-extension-stopped-working) - [The Komga extension stopped working?](#the-komga-extension-stopped-working)
- [Can I add more than one Kavita server or user?](#can-i-add-more-than-one-kavita-server-or-user) - [Can I add more than one Komga server or user?](#can-i-add-more-than-one-komga-server-or-user)
- [Can I test the Kavita extension before setting up my own server?](#can-i-test-the-kavita-extension-before-setting-up-my-own-server) - [Can I test the Komga extension before setting up my own server?](#can-i-test-the-komga-extension-before-setting-up-my-own-server)
- [Guides](#Guides) - [Guides](#Guides)
- [How do I add my Kavita server to Tachiyomi?](#how-do-i-add-my-kavita-server-to-tachiyomi) - [How do I add my Komga server to the app?](#how-do-i-add-my-komga-server-to-the-app)
Don't find the question you are look for go check out our general FAQs and Guides over at [Extension FAQ](https://tachiyomi.org/help/faq/#extensions) or [Getting Started](https://tachiyomi.org/help/guides/getting-started/#installation)
Kavita also has a documentation about the Tachiyomi Kavita extension at the [Kavita wiki](https://wiki.kavitareader.com/en/guides/misc/tachiyomi).
## FAQ ## FAQ
### Why do I see no manga? ### Why do I see no manga?
Kavita is a self-hosted comic/manga media server. Komga is a self-hosted comic/manga media server.
### Where can I get more information about Kavita? ### Where can I get more information about Komga?
You can visit the [Kavita](https://www.kavitareader.com/) website for for more information. You can visit the [Komga](https://komga.org/) website for for more information.
### The Kavita extension stopped working? ### The Komga extension stopped working?
Make sure that your Kavita server and extension are on the newest version. Make sure that your Komga server and extension are on the newest version.
### Can I add more than one Kavita server or user? ### Can I add more than one Komga server or user?
Yes, currently you can add up to 3 different Kavita instances to Tachiyomi. Yes, currently you can add up to 11 different Komga instances to the app. The number of instances
available can be customized in extension settings.
### Can I test the Kavita extension before setting up my own server? ### Can I test the Komga extension before setting up my own server?
Yes, you can try it out with the DEMO servers OPDS url `https://demo.kavitareader.com/api/opds/aca1c50d-7e08-4f37-b356-aecd6bf69b72`. Yes, you can try it out with the DEMO server `https://demo.komga.org`, username `demo@komga.org` and
password `komga-demo`.
### Why are EPUB chapters/books missing?
Mihon/Tachiyomi does not support reading text. EPUB files containing only images will be available
if your Komga server version is [1.9.0](https://github.com/gotson/komga/releases/tag/1.9.0)
or newer.
## Guides ## Guides
### How do I add my Kavita server to Tachiyomi? ### How do I add my Komga server to the app?
Go into the settings of the Kavita extension from the Extension tab in Browse and fill in your OPDS url. Go into the settings of the Komga extension (under Browse -> Extensions) and fill in your server
address and login details.

View File

@@ -3,6 +3,20 @@ login_errors_header_token_empty="Error: The JSON Web Token is empty.\nTry openin
login_errors_invalid_url=Invalid URL: login_errors_invalid_url=Invalid URL:
login_errors_parse_tokendto=There was an error parsing the auth token login_errors_parse_tokendto=There was an error parsing the auth token
pref_customsource_title=Displayed name for source pref_customsource_title=Displayed name for source
pref_group_tags_title=Group Tags (fork must support grouping)
pref_group_tags_summary_on=Will prefix tags with their type
pref_group_tags_summary_off=List all tags together
pref_last_volume_cover_title=Keep cover updated
pref_last_volume_cover_summary_off=Keep current cover
pref_last_volume_cover_summary_on=Use the last volume cover when updating
pref_show_epub_title=Show EPUB (EPUB can't be read in Mihon)
pref_show_epub_summary_off=Hide EPUB titles in browsing
pref_show_epub_summary_on=Show EPUB titles in browsing
pref_rd_date_title=Reading List: Display Release Date
pref_rd_date_summary_off=Do not display the release date
pref_rd_date_summary_on=Display the release date | !! Once you toggle it on, if you toggle it off again, it will stays as N/A !!
pref_reset_title=Reset All Settings
pref_reset_summary=Clear all preferences for this Kavita instance (Only affect the selected instance)
pref_edit_customsource_summary=Here you can change this source name.\nYou can write a descriptive name to identify this OPDS URL. pref_edit_customsource_summary=Here you can change this source name.\nYou can write a descriptive name to identify this OPDS URL.
pref_filters_summary=Show these filters in the filter list pref_filters_summary=Show these filters in the filter list
pref_filters_title=Default filters shown pref_filters_title=Default filters shown
@@ -10,7 +24,7 @@ pref_opds_badformed_url=Incorrect OPDS address. Please copy it from User setting
pref_opds_duplicated_source_url=The URL is configured in a different source -> pref_opds_duplicated_source_url=The URL is configured in a different source ->
pref_opds_must_setup_address=You must set up the address to communicate with Kavita pref_opds_must_setup_address=You must set up the address to communicate with Kavita
pref_opds_summary=The OPDS URL copied from User Settings. This should include address and end with the API key. pref_opds_summary=The OPDS URL copied from User Settings. This should include address and end with the API key.
restartapp_settings=Restart Tachiyomi to apply new setting. restartapp_settings=Restart Mihon to apply new setting.
version_exceptions_chapters_parse=Unhandled exception parsing chapters. Send your logs to the Kavita devs. version_exceptions_chapters_parse=Unhandled exception parsing chapters. Send your logs to the Kavita devs.
check_version=Ensure you have the newest version of the extension and Kavita. (0.7.8 or newer.)\nIf the issue persists, report it to the Kavita developers with the accompanying logs. check_version=Ensure you have the newest version of the extension and Kavita. (0.7.8 or newer.)\nIf the issue persists, report it to the Kavita developers with the accompanying logs.
version_exceptions_smart_filter=Could not decode SmartFilter. Ensure you are using Kavita version 0.7.11 or later. version_exceptions_smart_filter=Could not decode SmartFilter. Ensure you are using Kavita version 0.7.11 or later.

View File

@@ -1,6 +1,4 @@
version_exceptions_chapters_parse=Exception non trait\u00E9e durant l'analyse des chapitres. Envoyez les logs aux d\u00E9velopeurs de Kavita.
version_exceptions_chapters_parse=Exception non trait\u00E9e durant l'analyse des chapitres. Envoyez les journaux aux d\u00E9velopeurs de Kavita
pref_customsource_title=Nom d'affichage pour la source pref_customsource_title=Nom d'affichage pour la source
version_exceptions_smart_filter=\u00C9chec du d\u00E9codage de SmartFilter. Assurez-vous que vous utilisez au moins Kavita version 0.7.11 version_exceptions_smart_filter=\u00C9chec du d\u00E9codage de SmartFilter. Assurez-vous que vous utilisez au moins Kavita version 0.7.11
pref_opds_summary=L'URL OPDS a \u00E9t\u00E9 copi\u00E9e \u00E0 partir des param\u00E8tres de l'utilisateur. Ceci devrait inclure l'adresse et la cl\u00E9 API. pref_opds_summary=L'URL OPDS a \u00E9t\u00E9 copi\u00E9e \u00E0 partir des param\u00E8tres de l'utilisateur. Ceci devrait inclure l'adresse et la cl\u00E9 API.
@@ -8,13 +6,13 @@ pref_filters_summary=Afficher ces filtres dans la liste des filtres
check_version=Assurez-vous que vous avez l'extension et Kavita mises \u00E0 jour. (version Mini\u202F: 0.7.8)\nSi le probl\u00E8me persiste, signalez-le aux d\u00E9veloppeurs de Kavita en fournissant des journaux check_version=Assurez-vous que vous avez l'extension et Kavita mises \u00E0 jour. (version Mini\u202F: 0.7.8)\nSi le probl\u00E8me persiste, signalez-le aux d\u00E9veloppeurs de Kavita en fournissant des journaux
pref_filters_title=Filtres par d\u00E9faut affich\u00E9s pref_filters_title=Filtres par d\u00E9faut affich\u00E9s
pref_edit_customsource_summary=Ici vous pouvez changer ce nom source.\nVous pouvez \u00E9crire un nom descriptif pour identifier cette URL opds pref_edit_customsource_summary=Ici vous pouvez changer ce nom source.\nVous pouvez \u00E9crire un nom descriptif pour identifier cette URL opds
pref_opds_badformed_url=L'adresse OPDS n'est pas correcte. Veuillez la copiez \u00E0 partir des param\u00E8tres de l'utilisateur - > Applis tierces -> URL OPDS pref_opds_badformed_url=L'adresse OPDS n'est pas correcte. Veuillez la copier \u00E0 partir des param\u00E8tres de l'utilisateur - > Applis tierces -> URL OPDS
login_errors_parse_tokendto=Il y a eu une erreur pendant l'analyse du jeton d'authentification login_errors_parse_tokendto=Il y a eu une erreur pendant l'analyse du jeton d'authentification
restartapp_settings=Red\u00E9marrez Tachiyomi pour appliquer le nouveau r\u00E9glage. restartapp_settings=Red\u00E9marrez Mihon pour appliquer le nouveau r\u00E9glage.
pref_opds_duplicated_source_url=L'URL est configur\u00E9e dans une autre source -> pref_opds_duplicated_source_url=L'URL est configur\u00E9e dans une autre source ->
pref_opds_must_setup_address=Vous devez configurer l'adresse pour communiquer avec Kavita pref_opds_must_setup_address=Vous devez configurer l'adresse pour communiquer avec Kavita
login_errors_failed_login=\u00C9chec de la connexion. Quelque chose s'est mal pass\u00E9 login_errors_failed_login=\u00C9chec de la connexion. Quelque chose s'est mal pass\u00E9
http_errors_500=Quelque chose s'est mal pass\u00E9 http_errors_500=Quelque chose s'est mal pass\u00E9
login_errors_header_token_empty=\u00AB\u00A0Erreur\u202F: le jeton jwt est vide.\nEssayez d'abord d'ouvrir l'extension\u00A0\u00BB login_errors_header_token_empty=\u00AB\u00A0Erreur\u202F: le token jwt est vide.\nEssayez d'abord d'ouvrir l'extension\u00A0\u00BB
login_errors_invalid_url=URL invalide\u202F: login_errors_invalid_url=URL invalide\u202F:
http_errors_401=Il y a eu une erreur. Essayez de nouveau ou rechargez l'application http_errors_401=Il y a eu une erreur. Essayez de nouveau ou relancez l'application

View File

@@ -1,8 +1,6 @@
pref_customsource_title=Vist kildenavn pref_customsource_title=Vist kildenavn
pref_edit_customsource_summary=Her kan du endre dette kildenavnet.\nDu kan skrive et beskrivende navn for \u00E5 identifisere denne OPDS-nettadressen. pref_edit_customsource_summary=Her kan du endre dette kildenavnet.\nDu kan skrive et beskrivende navn for \u00E5 identifisere denne OPDS-nettadressen.
restartapp_settings=Ny innstilling trer i kraft n\u00E5r du starter Tachiyomi p\u00E5 ny. restartapp_settings=Ny innstilling trer i kraft n\u00E5r du starter Mihon p\u00E5 ny.
duplicated_source_url=Nettadressen er satt opp i en annen Kavita-instans duplicated_source_url=Nettadressen er satt opp i en annen Kavita-instans
pref_filters_summary=Vis disse filterne i filterlisten pref_filters_summary=Vis disse filterne i filterlisten
pref_filters_title=Forvalgte filtre valgt pref_filters_title=Forvalgte filtre valgt

View File

@@ -1,17 +1,14 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlinx-serialization'
ext { ext {
kmkVersionCode = 1
extName = 'Kavita' extName = 'Kavita'
pkgNameSuffix = 'all.kavita'
extClass = '.KavitaFactory' extClass = '.KavitaFactory'
extVersionCode = 16 extVersionCode = 19
} isNsfw = false
dependencies {
implementation 'info.debatty:java-string-similarity:2.0.0'
implementation(project(':lib-i18n'))
} }
apply from: "$rootDir/common.gradle" apply from: "$rootDir/common.gradle"
dependencies {
implementation("org.apache.commons:commons-text:1.11.0")
implementation project(':lib:i18n')
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 47 KiB

View File

@@ -3,18 +3,25 @@ package eu.kanade.tachiyomi.extension.all.kavita
import eu.kanade.tachiyomi.extension.all.kavita.KavitaConstants.noSmartFilterSelected import eu.kanade.tachiyomi.extension.all.kavita.KavitaConstants.noSmartFilterSelected
import eu.kanade.tachiyomi.source.model.Filter import eu.kanade.tachiyomi.source.model.Filter
class UserRating : class UserRating : Filter.Select<Int>(
Filter.Select<String>( "Minimum Rating",
"Minimum Rating", arrayOf(
arrayOf( "Any",
"Any", "1 star",
"1 star", "2 stars",
"2 stars", "3 stars",
"3 stars", "4 stars",
"4 stars", "5 stars",
"5 stars", ).mapIndexed { index, _ -> index }.toTypedArray(),
), ) {
) override fun toString(): String {
return when (state) {
0 -> "Any"
else -> "$state star${if (state > 1) "s" else ""}"
}
}
}
class SmartFiltersFilter(smartFilters: Array<String>) : class SmartFiltersFilter(smartFilters: Array<String>) :
Filter.Select<String>("Smart Filters", arrayOf(noSmartFilterSelected) + smartFilters) Filter.Select<String>("Smart Filters", arrayOf(noSmartFilterSelected) + smartFilters)
class SortFilter(sortables: Array<String>) : Filter.Sort("Sort by", sortables, Selection(0, true)) class SortFilter(sortables: Array<String>) : Filter.Sort("Sort by", sortables, Selection(0, true))
@@ -26,15 +33,27 @@ val sortableList = listOf(
Pair("Item added", 4), Pair("Item added", 4),
Pair("Time to Read", 5), Pair("Time to Read", 5),
Pair("Release year", 6), Pair("Release year", 6),
Pair("Read Progress", 7),
Pair("Average Rating", 8),
Pair("Random", 9),
) )
class SpecialListFilter : Filter.Select<String>(
"Special Lists",
arrayOf("None", "Want to Read", "Reading Lists"),
)
// Use Filter.CheckBox directly for status
class StatusFilter(name: String) : Filter.CheckBox(name, false) class StatusFilter(name: String) : Filter.CheckBox(name, false)
class StatusFilterGroup(filters: List<StatusFilter>) : class StatusFilterGroup(filters: List<StatusFilter>) :
Filter.Group<StatusFilter>("Status", filters) Filter.Group<StatusFilter>("Status", filters)
class ReleaseYearRange(name: String) : Filter.Text(name) // Use Filter.Text directly for release year range
class ReleaseYearRange(name: String) : Filter.Text(name, "")
class ReleaseYearRangeGroup(filters: List<ReleaseYearRange>) : class ReleaseYearRangeGroup(filters: List<ReleaseYearRange>) :
Filter.Group<ReleaseYearRange>("Release Year", filters) Filter.Group<ReleaseYearRange>("Release Year", filters)
// Use Filter.TriState for genres/tags/age ratings/collections/languages/libraries
class GenreFilter(name: String) : Filter.TriState(name) class GenreFilter(name: String) : Filter.TriState(name)
class GenreFilterGroup(genres: List<GenreFilter>) : class GenreFilterGroup(genres: List<GenreFilter>) :
Filter.Group<GenreFilter>("Genres", genres) Filter.Group<GenreFilter>("Genres", genres)

View File

@@ -1,10 +1,18 @@
package eu.kanade.tachiyomi.extension.all.kavita package eu.kanade.tachiyomi.extension.all.kavita
object KavitaConstants { object KavitaConstants {
val PERSON_ROLES = listOf(
"Writer", "Penciller", "Inker", "Colorist",
"Letterer", "CoverArtist", "Editor",
"Publisher", "Character", "Translator",
)
// toggle filters // toggle filters
const val toggledFiltersPref = "toggledFilters" const val toggledFiltersPref = "toggledFilters"
val filterPrefEntries = arrayOf( val filterPrefEntries = arrayOf(
"Sort Options", "Sort Options",
"Special Lists",
"Format", "Format",
"Libraries", "Libraries",
"Read Status", "Read Status",
@@ -26,9 +34,13 @@ object KavitaConstants {
"Character", "Character",
"Translators", "Translators",
"ReleaseYearRange", "ReleaseYearRange",
"Average Rating",
"Random",
"Read Progress",
) )
val filterPrefEntriesValue = arrayOf( val filterPrefEntriesValue = arrayOf(
"Sort Options", "Sort Options",
"Special Lists",
"Format", "Format",
"Libraries", "Libraries",
"Read Status", "Read Status",
@@ -50,9 +62,13 @@ object KavitaConstants {
"Character", "Character",
"Translators", "Translators",
"ReleaseYearRange", "ReleaseYearRange",
"Average Rating",
"Random",
"Read Progress",
) )
val defaultFilterPrefEntries = setOf( val defaultFilterPrefEntries = setOf(
"Sort Options", "Sort Options",
"Special Lists",
"Format", "Format",
"Libraries", "Libraries",
"Read Status", "Read Status",
@@ -74,6 +90,9 @@ object KavitaConstants {
"Character", "Character",
"Translators", "Translators",
"ReleaseYearRange", "ReleaseYearRange",
"Average Rating",
"Random",
"Read Progress",
) )
const val customSourceNamePref = "customSourceName" const val customSourceNamePref = "customSourceName"

View File

@@ -1,7 +1,9 @@
package eu.kanade.tachiyomi.extension.all.kavita package eu.kanade.tachiyomi.extension.all.kavita
import android.util.Log
import eu.kanade.tachiyomi.extension.all.kavita.dto.ChapterDto import eu.kanade.tachiyomi.extension.all.kavita.dto.ChapterDto
import eu.kanade.tachiyomi.extension.all.kavita.dto.ChapterType import eu.kanade.tachiyomi.extension.all.kavita.dto.ChapterType
import eu.kanade.tachiyomi.extension.all.kavita.dto.LibraryTypeEnum
import eu.kanade.tachiyomi.extension.all.kavita.dto.PaginationInfo import eu.kanade.tachiyomi.extension.all.kavita.dto.PaginationInfo
import eu.kanade.tachiyomi.extension.all.kavita.dto.SeriesDto import eu.kanade.tachiyomi.extension.all.kavita.dto.SeriesDto
import eu.kanade.tachiyomi.extension.all.kavita.dto.VolumeDto import eu.kanade.tachiyomi.extension.all.kavita.dto.VolumeDto
@@ -42,62 +44,138 @@ class KavitaHelper {
} }
fun getIdFromUrl(url: String): Int { fun getIdFromUrl(url: String): Int {
return url.split("/").last().toInt() return try {
val id = url.substringAfterLast("/").toInt()
Log.d("KavitaHelper", "Extracted ID $id from URL: $url")
id
} catch (e: Exception) {
Log.e("KavitaHelper", "Failed to extract ID from URL: $url", e)
-1
}
} }
fun createSeriesDto(obj: SeriesDto, baseUrl: String, apiKey: String): SManga = // Rating Providers from Series-Details-Plus
private fun getProviderName(provider: Int): String = when (provider) {
0 -> "User"
1 -> "AniList"
2 -> "MyAnimeList"
3 -> "MangaUpdates"
else -> "Rating"
}
fun createSeriesDto(obj: SeriesDto, baseUrl: String, apiUrl: String, apiKey: String): SManga =
SManga.create().apply { SManga.create().apply {
// url = "$baseUrl/library/${obj.libraryId}/series/${obj.id}"
url = "$baseUrl/Series/${obj.id}" url = "$baseUrl/Series/${obj.id}"
title = obj.name title = obj.name
// Deprecated: description = obj.summary
thumbnail_url = "$baseUrl/image/series-cover?seriesId=${obj.id}&apiKey=$apiKey" thumbnail_url = "$baseUrl/image/series-cover?seriesId=${obj.id}&apiKey=$apiKey"
}
class CompareChapters { // Set status based on read progress
companion object : Comparator<SChapter> { status = when {
override fun compare(a: SChapter, b: SChapter): Int { obj.pagesRead >= obj.pages -> SManga.COMPLETED
if (a.chapter_number < 1.0 && b.chapter_number < 1.0) { obj.pagesRead > 0 -> SManga.ONGOING
// Both are volumes, multiply by 100 and do normal sort else -> SManga.UNKNOWN
return if ((a.chapter_number * 100) < (b.chapter_number * 100)) {
1
} else {
-1
}
} else {
if (a.chapter_number < 1.0 && b.chapter_number >= 1.0) {
// A is volume, b is not. A should sort first
return 1
} else if (a.chapter_number >= 1.0 && b.chapter_number < 1.0) {
return -1
}
}
if (a.chapter_number < b.chapter_number) return 1
if (a.chapter_number > b.chapter_number) return -1
return 0
} }
} }
}
fun chapterFromVolume(chapter: ChapterDto, volume: VolumeDto): SChapter = // class CompareChapters {
// companion object : Comparator<SChapter> {
// override fun compare(a: SChapter, b: SChapter): Int {
// if (a.chapter_number < 1.0 && b.chapter_number < 1.0) {
// // Both are volumes, multiply by 100 and do normal sort
// return if ((a.chapter_number * 100) < (b.chapter_number * 100)) {
// 1
// } else {
// -1
// }
// } else {
// if (a.chapter_number < 1.0 && b.chapter_number >= 1.0) {
// // A is volume, b is not. A should sort first
// return 1
// } else if (a.chapter_number >= 1.0 && b.chapter_number < 1.0) {
// return -1
// }
// }
// if (a.chapter_number < b.chapter_number) return 1
// if (a.chapter_number > b.chapter_number) return -1
// return 0
// }
// }
// }
fun chapterFromVolume(chapter: ChapterDto, volume: VolumeDto, singleFileVolumeNumber: Int? = null, libraryType: LibraryTypeEnum? = null): SChapter =
SChapter.create().apply { SChapter.create().apply {
val type = ChapterType.of(chapter, volume) val type = ChapterType.of(chapter, volume, libraryType)
name = when (type) { name = when (type) {
ChapterType.Regular -> "Volume ${volume.number} Chapter ${chapter.number}" ChapterType.Regular -> {
ChapterType.SingleFileVolume -> "Volume ${volume.number}" val volumeNum = volume.number.toString().toIntOrNull()?.let {
ChapterType.Special -> chapter.range it.toString().padStart(2, '0')
ChapterType.LooseLeaf -> { } ?: volume.number.toString()
val cleanedName = chapter.title.replaceFirst("^0+(?!$)".toRegex(), "") val chapterNum = chapter.number.toIntOrNull()?.let {
"Chapter $cleanedName" it.toString().padStart(2, '0')
} ?: chapter.number
when {
chapter.titleName.isBlank() -> "Volume $volumeNum Chapter $chapterNum"
chapter.titleName.trim().matches(Regex("^\\d+$")) -> "Volume $volumeNum Chapter ${chapter.titleName.trim().padStart(2, '0')}"
else -> "Volume $volumeNum $chapterNum - ${chapter.titleName}"
}
}
ChapterType.SingleFileVolume -> {
when {
volume.name.isBlank() -> "Volume ${volume.number}"
volume.name.trim().matches(Regex("^\\d+$")) -> "Volume ${volume.name.trim().toIntOrNull()?.toString() ?: volume.name.trim()}"
else -> "${volume.number} - ${volume.name}"
}
}
ChapterType.Special -> chapter.titleName.takeIf { it.isNotBlank() } ?: chapter.range
ChapterType.Chapter -> {
val chapterNum = chapter.number.toIntOrNull()?.let {
it.toString().padStart(2, '0')
} ?: chapter.number
when {
chapter.titleName.isBlank() -> "Chapter $chapterNum"
chapter.titleName.trim().matches(Regex("^\\d+$")) -> "Chapter ${chapter.titleName.trim().padStart(2, '0')}"
else -> "$chapterNum - ${chapter.titleName}"
}
}
ChapterType.Issue -> {
val issueNum = chapter.number.toIntOrNull()?.let {
it.toString().padStart(3, '0')
} ?: chapter.number
when {
chapter.titleName.isNotBlank() && !chapter.titleName.trim().matches(Regex("^\\d+$")) ->
"#$issueNum ${chapter.titleName}"
chapter.title.isNotBlank() && !chapter.title.trim().matches(Regex("^\\d+$")) ->
"#$issueNum ${chapter.title}"
else -> "Issue #$issueNum"
}
} }
} }
chapter_number = if (type == ChapterType.SingleFileVolume) { // chapter_number = try {
volume.number.toFloat() / 10000 // // if (type == ChapterType.SingleFileVolume) {
} else { // // volume.number.toFloat() / 10000
chapter.number.toFloat() // // } else {
// // chapter.number.toFloatOrNull() ?: 0f
// // }
// // } catch (e: NumberFormatException) {
// // 0f
// // }
chapter_number = when {
type == ChapterType.SingleFileVolume && singleFileVolumeNumber != null -> singleFileVolumeNumber.toFloat()
type != ChapterType.SingleFileVolume -> chapter.number.toFloatOrNull() ?: 0f
else -> 0f
} }
url = chapter.id.toString() url = when {
type == ChapterType.SingleFileVolume && singleFileVolumeNumber != null ->
"volume_${volume.id}"
else -> chapter.id.toString()
}
// url = chapter.id.toString()
if (chapter.fileCount > 1) { if (chapter.fileCount > 1) {
// salt/offset to recognize chapters with new merged part-chapters as new and hence unread // salt/offset to recognize chapters with new merged part-chapters as new and hence unread
@@ -105,8 +183,14 @@ class KavitaHelper {
url = "${url}_${chapter.fileCount}" url = "${url}_${chapter.fileCount}"
} }
date_upload = parseDate(chapter.created) date_upload = parseDateSafe(chapter.created)
scanlator = "${chapter.pages} pages" scanlator = when (type) {
ChapterType.SingleFileVolume -> "Volume"
ChapterType.Special -> "Special"
ChapterType.Issue -> "Issue"
ChapterType.Chapter -> "Chapter"
ChapterType.Regular -> "Chapter"
}
} }
val intl = Intl( val intl = Intl(

View File

@@ -0,0 +1,93 @@
package eu.kanade.tachiyomi.extension.all.kavita
import android.text.Editable
import android.text.TextWatcher
import android.widget.Button
import android.widget.Toast
import androidx.preference.EditTextPreference
import androidx.preference.PreferenceScreen
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
val formatterDate = SimpleDateFormat("yyyy-MM-dd", Locale.US)
.apply { timeZone = TimeZone.getTimeZone("UTC") }
val formatterDateTime = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US)
.apply { timeZone = TimeZone.getTimeZone("UTC") }
fun parseDateSafe(date: String?): Long {
return date?.let {
try {
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US)
sdf.timeZone = TimeZone.getTimeZone("UTC")
sdf.parse(it)?.time ?: 0L
} catch (_: Exception) {
0L
}
} ?: 0L
}
fun PreferenceScreen.addEditTextPreference(
title: String,
default: String,
summary: String,
dialogMessage: String? = null,
inputType: Int? = null,
validate: ((String) -> Boolean)? = null,
validationMessage: String? = null,
key: String = title,
restartRequired: Boolean = false,
) {
EditTextPreference(context).apply {
this.key = key
this.title = title
this.summary = summary
this.setDefaultValue(default)
dialogTitle = title
this.dialogMessage = dialogMessage
setOnBindEditTextListener { editText ->
if (inputType != null) {
editText.inputType = inputType
}
if (validate != null) {
editText.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(editable: Editable?) {
requireNotNull(editable)
val text = editable.toString()
val isValid = text.isBlank() || validate(text)
editText.error = if (!isValid) validationMessage else null
editText.rootView.findViewById<Button>(android.R.id.button1)
?.isEnabled = editText.error == null
}
},
)
}
}
setOnPreferenceChangeListener { _, newValue ->
try {
val text = newValue as String
val result = text.isBlank() || validate?.invoke(text) ?: true
if (restartRequired && result) {
Toast.makeText(context, "Restart Tachiyomi to apply new setting.", Toast.LENGTH_LONG).show()
}
result
} catch (e: Exception) {
e.printStackTrace()
false
}
}
}.also(::addPreference)
}

View File

@@ -8,7 +8,7 @@ data class FilterV2Dto(
val id: Int? = null, val id: Int? = null,
val name: String? = null, val name: String? = null,
val statements: MutableList<FilterStatementDto> = mutableListOf(), val statements: MutableList<FilterStatementDto> = mutableListOf(),
val combination: Int = 0, // FilterCombination = FilterCombination.And, val combination: Int = FilterCombination.And.ordinal,
val sortOptions: SortOptions = SortOptions(), val sortOptions: SortOptions = SortOptions(),
val limitTo: Int = 0, val limitTo: Int = 0,
) { ) {
@@ -17,20 +17,22 @@ data class FilterV2Dto(
statements.add(FilterStatementDto(comparison.type, field.type, value)) statements.add(FilterStatementDto(comparison.type, field.type, value))
} }
} }
fun addStatement(comparison: FilterComparison, field: FilterField, values: java.util.ArrayList<out Any>) {
fun addStatement(comparison: FilterComparison, field: FilterField, values: List<Any>) {
if (values.isNotEmpty()) { if (values.isNotEmpty()) {
statements.add(FilterStatementDto(comparison.type, field.type, values.joinToString(","))) statements.add(FilterStatementDto(comparison.type, field.type, values.joinToString(",")))
} }
} }
fun addContainsNotTriple(list: List<Triple<FilterField, java.util.ArrayList<out Any>, ArrayList<Int>>>) { fun addContainsNotTriple(list: List<Triple<FilterField, List<Any>, List<Int>>>) {
list.map { list.forEach {
addStatement(FilterComparison.Contains, it.first, it.second) addStatement(FilterComparison.Contains, it.first, it.second)
addStatement(FilterComparison.NotContains, it.first, it.third) addStatement(FilterComparison.NotContains, it.first, it.third)
} }
} }
fun addPeople(list: List<Pair<FilterField, ArrayList<Int>>>) {
list.map { fun addPeople(list: List<Pair<FilterField, List<Int>>>) {
list.forEach {
addStatement(FilterComparison.MustContains, it.first, it.second) addStatement(FilterComparison.MustContains, it.first, it.second)
} }
} }
@@ -38,11 +40,15 @@ data class FilterV2Dto(
@Serializable @Serializable
data class FilterStatementDto( data class FilterStatementDto(
// todo: Create custom serializator for comparison and field and remove .type extension in Kavita.kt
val comparison: Int, val comparison: Int,
val field: Int, val field: Int,
val value: String, val value: String,
)
@Serializable
data class SortOptions(
var sortField: Int = SortFieldEnum.AverageRating.type,
var isAscending: Boolean = true,
) )
@Serializable @Serializable
@@ -53,20 +59,17 @@ enum class SortFieldEnum(val type: Int) {
LastChapterAdded(4), LastChapterAdded(4),
TimeToRead(5), TimeToRead(5),
ReleaseYear(6), ReleaseYear(6),
ReadProgress(7),
AverageRating(8),
Random(9),
; ;
companion object { companion object {
private val map = SortFieldEnum.values().associateBy(SortFieldEnum::type) private val map = values().associateBy(SortFieldEnum::type)
fun fromInt(type: Int) = map[type] fun fromInt(type: Int) = map[type]
} }
} }
@Serializable
data class SortOptions(
var sortField: Int = SortFieldEnum.SortName.type,
var isAscending: Boolean = true,
)
@Serializable @Serializable
enum class FilterCombination { enum class FilterCombination {
Or, Or,
@@ -101,6 +104,18 @@ enum class FilterField(val type: Int) {
ReadTime(23), ReadTime(23),
Path(24), Path(24),
FilePath(25), FilePath(25),
WantToRead(26),
ReadingDate(27),
AverageRating(28),
Imprint(29),
Team(30),
Location(31),
ReadLast(32),
;
companion object {
fun fromType(type: Int): FilterField? = values().find { it.type == type }
}
} }
@Serializable @Serializable
@@ -121,4 +136,46 @@ enum class FilterComparison(val type: Int) {
IsAfter(13), IsAfter(13),
IsInLast(14), IsInLast(14),
IsNotInLast(15), IsNotInLast(15),
IsEmpty(16),
}
@Serializable
data class PersonSearchDto(
val id: Int,
val name: String,
val role: Int? = null,
)
enum class PersonRole(val id: Int) {
Writer(0),
Penciller(1),
Inker(2),
Colorist(3),
Letterer(4),
CoverArtist(5),
Editor(6),
Publisher(7),
Character(8),
Translator(9),
;
companion object {
private val map = values().associateBy(PersonRole::id)
fun fromId(id: Int): PersonRole? = map[id]
}
}
fun PersonRole.toFilterField(): FilterField? {
return when (this) {
PersonRole.Writer -> FilterField.Writers
PersonRole.Penciller -> FilterField.Penciller
PersonRole.Inker -> FilterField.Inker
PersonRole.Colorist -> FilterField.Colorist
PersonRole.Letterer -> FilterField.Letterer
PersonRole.CoverArtist -> FilterField.CoverArtist
PersonRole.Editor -> FilterField.Editor
PersonRole.Publisher -> FilterField.Publisher
PersonRole.Character -> FilterField.Characters
PersonRole.Translator -> FilterField.Translators
}
} }

View File

@@ -1,7 +1,13 @@
package eu.kanade.tachiyomi.extension.all.kavita.dto package eu.kanade.tachiyomi.extension.all.kavita.dto
import eu.kanade.tachiyomi.source.model.SManga
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
interface ConvertibleToSManga {
fun toSManga(baseUrl: String, apiUrl: String, apiKey: String): SManga
}
@Serializable @Serializable
enum class MangaFormat(val format: Int) { enum class MangaFormat(val format: Int) {
Image(0), Image(0),
@@ -10,26 +16,32 @@ enum class MangaFormat(val format: Int) {
Epub(3), Epub(3),
Pdf(4), Pdf(4),
; ;
companion object { companion object {
private val map = PersonRole.values().associateBy(PersonRole::role) private val map = values().associateBy(MangaFormat::format)
fun fromInt(type: Int) = map[type] fun fromInt(type: Int): MangaFormat? = map[type]
} }
} }
enum class PersonRole(val role: Int) {
Other(1), @Serializable
Writer(3), data class LibraryDto(
Penciller(4), val id: Int,
Inker(5), val name: String,
Colorist(6), val type: Int,
Letterer(7), )
CoverArtist(8),
Editor(9), @Serializable // https://github.com/Kareadita/Kavita/blob/develop/API/Entities/Enums/LibraryType.cs
Publisher(10), enum class LibraryTypeEnum(val type: Int) {
Character(11), Manga(0),
Translator(12), Comic(1),
Book(2),
Image(3),
LightNovel(4),
ComicVine(5),
; ;
companion object { companion object {
private val map = PersonRole.values().associateBy(PersonRole::role) private val map = values().associateBy(LibraryTypeEnum::type)
fun fromInt(type: Int) = map[type] fun fromInt(type: Int) = map[type]
} }
} }
@@ -51,28 +63,127 @@ data class SeriesDto(
val created: String? = "", val created: String? = "",
val libraryId: Int, val libraryId: Int,
val libraryName: String? = "", val libraryName: String? = "",
val ratings: List<RatingDto> = emptyList(),
) )
@Serializable @Serializable
data class SeriesMetadataDto( data class SeriesDetailPlusDto(
val seriesId: Int? = null,
val libraryName: String? = "",
val libraryId: Int? = null,
val summary: String? = null,
val genres: List<MetadataGenres> = emptyList(),
val tags: List<MetadataTag> = emptyList(),
val writers: List<MetadataPeople> = emptyList(),
val coverArtists: List<MetadataPeople> = emptyList(),
val publicationStatus: Int? = null,
val averageScore: Float = 0f,
val ratings: List<RatingDto> = emptyList(),
) {
// Helper function to get the library name from SeriesDto if needed
fun getLibraryName(seriesDto: SeriesDto?): String? {
return if (!libraryName.isNullOrEmpty()) {
libraryName
} else {
seriesDto?.libraryName
}
}
// Helper function to get the library ID from SeriesDto if needed
fun getLibraryId(seriesDto: SeriesDto?): Int? {
return libraryId ?: seriesDto?.libraryId
}
}
@Serializable
data class SeriesDetailPlusWrapperDto(
val series: SeriesPlus? = null,
val ratings: List<RatingDto> = emptyList(),
val recommendations: RecommendationsDto? = null,
)
@Serializable
data class SeriesPlus(
val averageScore: Float = 0f,
val summary: String = "",
val relations: List<RelationDto> = emptyList(),
)
@Serializable
data class RecommendationsDto(
val ownedSeries: List<SeriesDto> = emptyList(),
)
@Serializable
data class RatingDto(
val averageScore: Float = 0f,
val favoriteCount: Int = 0,
val provider: Int = 0,
val authority: Int = 0,
val providerUrl: String? = null,
)
@Serializable
data class RelationDto(
val seriesName: RelationName,
val relation: Int,
val aniListId: Int? = null,
val malId: Int? = null,
val provider: Int? = null,
val plusMediaFormat: Int? = null,
)
@Serializable
data class RelationName(
val englishTitle: String? = null,
val romajiTitle: String? = null,
val nativeTitle: String? = null,
val preferredTitle: String? = null,
)
@Serializable
data class RelatedSeriesResponse(
val sourceSeriesId: Int,
val sequels: List<RelatedSeriesItem> = emptyList(),
val prequels: List<RelatedSeriesItem> = emptyList(),
val spinOffs: List<RelatedSeriesItem> = emptyList(),
val adaptations: List<RelatedSeriesItem> = emptyList(),
val sideStories: List<RelatedSeriesItem> = emptyList(),
val characters: List<RelatedSeriesItem> = emptyList(),
val contains: List<RelatedSeriesItem> = emptyList(),
val others: List<RelatedSeriesItem> = emptyList(),
val alternativeSettings: List<RelatedSeriesItem> = emptyList(),
val alternativeVersions: List<RelatedSeriesItem> = emptyList(),
val doujinshis: List<RelatedSeriesItem> = emptyList(),
val parent: List<RelatedSeriesItem> = emptyList(),
val editions: List<RelatedSeriesItem> = emptyList(),
val annuals: List<RelatedSeriesItem> = emptyList(),
)
@Serializable
data class RelatedSeriesItem(
val id: Int, val id: Int,
val summary: String? = "",
val writers: List<Person> = emptyList(),
val coverArtists: List<Person> = emptyList(),
val genres: List<Genres> = emptyList(),
val seriesId: Int,
val ageRating: Int,
val publicationStatus: Int,
)
@Serializable
data class Genres(
val title: String,
)
@Serializable
data class Person(
val name: String, val name: String,
val coverImage: String? = null,
val libraryId: Int,
val libraryName: String? = null,
val format: Int = 0,
) : ConvertibleToSManga {
override fun toSManga(baseUrl: String, apiUrl: String, apiKey: String): SManga = SManga.create().apply {
title = name
url = "$baseUrl/Series/$id"
thumbnail_url = when {
!coverImage.isNullOrBlank() && (coverImage.startsWith("http://") || coverImage.startsWith("https://")) -> coverImage
else -> "$apiUrl/image/series-cover?seriesId=$id&apiKey=$apiKey"
}
initialized = true
}
}
@Serializable
data class AuthorDto(
val name: String,
val role: String,
) )
@Serializable @Serializable
@@ -85,27 +196,33 @@ data class VolumeDto(
val lastModified: String, val lastModified: String,
val created: String, val created: String,
val seriesId: Int, val seriesId: Int,
val coverImage: String,
val chapters: List<ChapterDto> = emptyList(), val chapters: List<ChapterDto> = emptyList(),
) )
@Serializable
enum class ChapterType { enum class ChapterType {
Regular, // chapter with volume information Regular, // chapter with volume information
LooseLeaf, // chapter without volume information Chapter, // manga chapter without volume information
SingleFileVolume, SingleFileVolume,
Special, Special,
Issue, // For comics
; ;
companion object { companion object {
fun of(chapter: ChapterDto, volume: VolumeDto): ChapterType = fun of(chapter: ChapterDto, volume: VolumeDto, libraryType: LibraryTypeEnum? = null): ChapterType =
if (volume.number == 100_000) { when {
Special volume.number == 100_000 -> Special
} else if (volume.number == -100_000) { volume.number == -100_000 -> when (libraryType) {
LooseLeaf LibraryTypeEnum.Comic, LibraryTypeEnum.ComicVine -> Issue
} else { LibraryTypeEnum.Manga, LibraryTypeEnum.LightNovel, LibraryTypeEnum.Book -> Chapter
if (chapter.number == "-100000") { else -> Chapter // Default to Chapter for other types
SingleFileVolume }
} else { chapter.number == "-100000" -> SingleFileVolume
Regular else -> when (libraryType) {
LibraryTypeEnum.Comic, LibraryTypeEnum.ComicVine -> Issue
LibraryTypeEnum.Manga, LibraryTypeEnum.LightNovel, LibraryTypeEnum.Book -> Chapter
else -> Regular
} }
} }
} }
@@ -119,10 +236,12 @@ data class ChapterDto(
val pages: Int, val pages: Int,
val isSpecial: Boolean, val isSpecial: Boolean,
val title: String, val title: String,
val titleName: String,
val pagesRead: Int, val pagesRead: Int,
val coverImageLocked: Boolean, val coverImageLocked: Boolean,
val volumeId: Int, val volumeId: Int,
val created: String, val created: String,
val lastModifiedUtc: String,
val files: List<FileDto>? = null, val files: List<FileDto>? = null,
) { ) {
val fileCount: Int val fileCount: Int
@@ -133,3 +252,37 @@ data class ChapterDto(
data class FileDto( data class FileDto(
val id: Int, val id: Int,
) )
@Serializable
data class ReadingListDto(
val id: Int,
val title: String,
val coverImage: String? = null,
val promoted: Boolean = false,
val summary: String?,
val itemCount: Int,
val startingYear: Int,
val startingMonth: Int,
val endingYear: Int,
val endingMonth: Int,
val ownerUserName: String?,
@SerialName("items") val items: List<ReadingListItemDto> = emptyList(),
)
@Serializable
data class ReadingListItemDto(
val id: Int,
val order: Int,
val chapterId: Int?,
val seriesId: Int,
val seriesName: String,
val chapterNumber: String?,
val volumeNumber: String?,
val chapterTitleName: String?,
val volumeId: Int?,
val title: String?,
val summary: String?,
val releaseDate: String?,
val libraryName: String?,
@SerialName("readingListId") val readingListId: Int,
)

View File

@@ -1,100 +1,35 @@
// Metadata descriptors for filters and categorization
package eu.kanade.tachiyomi.extension.all.kavita.dto package eu.kanade.tachiyomi.extension.all.kavita.dto
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
/**
* This file contains all class for filtering
* */
@Serializable @Serializable
data class MetadataGenres( data class MetadataGenres(val id: Int, val title: String)
val id: Int,
val title: String,
)
@Serializable @Serializable
data class MetadataPeople( data class MetadataPeople(
val id: Int, val id: Int,
val name: String, val name: String,
val role: Int, val role: Int? = null,
) )
@Serializable @Serializable
data class MetadataPubStatus( data class MetadataPubStatus(val value: Int, val title: String)
val value: Int,
val title: String,
)
@Serializable @Serializable
data class MetadataTag( data class MetadataTag(val id: Int, val title: String)
val id: Int,
val title: String,
)
@Serializable @Serializable
data class MetadataAgeRatings( data class MetadataAgeRatings(val value: Int, val title: String)
val value: Int,
val title: String,
)
@Serializable @Serializable
data class MetadataLanguages( data class MetadataLanguages(val isoCode: String, val title: String)
val isoCode: String,
val title: String,
)
@Serializable @Serializable
data class MetadataLibrary( data class MetadataLibrary(val id: Int, val name: String, val type: Int)
val id: Int,
val name: String,
val type: Int,
)
@Serializable @Serializable
data class MetadataCollections( data class MetadataCollections(val id: Int, val title: String)
val id: Int,
val title: String,
)
data class MetadataPayload(
val forceUseMetadataPayload: Boolean = true,
var sorting: Int = 1,
var sorting_asc: Boolean = true,
var readStatus: ArrayList<String> = arrayListOf<String>(),
val readStatusList: List<String> = listOf("notRead", "inProgress", "read"),
// _i = included, _e = excluded
var genres_i: ArrayList<Int> = arrayListOf<Int>(),
var genres_e: ArrayList<Int> = arrayListOf<Int>(),
var tags_i: ArrayList<Int> = arrayListOf<Int>(),
var tags_e: ArrayList<Int> = arrayListOf<Int>(),
var ageRating_i: ArrayList<Int> = arrayListOf<Int>(),
var ageRating_e: ArrayList<Int> = arrayListOf<Int>(),
var formats: ArrayList<Int> = arrayListOf<Int>(),
var collections_i: ArrayList<Int> = arrayListOf<Int>(),
var collections_e: ArrayList<Int> = arrayListOf<Int>(),
var userRating: Int = 0,
var people: ArrayList<Int> = arrayListOf<Int>(),
// _i = included, _e = excluded
var language_i: ArrayList<String> = arrayListOf<String>(),
var language_e: ArrayList<String> = arrayListOf<String>(),
var libraries_i: ArrayList<Int> = arrayListOf<Int>(),
var libraries_e: ArrayList<Int> = arrayListOf<Int>(),
var pubStatus: ArrayList<Int> = arrayListOf<Int>(),
var seriesNameQuery: String = "",
var releaseYearRangeMin: Int = 0,
var releaseYearRangeMax: Int = 0,
var peopleWriters: ArrayList<Int> = arrayListOf<Int>(),
var peoplePenciller: ArrayList<Int> = arrayListOf<Int>(),
var peopleInker: ArrayList<Int> = arrayListOf<Int>(),
var peoplePeoplecolorist: ArrayList<Int> = arrayListOf<Int>(),
var peopleLetterer: ArrayList<Int> = arrayListOf<Int>(),
var peopleCoverArtist: ArrayList<Int> = arrayListOf<Int>(),
var peopleEditor: ArrayList<Int> = arrayListOf<Int>(),
var peoplePublisher: ArrayList<Int> = arrayListOf<Int>(),
var peopleCharacter: ArrayList<Int> = arrayListOf<Int>(),
var peopleTranslator: ArrayList<Int> = arrayListOf<Int>(),
)
@Serializable @Serializable
data class SmartFilter( data class SmartFilter(
@@ -102,3 +37,40 @@ data class SmartFilter(
val name: String, val name: String,
val filter: String, val filter: String,
) )
@Serializable
data class MetadataPayload(
val forceUseMetadataPayload: Boolean = true,
var sorting: Int = 1,
var sorting_asc: Boolean = true,
var readStatus: ArrayList<String> = arrayListOf("notRead", "inProgress", "read"),
var genres_i: ArrayList<Int> = arrayListOf(),
var genres_e: ArrayList<Int> = arrayListOf(),
var tags_i: ArrayList<Int> = arrayListOf(),
var tags_e: ArrayList<Int> = arrayListOf(),
var ageRating_i: ArrayList<Int> = arrayListOf(),
var ageRating_e: ArrayList<Int> = arrayListOf(),
var formats: ArrayList<Int> = arrayListOf(),
var collections_i: ArrayList<Int> = arrayListOf(),
var collections_e: ArrayList<Int> = arrayListOf(),
var userRating: Int = 0,
var people: ArrayList<Int> = arrayListOf(),
var language_i: ArrayList<String> = arrayListOf(),
var language_e: ArrayList<String> = arrayListOf(),
var libraries_i: ArrayList<Int> = arrayListOf(),
var libraries_e: ArrayList<Int> = arrayListOf(),
var pubStatus: ArrayList<Int> = arrayListOf(),
var seriesNameQuery: String = "",
var releaseYearRangeMin: Int = 0,
var releaseYearRangeMax: Int = 0,
var peopleWriters: ArrayList<Int> = arrayListOf(),
var peoplePenciller: ArrayList<Int> = arrayListOf(),
var peopleInker: ArrayList<Int> = arrayListOf(),
var peopleColorist: ArrayList<Int> = arrayListOf(),
var peopleLetterer: ArrayList<Int> = arrayListOf(),
var peopleCoverArtist: ArrayList<Int> = arrayListOf(),
var peopleEditor: ArrayList<Int> = arrayListOf(),
var peoplePublisher: ArrayList<Int> = arrayListOf(),
var peopleCharacter: ArrayList<Int> = arrayListOf(),
var peopleTranslator: ArrayList<Int> = arrayListOf(),
)

View File

@@ -1,8 +1,9 @@
// Generic response and authentication models
package eu.kanade.tachiyomi.extension.all.kavita.dto package eu.kanade.tachiyomi.extension.all.kavita.dto
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
@Serializable // Used to process login @Serializable
data class AuthenticationDto( data class AuthenticationDto(
val username: String, val username: String,
val token: String, val token: String,
@@ -20,9 +21,9 @@ data class PaginationInfo(
@Serializable @Serializable
data class ServerInfoDto( data class ServerInfoDto(
val installId: String, val installId: String,
val os: String, // val os: String,
val isDocker: Boolean, val isDocker: Boolean,
val dotnetVersion: String, // val dotnetVersion: String,
val kavitaVersion: String, val kavitaVersion: String,
val numOfCores: Int, // val numOfCores: Int,
) )