Initial commit

This commit is contained in:
arkon 2024-01-08 16:56:54 -05:00
commit 7849d19fc4
122 changed files with 8371 additions and 0 deletions

19
.editorconfig Normal file
View File

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

32
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,32 @@
**PLEASE READ THIS**
I acknowledge that:
- I have updated to the latest version of the app (stable is v0.15.1)
- 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
- 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**
---
## Device information
* Tachiyomi version: ?
* Android version: ?
* Device: ?
## Source information
* Source name: ?
* Source extension version: ?
## Steps to reproduce
1. First step
2. Second step
## Issue/Request
?
## Other details
Additional details and attachments.

View File

@ -0,0 +1,107 @@
name: 🐞 Issue report
description: Report a source issue in Tachiyomi
labels: [Bug]
body:
- type: input
id: source
attributes:
label: Source information
description: |
You can find the extension name and version in **Browse → Extensions**.
placeholder: |
Example: "Komga 1.3.18"
validations:
required: true
- type: input
id: language
attributes:
label: Source language
placeholder: |
Example: "English"
validations:
required: true
- type: textarea
id: reproduce-steps
attributes:
label: Steps to reproduce
description: Provide an example of the issue.
placeholder: |
Example:
1. First step
2. Second step
3. Issue here
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: Expected behavior
placeholder: |
Example:
"This should happen..."
validations:
required: true
- type: textarea
id: actual-behavior
attributes:
label: Actual behavior
placeholder: |
Example:
"This happened instead..."
validations:
required: true
- type: input
id: tachiyomi-version
attributes:
label: Tachiyomi version
description: |
You can find your Tachiyomi version in **More → About**.
placeholder: |
Example: "0.15.1"
validations:
required: true
- type: input
id: android-version
attributes:
label: Android version
description: |
You can find this somewhere in your Android settings.
placeholder: |
Example: "Android 11"
validations:
required: true
- type: textarea
id: other-details
attributes:
label: Other details
placeholder: |
Additional details and attachments.
- type: checkboxes
id: acknowledgements
attributes:
label: Acknowledgements
description: Your issue will be closed if you haven't done these steps.
options:
- label: I have searched the existing issues and this is a new ticket, **NOT** a duplicate or related to another open or closed issue.
required: true
- label: I have written a short but informative title.
required: true
- label: I have updated the app to version **[0.15.1](https://github.com/tachiyomiorg/tachiyomi/releases/latest)**.
required: true
- label: I have updated all installed extensions.
required: true
- label: I have tried the [troubleshooting guide](https://tachiyomi.org/help/guides/troubleshooting/).
required: true
- label: If this is an issue with the app itself, I should be opening an issue in the [app repository](https://github.com/tachiyomiorg/tachiyomi/issues/new/choose).
required: true
- label: I will fill out all of the requested information in this form.
required: true

View File

@ -0,0 +1,50 @@
name: ⭐ Feature request
description: Suggest a feature to improve an existing source
labels: [Feature request]
body:
- type: input
id: source
attributes:
label: Source name
description: |
You can find the extension name in **Browse → Extensions**.
placeholder: |
Example: "Komga"
validations:
required: true
- type: textarea
id: feature-description
attributes:
label: Describe your suggested feature
description: How can an existing extension be improved?
placeholder: |
Example:
"It should work like this..."
validations:
required: true
- type: textarea
id: other-details
attributes:
label: Other details
placeholder: |
Additional details and attachments.
- type: checkboxes
id: acknowledgements
attributes:
label: Acknowledgements
description: Your issue will be closed if you haven't done these steps.
options:
- label: I have searched the existing issues and this is a new ticket, **NOT** a duplicate or related to another open or closed issue.
required: true
- label: I have written a short but informative title.
required: true
- label: If this is an issue with the app itself, I should be opening an issue in the [app repository](https://github.com/tachiyomiorg/tachiyomi/issues/new/choose).
required: true
- label: I have updated the app to version **[0.15.1](https://github.com/tachiyomiorg/tachiyomi/releases/latest)**.
required: true
- label: I will fill out all of the requested information in this form.
required: true

View File

@ -0,0 +1,41 @@
name: 🧠 Meta request
description: Suggest improvements to the project
labels: [Meta request]
body:
- type: textarea
id: feature-description
attributes:
label: Describe why this should be added
description: How can the project be improved?
placeholder: |
Example:
"It should work like this..."
validations:
required: true
- type: textarea
id: other-details
attributes:
label: Other details
placeholder: |
Additional details and attachments.
- type: checkboxes
id: acknowledgements
attributes:
label: Acknowledgements
description: Your issue will be closed if you haven't done these steps.
options:
- label: I have searched the existing issues and this is a new ticket, **NOT** a duplicate or related to another open or closed issue.
required: true
- label: I have written a short but informative title.
required: true
- label: If this is an issue with the app itself, I should be opening an issue in the [app repository](https://github.com/tachiyomiorg/tachiyomi/issues/new/choose).
required: true
- label: I have updated the app to version **[0.15.1](https://github.com/tachiyomiorg/tachiyomi/releases/latest)**.
required: true
- label: I have updated all installed extensions.
required: true
- label: I will fill out all of the requested information in this form.
required: true

11
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: ⚠️ Application issue
url: https://github.com/tachiyomiorg/tachiyomi/issues/new/choose
about: Issues and requests about the app itself should be opened in the tachiyomi repository instead
- name: 📦 Tachiyomi extensions
url: https://tachiyomi.org/extensions
about: List of all available extensions with download links
- name: 🖥️ Tachiyomi website
url: https://tachiyomi.org/help/
about: Guides, troubleshooting, and answers to common questions

8
.github/pull_request_template.md vendored Normal file
View File

@ -0,0 +1,8 @@
Checklist:
- [ ] Updated `extVersionCode` value in `build.gradle` for individual extensions
- [ ] Referenced all related issues in the PR body (e.g. "Closes #xyz")
- [ ] Added the `isNsfw = true` flag in `build.gradle` when appropriate
- [ ] Have not changed source names
- [ ] 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

BIN
.github/readme-images/app-icon.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

8
.github/renovate.json vendored Normal file
View File

@ -0,0 +1,8 @@
{
"extends": [
"config:base"
],
"includePaths": [
".github/**"
]
}

17
.github/scripts/commit-repo.sh vendored Executable file
View File

@ -0,0 +1,17 @@
#!/bin/bash
set -e
rsync -a --delete --exclude .git --exclude .gitignore ../main/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/extensions@repo/index.min.json
else
echo "No changes to commit"
fi

62
.github/scripts/create-repo.sh vendored Executable file
View File

@ -0,0 +1,62 @@
#!/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[^']+")
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
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 sources "$SOURCE_INFO" \
'{name:$name, pkg:$pkg, apk:$apk, lang:$lang, code:$code, version:$version, nsfw:$nsfw, sources:$sources}'
done | jq -sr '[.[]]' > index.json
# Alternate minified copy
jq -c '.' < index.json > index.min.json
cat index.json

26
.github/scripts/move-apks.sh vendored Executable file
View File

@ -0,0 +1,26 @@
#!/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 "1" ]; 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

@ -0,0 +1,25 @@
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/extensions/issues/new/choose)."
close-issue-reason: not_planned
ascending: true
operations-per-run: 250

View File

@ -0,0 +1,31 @@
name: PR build check
on:
pull_request:
paths-ignore:
- '**.md'
- '.github/workflows/issue_moderator.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
build_individual:
name: Build individual modules
runs-on: ubuntu-latest
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
uses: gradle/gradle-build-action@v2
with:
arguments: assembleDebug
cache-read-only: true

98
.github/workflows/build_push.yml vendored Normal file
View File

@ -0,0 +1,98 @@
name: CI
on:
push:
branches:
- main
paths-ignore:
- '**.md'
- '.github/workflows/issue_moderator.yml'
concurrency:
group: ${{ github.workflow }}
cancel-in-progress: true
env:
CI_CHUNK_SIZE: 65
jobs:
build_individual:
name: Build individual modules
runs-on: ubuntu-latest
steps:
- name: Checkout main branch
uses: actions/checkout@v4
- name: Set up JDK
uses: actions/setup-java@v4
with:
java-version: 11
distribution: adopt
- name: Prepare signing key
run: |
echo ${{ secrets.SIGNING_KEY }} | base64 -d > signingkey.jks
- name: Build extensions (chunk ${{ matrix.chunk }})
uses: gradle/gradle-build-action@v2
env:
ALIAS: ${{ secrets.ALIAS }}
KEY_STORE_PASSWORD: ${{ secrets.KEY_STORE_PASSWORD }}
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
with:
arguments: assembleRelease
- name: Upload APKs
uses: actions/upload-artifact@v4
if: "github.repository == 'tachiyomiorg/extensions'"
with:
name: "individual-apks"
path: "**/*.apk"
retention-days: 1
- name: Clean up CI files
run: rm signingkey.jks
publish_repo:
name: Publish repo
needs:
- build_individual
if: "github.repository == 'tachiyomiorg/extensions'"
runs-on: ubuntu-latest
steps:
- name: Download APK artifacts
uses: actions/download-artifact@v4
with:
path: ~/apk-artifacts
- name: Set up JDK
uses: actions/setup-java@v4
with:
java-version: 17
distribution: adopt
- name: Checkout main branch
uses: actions/checkout@v4
with:
ref: main
path: main
- name: Create repo artifacts
run: |
cd main
./.github/scripts/move-apks.sh
INSPECTOR_LINK="$(curl -s "https://api.github.com/repos/tachiyomiorg/tachiyomi-extensions-inspector/releases/latest" | jq -r '.assets[0].browser_download_url')"
curl -L "$INSPECTOR_LINK" -o ./Inspector.jar
java -jar ./Inspector.jar "apk" "output.json" "tmp"
./.github/scripts/create-repo.sh
- name: Checkout repo branch
uses: actions/checkout@v4
with:
ref: repo
path: repo
- name: Deploy repo
run: |
cd repo
../main/.github/scripts/commit-repo.sh

52
.github/workflows/issue_moderator.yml vendored Normal file
View File

@ -0,0 +1,52 @@
name: Issue moderator
on:
issues:
types: [opened, edited, reopened]
issue_comment:
types: [created]
jobs:
autoclose:
runs-on: ubuntu-latest
steps:
- name: Moderate issues
uses: tachiyomiorg/issue-moderator-action@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
duplicate-label: Duplicate
duplicate-check-enabled: true
duplicate-check-labels: |
["Source request", "Domain changed"]
existing-check-enabled: true
existing-check-labels: |
["Source request", "Domain changed"]
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",
"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,
"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."
}
]
auto-close-ignore-label: do-not-autoclose

19
.github/workflows/lock.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: Lock threads
on:
# Daily
schedule:
- cron: '0 0 * * *'
# Manual trigger
workflow_dispatch:
inputs:
jobs:
lock:
runs-on: ubuntu-latest
steps:
- uses: dessant/lock-threads@v5
with:
github-token: ${{ github.token }}
issue-inactive-days: '2'
pr-inactive-days: '2'

12
.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
.gradle
/local.properties
/.idea/workspace.xml
.DS_Store
build/
/captures
.idea/
*.iml
repo/
apk/
gen
generated-src/

126
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,126 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community moderators are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community moderators have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community moderators responsible for enforcement at
the [Tachiyomi Discord server](https://discord.gg/tachiyomi).
All complaints will be reviewed and investigated promptly and fairly.
All community moderators are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community moderators will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community moderators, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/),
version 2.1, available at
[v2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html).
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
For answers to common questions about this code of conduct, see the FAQ at
[FAQ](https://www.contributor-covenant.org/faq). Translations are available
at [translations](https://www.contributor-covenant.org/translations).

606
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,606 @@
# 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 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/extensions/issues/new?assignees=&labels=Meta+request&template=request_meta.yml) or fixing it directly by submitting a Pull Request.
## Table of Contents
1. [Prerequisites](#prerequisites)
1. [Tools](#tools)
2. [Cloning the repository](#cloning-the-repository)
2. [Getting help](#getting-help)
3. [Writing an extension](#writing-an-extension)
1. [Setting up a new Gradle module](#setting-up-a-new-gradle-module)
2. [Core dependencies](#core-dependencies)
3. [Extension main class](#extension-main-class)
4. [Extension call flow](#extension-call-flow)
5. [Misc notes](#misc-notes)
6. [Advanced extension features](#advanced-extension-features)
4. [Running](#running)
5. [Debugging](#debugging)
1. [Android Debugger](#android-debugger)
2. [Logs](#logs)
3. [Inspecting network calls](#inspecting-network-calls)
4. [Using external network inspecting tools](#using-external-network-inspecting-tools)
6. [Building](#building)
7. [Submitting the changes](#submitting-the-changes)
1. [Pull Request checklist](#pull-request-checklist)
## 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.
- Basic [Android development](https://developer.android.com/)
- [Kotlin](https://kotlinlang.org/)
- Web scraping
- [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML)
- [CSS selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors)
- [OkHttp](https://square.github.io/okhttp/)
- [JSoup](https://jsoup.org/)
### Tools
- [Android Studio](https://developer.android.com/studio)
- Emulator or phone with developer options enabled and a recent version of Tachiyomi installed
- [Icon Generator](https://as280093.github.io/AndroidAssetStudio/icons-launcher.html)
### 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.
<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.
**Also make sure you are using the latest version of Git as many commands used here are pretty new.**
2. Do a partial clone.
```bash
git clone --filter=blob:none --sparse <fork-repo-url>
cd extensions/
```
3. Configure sparse checkout.
There are two modes of pattern matching. The default is cone (🔺) mode.
Cone mode enables significantly faster pattern matching for big monorepos
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
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.
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:
```bash
git sparse-checkout set --cone --sparse-index
# add project folders
git sparse-checkout add .run buildSrc core gradle lib
# add a single source
git sparse-checkout add src/<lang>/<source>
```
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
unless you fully understand how cone mode works, or you might break it.
To use the legacy non-cone mode, follow these steps:
```bash
# enable sparse checkout
git sparse-checkout set --no-cone
# edit sparse checkout filter
vim .git/info/sparse-checkout
# alternatively, if you have VS Code installed
code .git/info/sparse-checkout
```
Here's an example:
```bash
/*
!/src/*
# allow a single source
/src/<lang>/<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.
```bash
# add upstream
git remote add upstream <tachiyomiorg-repo-url>
# optionally disable push to upstream
git remote set-url --push upstream no_pushing
# ignore 'repo' branch of upstream
# option 1: use negative refspec
git config --add remote.upstream.fetch "^refs/heads/repo"
# option 2: fetch main only (ignore all other branches)
git config remote.upstream.fetch "+refs/heads/main:refs/remotes/upstream/main"
# update remotes
git remote update
# track main of upstream instead of fork
git branch main -u upstream/main
```
5. Useful configurations. (optional)
```bash
# prune obsolete remote branches on fetch
git config remote.origin.prune true
# fast-forward only when pulling main branch
git config pull.ff only
# Add an alias to sync main branch without fetching useless blobs.
# 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
# sparse rules, which makes the local repo accumulate unused files.
# Use `git sync-main` to avoid this. Be careful if you have changes
# on main branch, which is not a good practice.
git config alias.sync-main '!git switch main && git fetch upstream && git reset --keep FETCH_HEAD'
```
6. Later, if you change the sparse checkout filter, run `git sparse-checkout reapply`.
Read more on
[Git's object model](https://github.blog/2020-12-17-commits-are-snapshots-not-diffs/),
[partial clone](https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/),
[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/),
and [negative refspecs](https://github.blog/2020-10-19-git-2-29-released/#user-content-negative-refspecs).
</details>
## 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 extension code for examples.
## 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.
### 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.
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
By default, all individual extensions are loaded for local development.
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.
#### Extension file structure
The simplest extension structure looks like this:
```console
$ tree src/<lang>/<mysourcename>/
src/<lang>/<mysourcename>/
├── AndroidManifest.xml
├── build.gradle
├── res
│   ├── mipmap-hdpi
│   │   └── ic_launcher.png
│   ├── mipmap-mdpi
│   │   └── ic_launcher.png
│   ├── mipmap-xhdpi
│   │   └── ic_launcher.png
│   ├── mipmap-xxhdpi
│   │   └── ic_launcher.png
│   ├── mipmap-xxxhdpi
│   │   └── ic_launcher.png
│   └── web_hi_res_512.png
└── src
└── eu
└── kanade
└── tachiyomi
└── extension
└── <lang>
└── <mysourcename>
└── <MySourceName>.kt
13 directories, 9 files
```
#### AndroidManifest.xml
A minimal [Android manifest file](https://developer.android.com/guide/topics/manifest/manifest-intro) is needed for Android to recognize an 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).
#### build.gradle
Make sure that your new extension's `build.gradle` file follows the following structure:
```gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
ext {
extName = '<My source name>'
pkgNameSuffix = '<lang>.<mysourcename>'
extClass = '.<MySourceName>'
extVersionCode = 1
isNsfw = true
}
apply from: "$rootDir/common.gradle"
```
| Field | Description |
| ----- | ----------- |
| `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. |
| `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. |
| `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. |
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`.
### Core dependencies
#### 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/main/app/src/main/java/eu/kanade/tachiyomi/source). Referencing the actual implementation will help with understanding extensions' call flow.
#### DataImage library
[`lib-dataimage`](https://github.com/tachiyomiorg/extensions/tree/main/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/).
```gradle
dependencies {
implementation(project(':lib-dataimage'))
}
```
#### i18n library
[`lib-i18n`](https://github.com/tachiyomiorg/extensions/tree/main/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
dependencies {
implementation(project(':lib-i18n'))
}
```
#### Additional dependencies
If you find yourself needing additional functionality, you can add more dependencies to your `build.gradle` file.
Many of [the dependencies](https://github.com/tachiyomiorg/tachiyomi/blob/main/app/build.gradle.kts) from the main Tachiyomi app are exposed to extensions by default.
> [!NOTE]
> 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.
> [!IMPORTANT]
> 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).
### 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`.
| 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. |
| `HttpSource` | For online source, where requests are made using HTTP. |
| `ParsedHttpSource` | Similar to `HttpSource`, but has methods useful for scraping pages. |
#### Main class key variables
| Field | Description |
| ----- | ----------- |
| `name` | Name displayed in the "Sources" tab in Tachiyomi. |
| `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). |
| `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
#### Popular Manga
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.
- 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.
- 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
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
- Similar to popular manga, but should be fetching the latest entries from a source.
#### 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`.
- If search functionality is not available, return `Observable.just(MangasPage(emptyList(), false))`
- `getFilterList` will be called to get all filters and filter types.
##### 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/main/source-api/src/commonMain/kotlin/eu/kanade/tachiyomi/source/model/Filter.kt) and in the table below.
| 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.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.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.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.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.
The `Filter` classes can also be extended, so you can create new custom filters like the `UriPartFilter`:
```kotlin
open class UriPartFilter(displayName: String, private val vals: Array<Pair<String, String>>) :
Filter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) {
fun toUriPart() = vals[state].second
}
```
#### Manga Details
- 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`.
- `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.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/main/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.
- 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.
- **The list should be sorted descending by the source order**.
- `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.
- It defaults to the URL provided to the request in `mangaDetailsRequest`.
#### Chapter
- After a chapter list for the manga is fetched and the app is going to cache the data, `prepareNewChapter` will be called.
- `SChapter.date_upload` is the [UNIX Epoch time](https://en.wikipedia.org/wiki/Unix_time) **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
private fun parseDate(dateStr: String): Long {
return runCatching { DATE_FORMATTER.parse(dateStr)?.time }
.getOrNull() ?: 0L
}
companion object {
private val DATE_FORMATTER by lazy {
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.
- `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.
- It defaults to the URL provided to the request in `pageListRequest`.
#### Chapter Pages
- When user opens a chapter, `getPageList` will be called and it will return a list of `Page`s.
- While a chapter is open in the reader or is being downloaded, `fetchImageUrl` will be called to get URLs for each page of the manga if the `Page.imageUrl` is empty.
- If the source provides all the `Page.imageUrl`'s directly, you can fill them and let the `Page.url` empty, so the app will skip the `fetchImageUrl` source and call directly `fetchImage`.
- The `Page.url` and `Page.imageUrl` attributes **should be set as an absolute URL**.
- Chapter pages numbers start from `0`.
- The list of `Page`s should be returned already sorted, the `index` field is ignored.
### Misc notes
- Sometimes you may find no use for some inherited methods. If so just override them and throw exceptions: `throw UnsupportedOperationException("Not used.")`
- 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`).
- 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
#### URL intent filter
Extensions can define URL intent filters by defining it inside a custom `AndroidManifest.xml` file.
(Example TBD.)
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
$ 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
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.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`.
#### Renaming existing sources
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/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
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.
> [!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.
> [!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.
## Running
To make local development more convenient, you can use the following run configuration to launch Tachiyomi directly at the Browse panel:
![](https://i.imgur.com/STy0UFY.png)
If you're running a Preview or debug build of Tachiyomi:
```
-W -S -n eu.kanade.tachiyomi.debug/eu.kanade.tachiyomi.ui.main.MainActivity -a eu.kanade.tachiyomi.SHOW_CATALOGUES
```
And for a release build of Tachiyomi:
```
-W -S -n eu.kanade.tachiyomi/eu.kanade.tachiyomi.ui.main.MainActivity -a eu.kanade.tachiyomi.SHOW_CATALOGUES
```
> [!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
### Android Debugger
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.
Instead, once you've built and installed your extension on the target device, use `Attach Debugger to Android Process` to start debugging Tachiyomi.
![](https://i.imgur.com/muhXyfu.png)
### Logs
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.
### 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.
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.
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 Tachiyomi package name in the process list.
### 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`.
#### 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.
```console
Install the tool.
$ sudo pip3 install mitmproxy
Execute the web interface and the proxy.
$ mitmweb
```
Alternatively, you can also use the Docker image:
```
$ docker run --rm -it -p 8080:8080 \
-p 127.0.0.1:8081:8081 \
--web-host 0.0.0.0 \
mitmproxy/mitmproxy mitmweb
```
After installing and running, open your browser and navigate to http://127.0.0.1:8081.
#### 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:
```kotlin
package eu.kanade.tachiyomi.extension.en.mysource
import android.annotation.SuppressLint
import eu.kanade.tachiyomi.source.online.HttpSource
import okhttp3.OkHttpClient
import java.net.InetSocketAddress
import java.net.Proxy
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
class MySource : HttpSource() {
private fun OkHttpClient.Builder.ignoreAllSSLErrors(): OkHttpClient.Builder {
val naiveTrustManager = @SuppressLint("CustomX509TrustManager")
object : X509TrustManager {
override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
}
val insecureSocketFactory = SSLContext.getInstance("TLSv1.2").apply {
val trustAllCerts = arrayOf<TrustManager>(naiveTrustManager)
init(null, trustAllCerts, SecureRandom())
}.socketFactory
sslSocketFactory(insecureSocketFactory, naiveTrustManager)
hostnameVerifier { _, _ -> true }
return this
}
override val client: OkHttpClient = network.cloudflareClient.newBuilder()
.ignoreAllSSLErrors()
.proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress("10.0.2.2", 8080)))
.build()
}
```
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).
If all went well, you should see all requests and responses made by the source in the web interface of `mitmweb`.
## Building
APKs can be created in Android Studio via `Build > Build Bundle(s) / APK(s) > Build APK(s)` or `Build > Generate Signed Bundle / APK`.
## 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 `main`: 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.
> [!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.
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
- Update `extVersionCode` value in `build.gradle` for individual extensions
- Reference all related issues in the PR body (e.g. "Closes #xyz")
- Add the `isNsfw = true` flag in `build.gradle` when appropriate
- 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

202
LICENSE Normal file
View File

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

54
README.md Normal file
View File

@ -0,0 +1,54 @@
| Build | Support Server |
|-------|---------|
| [![CI](https://github.com/tachiyomiorg/extensions/workflows/CI/badge.svg?event=push)](https://github.com/tachiyomiorg/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) |
# ![app icon](./.github/readme-images/app-icon.png)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.
# Usage
Extension sources can be downloaded, installed, and uninstalled via the main Tachiyomi app. They are installed and uninstalled like regular apps, in `.apk` format.
## Downloads
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/extensions/tree/repo/apk).
# Requests
To request a new source or bug fix, [create an issue](https://github.com/tachiyomiorg/extensions/issues/new/choose).
Note that requesting something does not imply that something will be added or fixed in a timely fashion or at all since the work is volunteer-based. Furthermore, some sources may 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
Contributions are welcome!
Check out the repo's [issue backlog](https://github.com/tachiyomiorg/extensions/issues) for source requests and bug reports.
To get started with development, see [CONTRIBUTING.md](./CONTRIBUTING.md).
It might also be good to read our [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md).
## License
Copyright 2015 Javier Tomás
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
## Disclaimer
The developer of this application does not have any affiliation with the content providers available.

25
build.gradle.kts Normal file
View File

@ -0,0 +1,25 @@
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 {
repositories {
mavenCentral()
google()
maven(url = "https://jitpack.io")
}
}
tasks.register<Delete>("clean") {
delete(rootProject.layout.buildDirectory.asFile.get())
}

2
buildSrc/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.gradle/
build/

View File

@ -0,0 +1,7 @@
plugins {
`kotlin-dsl`
}
repositories {
mavenCentral()
}

View File

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

93
common.gradle Normal file
View File

@ -0,0 +1,93 @@
apply plugin: 'org.jmailen.kotlinter'
android {
compileSdkVersion AndroidConfig.compileSdk
namespace "eu.kanade.tachiyomi.extension"
sourceSets {
main {
manifest.srcFile "AndroidManifest.xml"
java.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
release {
manifest.srcFile "AndroidManifest.xml"
}
debug {
manifest.srcFile "AndroidManifest.xml"
}
}
defaultConfig {
minSdkVersion AndroidConfig.minSdk
targetSdkVersion AndroidConfig.targetSdk
applicationIdSuffix pkgNameSuffix
versionCode extVersionCode
versionName project.ext.properties.getOrDefault("libVersion", "1.4") + ".$extVersionCode"
setProperty("archivesBaseName", "tachiyomi-$pkgNameSuffix-v$versionName")
manifestPlaceholders = [
appName : "Tachiyomi: $extName",
extClass: extClass,
nsfw: project.ext.properties.getOrDefault("isNsfw", false) ? 1 : 0,
]
}
signingConfigs {
release {
storeFile rootProject.file("signingkey.jks")
storePassword System.getenv("KEY_STORE_PASSWORD")
keyAlias System.getenv("ALIAS")
keyPassword System.getenv("KEY_PASSWORD")
}
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled false
}
}
dependenciesInfo {
includeInApk = false
}
buildFeatures {
// Disable unused AGP features
aidl false
renderScript false
resValues false
shaders false
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
freeCompilerArgs += "-opt-in=kotlinx.serialization.ExperimentalSerializationApi"
}
kotlinter {
experimentalRules = true
disabledRules = [
"experimental:argument-list-wrapping", // Doesn't play well with Android Studio
"experimental:comment-wrapping",
]
}
}
repositories {
mavenCentral()
}
dependencies {
implementation(project(":core"))
compileOnly(libs.bundles.common)
}
preBuild.dependsOn(lintKotlin)
lintKotlin.dependsOn(formatKotlin)

13
core/AndroidManifest.xml Normal file
View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature android:name="tachiyomi.extension" />
<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.nsfw" android:value="${nsfw}" />
</application>
</manifest>

27
core/build.gradle.kts Normal file
View File

@ -0,0 +1,27 @@
plugins {
id("com.android.library")
}
android {
compileSdk = AndroidConfig.compileSdk
defaultConfig {
minSdk = AndroidConfig.minSdk
}
namespace = "eu.kanade.tachiyomi.extension"
@Suppress("UnstableApiUsage")
sourceSets {
named("main") {
manifest.srcFile("AndroidManifest.xml")
res.setSrcDirs(listOf("res"))
}
}
libraryVariants.all {
generateBuildConfigProvider?.configure {
enabled = false
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

23
gradle.properties Normal file
View File

@ -0,0 +1,23 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx6144m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
org.gradle.parallel=true
org.gradle.workers.max=5
org.gradle.caching=true
# Enable AndroidX dependencies
android.useAndroidX=true

28
gradle/libs.versions.toml Normal file
View File

@ -0,0 +1,28 @@
[versions]
kotlin_version = "1.7.21"
coroutines_version = "1.6.4"
serialization_version = "1.4.0"
[libraries]
gradle-agp = { module = "com.android.tools.build:gradle", version = "7.4.2" }
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-kotlinter = { module = "org.jmailen.gradle:kotlinter-gradle", version = "3.13.0" }
tachiyomi-lib = { module = "com.github.tachiyomiorg:extensions-lib", version = "1.4.2" }
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-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization_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" }
injekt-core = { module = "com.github.inorichi.injekt:injekt-core", version = "65b0440" }
rxjava = { module = "io.reactivex:rxjava", version = "1.3.8" }
jsoup = { module = "org.jsoup:jsoup", version = "1.15.1" }
okhttp = { module = "com.squareup.okhttp3:okhttp", version = "5.0.0-alpha.11" }
quickjs = { module = "app.cash.quickjs:quickjs-android", version = "0.9.2" }
[bundles]
common = ["kotlin-stdlib", "coroutines-core", "coroutines-android", "injekt-core", "rxjava", "kotlin-protobuf", "kotlin-json", "jsoup", "okhttp", "tachiyomi-lib", "quickjs"]

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

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

244
gradlew vendored Executable file
View File

@ -0,0 +1,244 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || 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.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored Normal file
View File

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

136
ktlintCodeStyle.xml Normal file
View File

@ -0,0 +1,136 @@
<code_scheme name="Project" version="173">
<JetCodeStyleSettings>
<option name="PACKAGES_TO_USE_STAR_IMPORTS">
<value>
<package name="kotlinx.android.synthetic" withSubpackages="true" static="false" />
</value>
</option>
<option name="NAME_COUNT_TO_USE_STAR_IMPORT" value="2147483647" />
<option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="2147483647" />
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings>
<codeStyleSettings language="XML">
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
<arrangement>
<rules>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:android</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:id</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>style</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
<order>ANDROID_ATTRIBUTE_ORDER</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>.*</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
<codeStyleSettings language="kotlin">
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
<option name="LINE_COMMENT_AT_FIRST_COLUMN" value="false" />
<option name="LINE_COMMENT_ADD_SPACE" value="true" />
<option name="KEEP_BLANK_LINES_IN_DECLARATIONS" value="1" />
<option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
<option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="0" />
<option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
</codeStyleSettings>
</code_scheme>

View File

@ -0,0 +1,22 @@
plugins {
id("com.android.library")
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

@ -0,0 +1,133 @@
package eu.kanade.tachiyomi.lib.cryptoaes
// Thanks to Vlad on Stackoverflow: https://stackoverflow.com/a/63701411
import android.util.Base64
import java.security.MessageDigest
import java.util.Arrays
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
/**
* Conforming with CryptoJS AES method
*/
object CryptoAES {
private const val KEY_SIZE = 256
private const val IV_SIZE = 128
private const val HASH_CIPHER = "AES/CBC/PKCS7PADDING"
private const val AES = "AES"
private const val KDF_DIGEST = "MD5"
/**
* Decrypt using CryptoJS defaults compatible method.
* Uses KDF equivalent to OpenSSL's EVP_BytesToKey function
*
* http://stackoverflow.com/a/29152379/4405051
* @param cipherText base64 encoded ciphertext
* @param password passphrase
*/
fun decrypt(cipherText: String, password: String): String {
return try {
val ctBytes = Base64.decode(cipherText, Base64.DEFAULT)
val saltBytes = Arrays.copyOfRange(ctBytes, 8, 16)
val cipherTextBytes = Arrays.copyOfRange(ctBytes, 16, ctBytes.size)
val md5: MessageDigest = MessageDigest.getInstance("MD5")
val keyAndIV = generateKeyAndIV(32, 16, 1, saltBytes, password.toByteArray(Charsets.UTF_8), md5)
decryptAES(cipherTextBytes,
keyAndIV?.get(0) ?: ByteArray(32),
keyAndIV?.get(1) ?: ByteArray(16))
} catch (e: Exception) {
""
}
}
/**
* Decrypt using CryptoJS defaults compatible method.
*
* @param cipherText base64 encoded ciphertext
* @param keyBytes key as a bytearray
* @param ivBytes iv as a bytearray
*/
fun decrypt(cipherText: String, keyBytes: ByteArray, ivBytes: ByteArray): String {
return try {
val cipherTextBytes = Base64.decode(cipherText, Base64.DEFAULT)
decryptAES(cipherTextBytes, keyBytes, ivBytes)
} catch (e: Exception) {
""
}
}
/**
* Decrypt using CryptoJS defaults compatible method.
*
* @param cipherTextBytes encrypted text as a bytearray
* @param keyBytes key as a bytearray
* @param ivBytes iv as a bytearray
*/
private fun decryptAES(cipherTextBytes: ByteArray, keyBytes: ByteArray, ivBytes: ByteArray): String {
return try {
val cipher = Cipher.getInstance(HASH_CIPHER)
val keyS = SecretKeySpec(keyBytes, AES)
cipher.init(Cipher.DECRYPT_MODE, keyS, IvParameterSpec(ivBytes))
cipher.doFinal(cipherTextBytes).toString(Charsets.UTF_8)
} catch (e: Exception) {
""
}
}
/**
* Generates a key and an initialization vector (IV) with the given salt and password.
*
* https://stackoverflow.com/a/41434590
* This method is equivalent to OpenSSL's EVP_BytesToKey function
* (see https://github.com/openssl/openssl/blob/main/crypto/evp/evp_key.c).
* By default, OpenSSL uses a single iteration, MD5 as the algorithm and UTF-8 encoded password data.
*
* @param keyLength the length of the generated key (in bytes)
* @param ivLength the length of the generated IV (in bytes)
* @param iterations the number of digestion rounds
* @param salt the salt data (8 bytes of data or `null`)
* @param password the password data (optional)
* @param md the message digest algorithm to use
* @return an two-element array with the generated key and IV
*/
@Suppress("SameParameterValue")
private fun generateKeyAndIV(keyLength: Int, ivLength: Int, iterations: Int, salt: ByteArray, password: ByteArray, md: MessageDigest): Array<ByteArray?>? {
val digestLength = md.digestLength
val requiredLength = (keyLength + ivLength + digestLength - 1) / digestLength * digestLength
val generatedData = ByteArray(requiredLength)
var generatedLength = 0
return try {
md.reset()
// Repeat process until sufficient data has been generated
while (generatedLength < keyLength + ivLength) {
// Digest data (last digest if available, password data, salt if available)
if (generatedLength > 0) md.update(generatedData, generatedLength - digestLength, digestLength)
md.update(password)
md.update(salt, 0, 8)
md.digest(generatedData, generatedLength, digestLength)
// additional rounds
for (i in 1 until iterations) {
md.update(generatedData, generatedLength, digestLength)
md.digest(generatedData, generatedLength, digestLength)
}
generatedLength += digestLength
}
// Copy key and IV into separate byte arrays
val result = arrayOfNulls<ByteArray>(2)
result[0] = generatedData.copyOfRange(0, keyLength)
if (ivLength > 0) result[1] = generatedData.copyOfRange(keyLength, keyLength + ivLength)
result
} catch (e: Exception) {
throw e
} finally {
// Clean out temporary data
Arrays.fill(generatedData, 0.toByte())
}
}
}

View File

@ -0,0 +1,73 @@
package eu.kanade.tachiyomi.lib.cryptoaes
/**
* Helper class to deobfuscate JavaScript strings encoded in JSFuck style.
*
* More info on JSFuck found [here](https://en.wikipedia.org/wiki/JSFuck).
*
* Currently only supports Numeric and decimal ('.') characters
*/
object Deobfuscator {
fun deobfuscateJsPassword(inputString: String): String {
var idx = 0
val brackets = listOf('[', '(')
val evaluatedString = StringBuilder()
while (idx < inputString.length) {
val chr = inputString[idx]
if (chr !in brackets) {
idx++
continue
}
val closingIndex = getMatchingBracketIndex(idx, inputString)
if (chr == '[') {
val digit = calculateDigit(inputString.substring(idx, closingIndex))
evaluatedString.append(digit)
} else {
evaluatedString.append('.')
if (inputString.getOrNull(closingIndex + 1) == '[') {
val skippingIndex = getMatchingBracketIndex(closingIndex + 1, inputString)
idx = skippingIndex + 1
continue
}
}
idx = closingIndex + 1
}
return evaluatedString.toString()
}
private fun getMatchingBracketIndex(openingIndex: Int, inputString: String): Int {
val openingBracket = inputString[openingIndex]
val closingBracket = when (openingBracket) {
'[' -> ']'
else -> ')'
}
var counter = 0
for (idx in openingIndex until inputString.length) {
if (inputString[idx] == openingBracket) counter++
if (inputString[idx] == closingBracket) counter--
if (counter == 0) return idx // found matching bracket
if (counter < 0) return -1 // unbalanced brackets
}
return -1 // matching bracket not found
}
private fun calculateDigit(inputSubString: String): Char {
/* 0 == '+[]'
1 == '+!+[]'
2 == '!+[]+!+[]'
3 == '!+[]+!+[]+!+[]'
...
therefore '!+[]' count equals the digit
if count equals 0, check for '+[]' just to be sure
*/
val digit = "!\\+\\[]".toRegex().findAll(inputSubString).count() // matches '!+[]'
if (digit == 0) {
if ("\\+\\[]".toRegex().findAll(inputSubString).count() == 1) { // matches '+[]'
return '0'
}
} else if (digit in 1..9) {
return digit.digitToChar()
}
return '-' // Illegal digit
}
}

View File

@ -0,0 +1,24 @@
plugins {
id("com.android.library")
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

@ -0,0 +1,65 @@
package eu.kanade.tachiyomi.lib.dataimage
import android.util.Base64
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import org.jsoup.nodes.Element
/**
* If a source provides images via a data:image string instead of a URL, use these functions and interceptor
*/
/**
* Use if the attribute tag could have a data:image string or URL
* Transforms data:image in to a fake URL that OkHttp won't die on
*/
fun Element.dataImageAsUrl(attr: String): String {
return if (this.attr(attr).startsWith("data")) {
"https://127.0.0.1/?" + this.attr(attr).substringAfter(":")
} else {
this.attr("abs:$attr")
}
}
/**
* Use if the attribute tag has a data:image string but real URLs are on a different attribute
*/
fun Element.dataImageAsUrlOrNull(attr: String): String? {
return if (this.attr(attr).startsWith("data")) {
"https://127.0.0.1/?" + this.attr(attr).substringAfter(":")
} else {
null
}
}
/**
* Interceptor that detects the URLs we created with the above functions, base64 decodes the data if necessary,
* and builds a response with a valid image that Tachiyomi can display
*/
class DataImageInterceptor : Interceptor {
private val mediaTypePattern = Regex("""(^[^;,]*)[;,]""")
override fun intercept(chain: Interceptor.Chain): Response {
val url = chain.request().url.toString()
return if (url.startsWith("https://127.0.0.1/?image")) {
val dataString = url.substringAfter("?")
val byteArray = if (dataString.contains("base64")) {
Base64.decode(dataString.substringAfter("base64,"), Base64.DEFAULT)
} else {
dataString.substringAfter(",").toByteArray()
}
val mediaType = mediaTypePattern.find(dataString)!!.value.toMediaTypeOrNull()
Response.Builder().body(byteArray.toResponseBody(mediaType))
.request(chain.request())
.protocol(Protocol.HTTP_1_0)
.code(200)
.message("")
.build()
} else {
chain.proceed(chain.request())
}
}
}

22
lib/i18n/build.gradle.kts Normal file
View File

@ -0,0 +1,22 @@
plugins {
id("com.android.library")
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,93 @@
package eu.kanade.tachiyomi.lib.i18n
import org.jetbrains.annotations.PropertyKey
import java.io.InputStreamReader
import java.text.Collator
import java.util.Locale
import java.util.PropertyResourceBundle
/**
* A simple wrapper to make internationalization easier to use in sources.
*
* Message files should be put in the `assets/i18n` folder, with the name
* `messages_{iso_639_1}.properties`, where `iso_639_1` should be using
* snake case and be in lowercase.
*
* To edit the strings, use the official JetBrain's
* [Resource Bundle Editor plugin](https://plugins.jetbrains.com/plugin/17035-resource-bundle-editor).
*
* Make sure to configure Android Studio to save Properties files as UTF-8 as well.
* You can refer to this [documentation](https://www.jetbrains.com/help/idea/properties-files.html#1cbc434e)
* on how to do so.
*/
class Intl(
language: String,
availableLanguages: Set<String>,
private val baseLanguage: String,
private val classLoader: ClassLoader,
private val createMessageFileName: (String) -> String = { createDefaultMessageFileName(it) }
) {
val chosenLanguage: String = when (language) {
in availableLanguages -> language
else -> baseLanguage
}
private val locale: Locale = Locale.forLanguageTag(chosenLanguage)
val collator: Collator = Collator.getInstance(locale)
private val baseBundle: PropertyResourceBundle by lazy { createBundle(baseLanguage) }
private val bundle: PropertyResourceBundle by lazy {
if (chosenLanguage == baseLanguage) baseBundle else createBundle(chosenLanguage)
}
/**
* Returns the string from the message file. If the [key] is not present
* in the current language, the English value will be returned. If the [key]
* is also not present in English, the [key] surrounded by brackets will be returned.
*/
@Suppress("InvalidBundleOrProperty")
operator fun get(@PropertyKey(resourceBundle = "i18n.messages") key: String): String = when {
bundle.containsKey(key) -> bundle.getString(key)
baseBundle.containsKey(key) -> baseBundle.getString(key)
else -> "[$key]"
}
/**
* Uses the string as a format string and returns a string obtained by
* substituting the specified arguments, using the instance locale.
*/
@Suppress("InvalidBundleOrProperty")
fun format(@PropertyKey(resourceBundle = "i18n.messages") key: String, vararg args: Any?) =
get(key).format(locale, *args)
fun languageDisplayName(localeCode: String): String =
Locale.forLanguageTag(localeCode)
.getDisplayName(locale)
.replaceFirstChar { if (it.isLowerCase()) it.titlecase(locale) else it.toString() }
/**
* Creates a [PropertyResourceBundle] instance from the language specified.
* The expected message file will be loaded from the `res/raw`.
*
* The [PropertyResourceBundle] is used directly instead of [java.util.ResourceBundle]
* because the later has issues with UTF-8 files in Java 8, which would need
* the message files to be saved in ISO-8859-1, making the file readability bad.
*/
private fun createBundle(lang: String): PropertyResourceBundle {
val fileName = createMessageFileName(lang)
val fileContent = classLoader.getResourceAsStream(fileName)
return PropertyResourceBundle(InputStreamReader(fileContent, "UTF-8"))
}
companion object {
fun createDefaultMessageFileName(lang: String): String {
val langSnakeCase = lang.replace("-", "_").lowercase()
return "assets/i18n/messages_$langSnakeCase.properties"
}
}
}

View File

@ -0,0 +1,23 @@
plugins {
id("com.android.library")
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

@ -0,0 +1,121 @@
package eu.kanade.tachiyomi.lib.randomua
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.NetworkHelper
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import uy.kohesive.injekt.injectLazy
import java.io.IOException
private class RandomUserAgentInterceptor(
private val userAgentType: UserAgentType,
private val customUA: String?,
private val filterInclude: List<String>,
private val filterExclude: List<String>,
) : Interceptor {
private var userAgent: String? = null
private val json: Json by injectLazy()
private val network: NetworkHelper by injectLazy()
private val client = network.client
override fun intercept(chain: Interceptor.Chain): Response {
try {
val originalRequest = chain.request()
val newUserAgent = getUserAgent()
?: return chain.proceed(originalRequest)
val originalHeaders = originalRequest.headers
val modifiedHeaders = originalHeaders.newBuilder()
.set("User-Agent", newUserAgent)
.build()
return chain.proceed(
originalRequest.newBuilder()
.headers(modifiedHeaders)
.build()
)
} catch (e: Exception) {
throw IOException(e.message)
}
}
private fun getUserAgent(): String? {
if (userAgentType == UserAgentType.OFF) {
return customUA?.ifBlank { null }
}
if (!userAgent.isNullOrEmpty()) return userAgent
val uaResponse = client.newCall(GET(UA_DB_URL)).execute()
if (!uaResponse.isSuccessful) {
uaResponse.close()
return null
}
val userAgentList = uaResponse.use { json.decodeFromString<UserAgentList>(it.body.string()) }
return when (userAgentType) {
UserAgentType.DESKTOP -> userAgentList.desktop
UserAgentType.MOBILE -> userAgentList.mobile
else -> error("Expected UserAgentType.DESKTOP or UserAgentType.MOBILE but got UserAgentType.${userAgentType.name} instead")
}
.filter {
filterInclude.isEmpty() || filterInclude.any { filter ->
it.contains(filter, ignoreCase = true)
}
}
.filterNot {
filterExclude.any { filter ->
it.contains(filter, ignoreCase = true)
}
}
.randomOrNull()
.also { userAgent = it }
}
companion object {
private const val UA_DB_URL = "https://tachiyomiorg.github.io/user-agents/user-agents.json"
}
}
/**
* Helper function to add a latest random user agent interceptor.
* The interceptor will added at the first position in the chain,
* so the CloudflareInterceptor in the app will be able to make usage of it.
*
* @param userAgentType User Agent type one of (DESKTOP, MOBILE, OFF)
* @param customUA Optional custom user agent used when userAgentType is OFF
* @param filterInclude Filter to only include User Agents containing these strings
* @param filterExclude Filter to exclude User Agents containing these strings
*/
fun OkHttpClient.Builder.setRandomUserAgent(
userAgentType: UserAgentType,
customUA: String? = null,
filterInclude: List<String> = emptyList(),
filterExclude: List<String> = emptyList(),
) = apply {
interceptors().add(0, RandomUserAgentInterceptor(userAgentType, customUA, filterInclude, filterExclude))
}
enum class UserAgentType {
MOBILE,
DESKTOP,
OFF
}
@Serializable
private data class UserAgentList(
val desktop: List<String>,
val mobile: List<String>
)

View File

@ -0,0 +1,70 @@
package eu.kanade.tachiyomi.lib.randomua
import android.content.SharedPreferences
import android.widget.Toast
import androidx.preference.EditTextPreference
import androidx.preference.ListPreference
import androidx.preference.PreferenceScreen
import okhttp3.Headers
/**
* Helper function to return UserAgentType based on SharedPreference value
*/
fun SharedPreferences.getPrefUAType(): UserAgentType {
return when (getString(PREF_KEY_RANDOM_UA, "off")) {
"mobile" -> UserAgentType.MOBILE
"desktop" -> UserAgentType.DESKTOP
else -> UserAgentType.OFF
}
}
/**
* Helper function to return custom UserAgent from SharedPreference
*/
fun SharedPreferences.getPrefCustomUA(): String? {
return getString(PREF_KEY_CUSTOM_UA, null)
}
/**
* Helper function to add Random User-Agent settings to SharedPreference
*
* @param screen, PreferenceScreen from `setupPreferenceScreen`
*/
fun addRandomUAPreferenceToScreen(
screen: PreferenceScreen,
) {
ListPreference(screen.context).apply {
key = PREF_KEY_RANDOM_UA
title = TITLE_RANDOM_UA
entries = RANDOM_UA_ENTRIES
entryValues = RANDOM_UA_VALUES
summary = "%s"
setDefaultValue("off")
}.also(screen::addPreference)
EditTextPreference(screen.context).apply {
key = PREF_KEY_CUSTOM_UA
title = TITLE_CUSTOM_UA
summary = CUSTOM_UA_SUMMARY
setOnPreferenceChangeListener { _, newValue ->
try {
Headers.Builder().add("User-Agent", newValue as String).build()
true
} catch (e: IllegalArgumentException) {
Toast.makeText(screen.context, "User Agent invalid${e.message}", Toast.LENGTH_LONG).show()
false
}
}
}.also(screen::addPreference)
}
const val TITLE_RANDOM_UA = "Random User-Agent (Requires Restart)"
const val PREF_KEY_RANDOM_UA = "pref_key_random_ua_"
val RANDOM_UA_ENTRIES = arrayOf("OFF", "Desktop", "Mobile")
val RANDOM_UA_VALUES = arrayOf("off", "desktop", "mobile")
const val TITLE_CUSTOM_UA = "Custom User-Agent (Requires Restart)"
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)"

View File

@ -0,0 +1,22 @@
plugins {
id("com.android.library")
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

@ -0,0 +1,42 @@
package eu.kanade.tachiyomi.lib.synchrony
import app.cash.quickjs.QuickJs
/**
* Helper class to deobfuscate JavaScript strings with synchrony.
*/
object Deobfuscator {
fun deobfuscateScript(source: String): String? {
val originalScript = javaClass.getResource("/assets/$SCRIPT_NAME")
?.readText() ?: return null
// Sadly needed until QuickJS properly supports module imports:
// Regex for finding one and two in "export{one as Deobfuscator,two as Transformer};"
val regex = """export\{(.*) as Deobfuscator,(.*) as Transformer\};""".toRegex()
val synchronyScript = regex.find(originalScript)?.let { match ->
val (deob, trans) = match.destructured
val replacement = "const Deobfuscator = $deob, Transformer = $trans;"
originalScript.replace(match.value, replacement)
} ?: return null
return QuickJs.create().use { engine ->
engine.evaluate("globalThis.console = { log: () => {}, warn: () => {}, error: () => {}, trace: () => {} };")
engine.evaluate(synchronyScript)
engine.set(
"source", TestInterface::class.java,
object : TestInterface {
override fun getValue() = source
},
)
engine.evaluate("new Deobfuscator().deobfuscateSource(source.getValue())") as? String
}
}
private interface TestInterface {
fun getValue(): String
}
}
// Update this when the script is updated!
private const val SCRIPT_NAME = "synchrony-v2.4.2.1.js"

View File

@ -0,0 +1,23 @@
plugins {
id("com.android.library")
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

@ -0,0 +1,125 @@
package eu.kanade.tachiyomi.lib.textinterceptor
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.text.Html
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.io.ByteArrayOutputStream
class TextInterceptor : Interceptor {
// With help from:
// https://github.com/tachiyomiorg/extensions/pull/13304#issuecomment-1234532897
// 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 {
val request = chain.request()
val url = request.url
if (url.host != HOST) return chain.proceed(request)
val creator = textFixer("Author's Notes from ${url.pathSegments[0]}")
val story = textFixer(url.pathSegments[1])
// Heading
val paintHeading = TextPaint().apply {
color = Color.BLACK
textSize = HEADING_FONT_SIZE
typeface = Typeface.DEFAULT_BOLD
isAntiAlias = true
}
@Suppress("DEPRECATION")
val heading = StaticLayout(
creator, paintHeading, (WIDTH - 2 * X_PADDING).toInt(),
Layout.Alignment.ALIGN_NORMAL, SPACING_MULT, SPACING_ADD, true
)
// Body
val paintBody = TextPaint().apply {
color = Color.BLACK
textSize = BODY_FONT_SIZE
typeface = Typeface.DEFAULT
isAntiAlias = true
}
@Suppress("DEPRECATION")
val body = StaticLayout(
story, paintBody, (WIDTH - 2 * X_PADDING).toInt(),
Layout.Alignment.ALIGN_NORMAL, SPACING_MULT, SPACING_ADD, true
)
// Image building
val imgHeight: Int = (heading.height + body.height + 2 * Y_PADDING).toInt()
val bitmap: Bitmap = Bitmap.createBitmap(WIDTH, imgHeight, Bitmap.Config.ARGB_8888)
Canvas(bitmap).apply {
drawColor(Color.WHITE)
heading.draw(this, X_PADDING, Y_PADDING)
body.draw(this, X_PADDING, Y_PADDING + heading.height.toFloat())
}
// Image converting & returning
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream)
val responseBody = stream.toByteArray().toResponseBody("image/png".toMediaType())
return Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_1)
.code(200)
.message("OK")
.body(responseBody)
.build()
}
@SuppressLint("ObsoleteSdkInt")
private fun textFixer(htmlString: String): String {
return if (Build.VERSION.SDK_INT >= 24) {
Html.fromHtml(htmlString , Html.FROM_HTML_MODE_LEGACY).toString()
} else {
@Suppress("DEPRECATION")
Html.fromHtml(htmlString).toString()
}
}
@Suppress("SameParameterValue")
private fun StaticLayout.draw(canvas: Canvas, x: Float, y: Float) {
canvas.save()
canvas.translate(x, y)
this.draw(canvas)
canvas.restore()
}
}
object TextInterceptorHelper {
const val HOST = "tachiyomi-lib-textinterceptor"
fun createUrl(creator: String, text: String): String {
return "http://$HOST/" + Uri.encode(creator) + "/" + Uri.encode(text)
}
}

View File

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

View File

@ -0,0 +1,34 @@
package eu.kanade.tachiyomi.lib.unpacker
/**
* A helper class to extract substrings efficiently.
*
* Note that all methods move [startIndex] over the ending delimiter.
*/
class SubstringExtractor(private val text: String) {
private var startIndex = 0
fun skipOver(str: String) {
val index = text.indexOf(str, startIndex)
if (index == -1) return
startIndex = index + str.length
}
fun substringBefore(str: String): String {
val index = text.indexOf(str, startIndex)
if (index == -1) return ""
val result = text.substring(startIndex, index)
startIndex = index + str.length
return result
}
fun substringBetween(left: String, right: String): String {
val index = text.indexOf(left, startIndex)
if (index == -1) return ""
val leftIndex = index + left.length
val rightIndex = text.indexOf(right, leftIndex)
if (rightIndex == -1) return ""
startIndex = rightIndex + right.length
return text.substring(leftIndex, rightIndex)
}
}

View File

@ -0,0 +1,76 @@
package eu.kanade.tachiyomi.lib.unpacker
/**
* Helper class to unpack JavaScript code compressed by [packer](http://dean.edwards.name/packer/).
*
* Source code of packer can be found [here](https://github.com/evanw/packer/blob/main/packer.js).
*/
object Unpacker {
/**
* Unpacks JavaScript code compressed by packer.
*
* Specify [left] and [right] to unpack only the data between them.
*
* Note: single quotes `\'` in the data will be replaced with double quotes `"`.
*/
fun unpack(script: String, left: String? = null, right: String? = null): String =
unpack(SubstringExtractor(script), left, right)
/**
* Unpacks JavaScript code compressed by packer.
*
* Specify [left] and [right] to unpack only the data between them.
*
* Note: single quotes `\'` in the data will be replaced with double quotes `"`.
*/
fun unpack(script: SubstringExtractor, left: String? = null, right: String? = null): String {
val packed = script
.substringBetween("}('", ".split('|'),0,{}))")
.replace("\\'", "\"")
val parser = SubstringExtractor(packed)
val data: String
if (left != null && right != null) {
data = parser.substringBetween(left, right)
parser.skipOver("',")
} else {
data = parser.substringBefore("',")
}
if (data.isEmpty()) return ""
val dictionary = parser.substringBetween("'", "'").split("|")
val size = dictionary.size
return wordRegex.replace(data) {
val key = it.value
val index = parseRadix62(key)
if (index >= size) return@replace key
dictionary[index].ifEmpty { key }
}
}
private val wordRegex by lazy { Regex("""\w+""") }
private fun parseRadix62(str: String): Int {
var result = 0
for (ch in str.toCharArray()) {
result = result * 62 + when {
ch.code <= '9'.code -> { // 0-9
ch.code - '0'.code
}
ch.code >= 'a'.code -> { // a-z
// ch - 'a' + 10
ch.code - ('a'.code - 10)
}
else -> { // A-Z
// ch - 'A' + 36
ch.code - ('A'.code - 36)
}
}
}
return result
}
}

41
settings.gradle.kts Normal file
View File

@ -0,0 +1,41 @@
include(":core")
// Load all modules under /lib
File(rootDir, "lib").eachDir {
val libName = it.name
include(":lib-$libName")
project(":lib-$libName").projectDir = File("lib/$libName")
}
if (System.getenv("CI") == null) {
// Local development (full project build)
/**
* Add or remove modules to load as needed for local development here.
*/
loadAllIndividualExtensions()
// loadIndividualExtension("all", "komga")
} else {
// Running in CI (GitHub Actions)
loadAllIndividualExtensions()
}
fun loadAllIndividualExtensions() {
File(rootDir, "src").eachDir { dir ->
dir.eachDir { subdir ->
val name = ":extensions:individual:${dir.name}:${subdir.name}"
include(name)
project(name).projectDir = File("src/${dir.name}/${subdir.name}")
}
}
}
fun loadIndividualExtension(lang: String, name: String) {
val projectName = ":extensions:individual:$lang:$name"
include(projectName)
project(projectName).projectDir = File("src/${lang}/${name}")
}
fun File.eachDir(block: (File) -> Unit) {
listFiles()?.filter { it.isDirectory }?.forEach { block(it) }
}

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest />

View File

@ -0,0 +1,93 @@
## 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

37
src/all/kavita/README.md Normal file
View File

@ -0,0 +1,37 @@
# Kavita
Table of Content
- [FAQ](#FAQ)
- [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)
- [The Kavita extension stopped working?](#the-kavita-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 test the Kavita extension before setting up my own server?](#can-i-test-the-kavita-extension-before-setting-up-my-own-server)
- [Guides](#Guides)
- [How do I add my Kavita server to Tachiyomi?](#how-do-i-add-my-kavita-server-to-tachiyomi)
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
### Why do I see no manga?
Kavita is a self-hosted comic/manga media server.
### Where can I get more information about Kavita?
You can visit the [Kavita](https://www.kavitareader.com/) website for for more information.
### The Kavita extension stopped working?
Make sure that your Kavita server and extension are on the newest version.
### Can I add more than one Kavita server or user?
Yes, currently you can add up to 3 different Kavita instances to Tachiyomi.
### Can I test the Kavita 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`.
## Guides
### How do I add my Kavita server to Tachiyomi?
Go into the settings of the Kavita extension from the Extension tab in Browse and fill in your OPDS url.

View File

@ -0,0 +1,18 @@
login_errors_failed_login=Login failed. Something went wrong
login_errors_header_token_empty="Error: The JSON Web Token is empty.\nTry opening the extension first."
login_errors_invalid_url=Invalid URL:
login_errors_parse_tokendto=There was an error parsing the auth token
pref_customsource_title=Displayed name for source
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_title=Default filters shown
pref_opds_badformed_url=Incorrect OPDS address. Please copy it from User settings \u2192 3rd party apps \u2192 OPDS URL
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_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.
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.
version_exceptions_smart_filter=Could not decode SmartFilter. Ensure you are using Kavita version 0.7.11 or later.
http_errors_500=Something went wrong
http_errors_401=There was an error logging in. Try again or reload the app

View File

@ -0,0 +1,18 @@
pref_customsource_title=Nombre de la instancia
pref_edit_customsource_summary=Aqui puedes cambiar el nombre de la instancia.\nPuedes escribir un nombre descriptivo que identifique esta url/instancia
restartapp_settings=Reinicia la aplicación para aplicar los cambios
version_exceptions_chapters_parse=Algo ha ido mal al procesar los capitulos. Envia los registros de fallo a los desarrolladores de Kavita
check_version=Comprueba que tienes tanto Kavita como la extension actualizada. (Version minima: 0.7.8)\nSi el problema persiste, reportalo a los desarrolladores de Kavita aportando los registros de fallo.
version_exceptions_smart_filter=Fallo al decodificar los filtros inteligentes. Aseg\u00FArate que estas al menos en la version 0.7.11 de Kavita
http_errors_500=Algo ha ido mal
http_errors_401=Ha habido un error al iniciar sesi\u00F3n. Prueba otra vez o reinicia la aplicaci\u00F3n
pref_opds_summary=La url del OPDS copiada de la configuraci\u00F3n del usuario. Debe incluir la direcci\u00F3n y la clave api al final.
pref_filters_summary=Mostrar estos filtros en la lista de filtros
pref_filters_title=Filtros por defecto
pref_opds_badformed_url=La direcci\u00F3n OPDS no es correcta. Por favor, c\u00F3piela desde la Configuraci\u00F3n de usuario-> aplicaciones de terceros -> url de OPDS
login_errors_parse_tokendto=Se ha producido un error al procesar el token de autenticaci\u00F3n
pref_opds_duplicated_source_url=Url est\u00E1 configurado en una fuente diferente ->
pref_opds_must_setup_address=Debe configurar la direcci\u00F3n para comunicarse con Kavita
login_errors_failed_login=Error en el inicio de sesi\u00F3n. Algo ha ido mal
login_errors_header_token_empty="Error: el token jwt est\u00E1 vac\u00EDo.\nIntente abrir primero la extensi\u00F3n"
login_errors_invalid_url=URL no v\u00E1lida:

View File

@ -0,0 +1,20 @@
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
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_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
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_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
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.
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
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
login_errors_header_token_empty=\u00AB\u00A0Erreur\u202F: le jeton jwt est vide.\nEssayez d'abord d'ouvrir l'extension\u00A0\u00BB
login_errors_invalid_url=URL invalide\u202F:
http_errors_401=Il y a eu une erreur. Essayez de nouveau ou rechargez l'application

View File

@ -0,0 +1,21 @@
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.
restartapp_settings=Ny innstilling trer i kraft n\u00E5r du starter Tachiyomi p\u00E5 ny.
duplicated_source_url=Nettadressen er satt opp i en annen Kavita-instans
pref_filters_summary=Vis disse filterne i filterlisten
pref_filters_title=Forvalgte filtre valgt
login_errors_parse_tokendto=Kunne ikke tolke identifiseringssymbolet
login_errors_failed_login=Innlogging mislyktes. Noe gikk galt.
http_errors_500=Noe gikk galt
login_errors_header_token_empty="Feil: JSON-nettsymbol er tomt.\nPr\u00F8v \u00E5 \u00E5pne utvidelsen f\u00F8rst."
login_errors_invalid_url=Ugyldig nettadresse:
version_exceptions_chapters_parse=Uh\u00E5ndtert unntak i tolking av kapitler. Send loggene dine til Kavita-utviklerne.
version_exceptions_smart_filter=Kunne ikke dekode smartfilter. Forsikre deg om at du bruker Kavita versjon 0.7.11 eller nyere.
pref_opds_summary=OPDS-nettadressen kopiert fra brukerinnstillingene. Denne skal inkludere med adressen og slutte med API-n\u00F8kkelen.
check_version=Forsikre deg om at b\u00E5de utvidelsen og Kavita er av nyeste versjon. (Ihvertfall 0.7.8)\nHvis problemet vedvarer kan du rapportere det til Kavita-utviklerne med tilh\u00F8rende loggf\u00F8ring.
pref_opds_badformed_url=OPDS-adressen er ikke riktig. Kopier den fra brukerinnstillinger -> tredjepartsprogrammer -> OPDS-nettadresse
pref_opds_duplicated_source_url=Nettadressen er satt opp i en annen instans ->
pref_opds_must_setup_address=Du m\u00E5 sette opp adressen som skal kommunisere med Kavita
http_errors_401=Feil med innlogging. Pr\u00F8v \u00E5 laste inn p\u00E5 ny, eller start programmet p\u00E5 ny.

View File

@ -0,0 +1,17 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlinx-serialization'
ext {
extName = 'Kavita'
pkgNameSuffix = 'all.kavita'
extClass = '.KavitaFactory'
extVersionCode = 13
}
dependencies {
implementation 'info.debatty:java-string-similarity:2.0.0'
implementation(project(':lib-i18n'))
}
apply from: "$rootDir/common.gradle"

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

View File

@ -0,0 +1,112 @@
package eu.kanade.tachiyomi.extension.all.kavita
import eu.kanade.tachiyomi.extension.all.kavita.KavitaConstants.noSmartFilterSelected
import eu.kanade.tachiyomi.source.model.Filter
class UserRating :
Filter.Select<String>(
"Minimum Rating",
arrayOf(
"Any",
"1 star",
"2 stars",
"3 stars",
"4 stars",
"5 stars",
),
)
class SmartFiltersFilter(smartFilters: Array<String>) :
Filter.Select<String>("Smart Filters", arrayOf(noSmartFilterSelected) + smartFilters)
class SortFilter(sortables: Array<String>) : Filter.Sort("Sort by", sortables, Selection(0, true))
val sortableList = listOf(
Pair("Sort name", 1),
Pair("Created", 2),
Pair("Last modified", 3),
Pair("Item added", 4),
Pair("Time to Read", 5),
Pair("Release year", 6),
)
class StatusFilter(name: String) : Filter.CheckBox(name, false)
class StatusFilterGroup(filters: List<StatusFilter>) :
Filter.Group<StatusFilter>("Status", filters)
class ReleaseYearRange(name: String) : Filter.Text(name)
class ReleaseYearRangeGroup(filters: List<ReleaseYearRange>) :
Filter.Group<ReleaseYearRange>("Release Year", filters)
class GenreFilter(name: String) : Filter.TriState(name)
class GenreFilterGroup(genres: List<GenreFilter>) :
Filter.Group<GenreFilter>("Genres", genres)
class TagFilter(name: String) : Filter.TriState(name)
class TagFilterGroup(tags: List<TagFilter>) : Filter.Group<TagFilter>("Tags", tags)
class AgeRatingFilter(name: String) : Filter.TriState(name)
class AgeRatingFilterGroup(ageRatings: List<AgeRatingFilter>) :
Filter.Group<AgeRatingFilter>("Age Rating", ageRatings)
class FormatFilter(name: String) : Filter.CheckBox(name, false)
class FormatsFilterGroup(formats: List<FormatFilter>) :
Filter.Group<FormatFilter>("Formats", formats)
class CollectionFilter(name: String) : Filter.TriState(name)
class CollectionFilterGroup(collections: List<CollectionFilter>) :
Filter.Group<CollectionFilter>("Collection", collections)
class LanguageFilter(name: String) : Filter.TriState(name)
class LanguageFilterGroup(languages: List<LanguageFilter>) :
Filter.Group<LanguageFilter>("Language", languages)
class LibraryFilter(library: String) : Filter.TriState(library)
class LibrariesFilterGroup(libraries: List<LibraryFilter>) :
Filter.Group<LibraryFilter>("Libraries", libraries)
class PubStatusFilter(name: String) : Filter.CheckBox(name, false)
class PubStatusFilterGroup(status: List<PubStatusFilter>) :
Filter.Group<PubStatusFilter>("Publication Status", status)
class PeopleHeaderFilter(name: String) :
Filter.Header(name)
class PeopleSeparatorFilter :
Filter.Separator()
class WriterPeopleFilter(name: String) : Filter.CheckBox(name, false)
class WriterPeopleFilterGroup(peoples: List<WriterPeopleFilter>) :
Filter.Group<WriterPeopleFilter>("Writer", peoples)
class PencillerPeopleFilter(name: String) : Filter.CheckBox(name, false)
class PencillerPeopleFilterGroup(peoples: List<PencillerPeopleFilter>) :
Filter.Group<PencillerPeopleFilter>("Penciller", peoples)
class InkerPeopleFilter(name: String) : Filter.CheckBox(name, false)
class InkerPeopleFilterGroup(peoples: List<InkerPeopleFilter>) :
Filter.Group<InkerPeopleFilter>("Inker", peoples)
class ColoristPeopleFilter(name: String) : Filter.CheckBox(name, false)
class ColoristPeopleFilterGroup(peoples: List<ColoristPeopleFilter>) :
Filter.Group<ColoristPeopleFilter>("Colorist", peoples)
class LettererPeopleFilter(name: String) : Filter.CheckBox(name, false)
class LettererPeopleFilterGroup(peoples: List<LettererPeopleFilter>) :
Filter.Group<LettererPeopleFilter>("Letterer", peoples)
class CoverArtistPeopleFilter(name: String) : Filter.CheckBox(name, false)
class CoverArtistPeopleFilterGroup(peoples: List<CoverArtistPeopleFilter>) :
Filter.Group<CoverArtistPeopleFilter>("Cover Artist", peoples)
class EditorPeopleFilter(name: String) : Filter.CheckBox(name, false)
class EditorPeopleFilterGroup(peoples: List<EditorPeopleFilter>) :
Filter.Group<EditorPeopleFilter>("Editor", peoples)
class PublisherPeopleFilter(name: String) : Filter.CheckBox(name, false)
class PublisherPeopleFilterGroup(peoples: List<PublisherPeopleFilter>) :
Filter.Group<PublisherPeopleFilter>("Publisher", peoples)
class CharacterPeopleFilter(name: String) : Filter.CheckBox(name, false)
class CharacterPeopleFilterGroup(peoples: List<CharacterPeopleFilter>) :
Filter.Group<CharacterPeopleFilter>("Character", peoples)
class TranslatorPeopleFilter(name: String) : Filter.CheckBox(name, false)
class TranslatorPeopleFilterGroup(peoples: List<TranslatorPeopleFilter>) :
Filter.Group<TranslatorPeopleFilter>("Translator", peoples)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,81 @@
package eu.kanade.tachiyomi.extension.all.kavita
object KavitaConstants {
// toggle filters
const val toggledFiltersPref = "toggledFilters"
val filterPrefEntries = arrayOf(
"Sort Options",
"Format",
"Libraries",
"Read Status",
"Genres",
"Tags",
"Collections",
"Languages",
"Publication Status",
"Rating",
"Age Rating",
"Writers",
"Penciller",
"Inker",
"Colorist",
"Letterer",
"Cover Artist",
"Editor",
"Publisher",
"Character",
"Translators",
"ReleaseYearRange",
)
val filterPrefEntriesValue = arrayOf(
"Sort Options",
"Format",
"Libraries",
"Read Status",
"Genres",
"Tags",
"Collections",
"Languages",
"Publication Status",
"Rating",
"Age Rating",
"Writers",
"Penciller",
"Inker",
"Colorist",
"Letterer",
"CoverArtist",
"Editor",
"Publisher",
"Character",
"Translators",
"ReleaseYearRange",
)
val defaultFilterPrefEntries = setOf(
"Sort Options",
"Format",
"Libraries",
"Read Status",
"Genres",
"Tags",
"Collections",
"Languages",
"Publication Status",
"Rating",
"Age Rating",
"Writers",
"Penciller",
"Inker",
"Colorist",
"Letterer",
"CoverArtist",
"Editor",
"Publisher",
"Character",
"Translators",
"ReleaseYearRange",
)
const val customSourceNamePref = "customSourceName"
const val noSmartFilterSelected = "No smart filter loaded"
}

View File

@ -0,0 +1,13 @@
package eu.kanade.tachiyomi.extension.all.kavita
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceFactory
class KavitaFactory : SourceFactory {
override fun createSources(): List<Source> =
listOf(
Kavita("1"),
Kavita("2"),
Kavita("3"),
)
}

View File

@ -0,0 +1,141 @@
package eu.kanade.tachiyomi.extension.all.kavita
import eu.kanade.tachiyomi.extension.all.kavita.dto.ChapterDto
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.VolumeDto
import eu.kanade.tachiyomi.lib.i18n.Intl
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Response
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
class KavitaHelper {
val json = Json {
isLenient = true
ignoreUnknownKeys = true
allowSpecialFloatingPointValues = true
useArrayPolymorphism = true
prettyPrint = true
}
inline fun <reified T : Enum<T>> safeValueOf(type: String): T {
return java.lang.Enum.valueOf(T::class.java, type)
}
val dateFormatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSS", Locale.US)
.apply { timeZone = TimeZone.getTimeZone("UTC") }
fun parseDate(dateAsString: String): Long =
dateFormatter.parse(dateAsString)?.time ?: 0
fun hasNextPage(response: Response): Boolean {
val paginationHeader = response.header("Pagination")
var hasNextPage = false
if (!paginationHeader.isNullOrEmpty()) {
val paginationInfo = json.decodeFromString<PaginationInfo>(paginationHeader)
hasNextPage = paginationInfo.currentPage + 1 > paginationInfo.totalPages
}
return !hasNextPage
}
fun getIdFromUrl(url: String): Int {
return url.split("/").last().toInt()
}
fun createSeriesDto(obj: SeriesDto, baseUrl: String, apiKey: String): SManga =
SManga.create().apply {
url = "$baseUrl/Series/${obj.id}"
title = obj.name
// Deprecated: description = obj.summary
thumbnail_url = "$baseUrl/image/series-cover?seriesId=${obj.id}&apiKey=$apiKey"
}
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 chapterFromObject(obj: ChapterDto): SChapter = SChapter.create().apply {
url = obj.id.toString()
name = if (obj.number == "0" && obj.isSpecial) {
// This is a special. Chapter name is special name
obj.range
} else {
val cleanedName = obj.title.replaceFirst("^0+(?!$)".toRegex(), "")
"Chapter $cleanedName"
}
date_upload = parseDate(obj.created)
chapter_number = obj.number.toFloat()
scanlator = "${obj.pages} pages"
}
fun chapterFromVolume(obj: ChapterDto, volume: VolumeDto): SChapter =
SChapter.create().apply {
// If there are multiple chapters to this volume, then prefix with Volume number
if (volume.chapters.isNotEmpty() && obj.number != "0") {
// This volume is not volume 0, hence they are not loose chapters
// We just add a nice Volume X to the chapter title
// Chapter-based Volume
name = "Volume ${volume.number} Chapter ${obj.number}"
chapter_number = obj.number.toFloat()
} else if (obj.number == "0") {
// Both specials and volume has chapter number 0
if (volume.number == 0) {
// Treat as special
// Special is not in a volume
if (obj.range == "") {
// Special does not have any Title
name = "Chapter 0"
chapter_number = obj.number.toFloat()
} else {
// We use it's own special tile
name = obj.range
chapter_number = obj.number.toFloat()
}
} else {
// Is a single-file volume
// We encode the chapter number to support tracking
name = "Volume ${volume.number}"
chapter_number = volume.number.toFloat() / 10000
}
} else {
name = "Unhandled Else Volume ${volume.number}"
}
url = obj.id.toString()
date_upload = parseDate(obj.created)
scanlator = "${obj.pages} pages"
}
val intl = Intl(
language = Locale.getDefault().toString(),
baseLanguage = "en",
availableLanguages = KavitaInt.AVAILABLE_LANGS,
classLoader = this::class.java.classLoader!!,
createMessageFileName = { lang ->
when (lang) {
KavitaInt.SPANISH_LATAM -> Intl.createDefaultMessageFileName(KavitaInt.SPANISH)
else -> Intl.createDefaultMessageFileName(lang)
}
},
)
}

View File

@ -0,0 +1,17 @@
package eu.kanade.tachiyomi.extension.all.kavita
object KavitaInt {
const val ENGLISH = "en"
const val SPANISH = "es_ES"
const val SPANISH_LATAM = "es-419"
const val FRENCH = "fr_FR"
const val NORWEGIAN = "nb_NO"
val AVAILABLE_LANGS = setOf(
ENGLISH,
SPANISH,
SPANISH_LATAM,
NORWEGIAN,
FRENCH,
)
const val KAVITA_NAME = "Kavita"
}

View File

@ -0,0 +1,124 @@
package eu.kanade.tachiyomi.extension.all.kavita.dto
import kotlinx.serialization.Serializable
import kotlin.Triple
@Serializable
data class FilterV2Dto(
val id: Int? = null,
val name: String? = null,
val statements: MutableList<FilterStatementDto> = mutableListOf(),
val combination: Int = 0, // FilterCombination = FilterCombination.And,
val sortOptions: SortOptions = SortOptions(),
val limitTo: Int = 0,
) {
fun addStatement(comparison: FilterComparison, field: FilterField, value: String) {
if (value.isNotBlank()) {
statements.add(FilterStatementDto(comparison.type, field.type, value))
}
}
fun addStatement(comparison: FilterComparison, field: FilterField, values: java.util.ArrayList<out Any>) {
if (values.isNotEmpty()) {
statements.add(FilterStatementDto(comparison.type, field.type, values.joinToString(",")))
}
}
fun addContainsNotTriple(list: List<Triple<FilterField, java.util.ArrayList<out Any>, ArrayList<Int>>>) {
list.map {
addStatement(FilterComparison.Contains, it.first, it.second)
addStatement(FilterComparison.NotContains, it.first, it.third)
}
}
fun addPeople(list: List<Pair<FilterField, ArrayList<Int>>>) {
list.map {
addStatement(FilterComparison.MustContains, it.first, it.second)
}
}
}
@Serializable
data class FilterStatementDto(
// todo: Create custom serializator for comparison and field and remove .type extension in Kavita.kt
val comparison: Int,
val field: Int,
val value: String,
)
@Serializable
enum class SortFieldEnum(val type: Int) {
SortName(1),
CreatedDate(2),
LastModifiedDate(3),
LastChapterAdded(4),
TimeToRead(5),
ReleaseYear(6),
;
companion object {
private val map = SortFieldEnum.values().associateBy(SortFieldEnum::type)
fun fromInt(type: Int) = map[type]
}
}
@Serializable
data class SortOptions(
var sortField: Int = SortFieldEnum.SortName.type,
var isAscending: Boolean = true,
)
@Serializable
enum class FilterCombination {
Or,
And,
}
@Serializable
enum class FilterField(val type: Int) {
Summary(0),
SeriesName(1),
PublicationStatus(2),
Languages(3),
AgeRating(4),
UserRating(5),
Tags(6),
CollectionTags(7),
Translators(8),
Characters(9),
Publisher(10),
Editor(11),
CoverArtist(12),
Letterer(13),
Colorist(14),
Inker(15),
Penciller(16),
Writers(17),
Genres(18),
Libraries(19),
ReadProgress(20),
Formats(21),
ReleaseYear(22),
ReadTime(23),
Path(24),
FilePath(25),
}
@Serializable
enum class FilterComparison(val type: Int) {
Equal(0),
GreaterThan(1),
GreaterThanEqual(2),
LessThan(3),
LessThanEqual(4),
Contains(5),
MustContains(6),
Matches(7),
NotContains(8),
NotEqual(9),
BeginsWith(10),
EndsWith(11),
IsBefore(12),
IsAfter(13),
IsInLast(14),
IsNotInLast(15),
}

View File

@ -0,0 +1,103 @@
package eu.kanade.tachiyomi.extension.all.kavita.dto
import kotlinx.serialization.Serializable
@Serializable
enum class MangaFormat(val format: Int) {
Image(0),
Archive(1),
Unknown(2),
Epub(3),
Pdf(4),
;
companion object {
private val map = PersonRole.values().associateBy(PersonRole::role)
fun fromInt(type: Int) = map[type]
}
}
enum class PersonRole(val role: Int) {
Other(1),
Writer(3),
Penciller(4),
Inker(5),
Colorist(6),
Letterer(7),
CoverArtist(8),
Editor(9),
Publisher(10),
Character(11),
Translator(12),
;
companion object {
private val map = PersonRole.values().associateBy(PersonRole::role)
fun fromInt(type: Int) = map[type]
}
}
@Serializable
data class SeriesDto(
val id: Int,
val name: String,
val originalName: String = "",
val thumbnail_url: String? = "",
val localizedName: String? = "",
val sortName: String? = "",
val pages: Int,
val coverImageLocked: Boolean = true,
val pagesRead: Int,
val userRating: Float,
val userReview: String? = "",
val format: Int,
val created: String? = "",
val libraryId: Int,
val libraryName: String? = "",
)
@Serializable
data class SeriesMetadataDto(
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,
)
@Serializable
data class VolumeDto(
val id: Int,
val number: Int,
val name: String,
val pages: Int,
val pagesRead: Int,
val lastModified: String,
val created: String,
val seriesId: Int,
val chapters: List<ChapterDto> = emptyList(),
)
@Serializable
data class ChapterDto(
val id: Int,
val range: String,
val number: String,
val pages: Int,
val isSpecial: Boolean,
val title: String,
val pagesRead: Int,
val coverImageLocked: Boolean,
val volumeId: Int,
val created: String,
)

View File

@ -0,0 +1,104 @@
package eu.kanade.tachiyomi.extension.all.kavita.dto
import kotlinx.serialization.Serializable
/**
* This file contains all class for filtering
* */
@Serializable
data class MetadataGenres(
val id: Int,
val title: String,
)
@Serializable
data class MetadataPeople(
val id: Int,
val name: String,
val role: Int,
)
@Serializable
data class MetadataPubStatus(
val value: Int,
val title: String,
)
@Serializable
data class MetadataTag(
val id: Int,
val title: String,
)
@Serializable
data class MetadataAgeRatings(
val value: Int,
val title: String,
)
@Serializable
data class MetadataLanguages(
val isoCode: String,
val title: String,
)
@Serializable
data class MetadataLibrary(
val id: Int,
val name: String,
val type: Int,
)
@Serializable
data class MetadataCollections(
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
data class SmartFilter(
val id: Int,
val name: String,
val filter: String,
)

View File

@ -0,0 +1,28 @@
package eu.kanade.tachiyomi.extension.all.kavita.dto
import kotlinx.serialization.Serializable
@Serializable // Used to process login
data class AuthenticationDto(
val username: String,
val token: String,
val apiKey: String,
)
@Serializable
data class PaginationInfo(
val currentPage: Int,
val itemsPerPage: Int,
val totalItems: Int,
val totalPages: Int,
)
@Serializable
data class ServerInfoDto(
val installId: String,
val os: String,
val isDocker: Boolean,
val dotnetVersion: String,
val kavitaVersion: String,
val numOfCores: Int,
)

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest />

383
src/all/komga/CHANGELOG.md Normal file
View File

@ -0,0 +1,383 @@
## 1.4.47
Minimum Komga version required: `0.151.0`
### Feat
* add support for AVIF and HEIF image types
## 1.4.46
Minimum Komga version required: `0.151.0`
### Feat
* Update to extension-lib 1.4
- Clicking on chapter WebView should now open the chapter/book page.
## 1.3.45
Minimum Komga version required: `0.151.0`
### Feat
* Edit source display name
## 1.3.44
Minimum Komga version required: `0.151.0`
### Fix
* Better date/time parsing
## 1.3.43
Minimum Komga version required: `0.151.0`
### Fix
* Requests failing if address preference is saved with a trailing slash
### Features
* Add URL validation in the address preferences
* Use a URL-focused keyboard when available while editing the address preferences
## 1.3.42
Minimum Komga version required: `0.151.0`
### Fix
* default sort broken since Komga 0.155.1
* proper sort criteria for readlists
## 1.3.41
Minimum Komga version required: `0.151.0`
### Features
* Improve how the status is displayed
## 1.3.40
Minimum Komga version required: `0.151.0`
### Features
* Exclude from bulk update warnings
## 1.2.39
Minimum Komga version required: `0.151.0`
### Features
* Prepend series name in front of books within readlists
## 1.2.38
Minimum Komga version required: `0.113.0`
### Features
* Add `README.md`
## 1.2.37
Minimum Komga version required: `0.113.0`
### Features
* In app link to `CHANGELOG.md`
## 1.2.36
Minimum Komga version required: `0.113.0`
### Features
* Don't request conversion for JPEG XL images
## 1.2.35
Minimum Komga version required: `0.113.0`
### Features
* Display the Translators of a book in the scanlator chapter field
## 1.2.34
Minimum Komga version required: `0.113.0`
### Fix
* Loading of filter values could fail in some cases
## 1.2.33
Minimum Komga version required: `0.113.0`
### Fix
* Open in WebView and Share options now open regular browser link instead of showing JSON
* Note that Komga cannot be viewed using System WebView since there is no login prompt
However, opening in a regular browser works.
## 1.2.32
Minimum Komga version required: `0.113.0`
### Fix
* Source language, conventionally set to "en", is now changed to "all"
* Downloaded files, if any, will have to be moved to new location
- `Komga (EN)` to `Komga (ALL)`
- `Komga (3) (EN)` to `Komga (3) (ALL)`
## 1.2.31
Minimum Komga version required: `0.113.0`
### Refactor
* replace Gson with kotlinx.serialization
## 1.2.30
Minimum Komga version required: `0.113.0`
### Features
* display read list summary
* display aggregated tags on series
* search series by book tags
## 1.2.29
Minimum Komga version required: `0.97.0`
### Features
* filter deleted series and books
## 1.2.28
Minimum Komga version required: `0.97.0`
### Fix
* incorrect User Agent
## 1.2.27
Minimum Komga version required: `0.97.0`
### Fix
* filter series by read or in progress
## 1.2.26
Minimum Komga version required: `0.87.4`
### Fix
* show series with only in progress books when searching for unread only
## 1.2.25
Minimum Komga version required: `0.87.4`
### Fix
* sort order for read list books
## 1.2.24
Minimum Komga version required: `0.87.4`
### Fix
* only show series tags in the filter panel
* set URL properly on series and read lists, so restoring from a backup can work properly
## 1.2.23
Minimum Komga version required: `0.75.0`
### Features
* ignore DNS over HTTPS so it can reach IP addresses
## 1.2.22
Minimum Komga version required: `0.75.0`
### Features
* add error logs and better catch exceptions
## 1.2.21
Minimum Komga version required: `0.75.0`
### Features
* browse read lists (from the filter menu)
* filter by collection, respecting the collection's ordering
## 1.2.20
Minimum Komga version required: `0.75.0`
### Features
* filter by authors, grouped by role
## 1.2.19
Minimum Komga version required: `0.68.0`
### Features
* display Series authors
* display Series summary from books if no summary exists for Series
## 1.2.18
Minimum Komga version required: `0.63.2`
### Fix
* use metadata.releaseDate or fileLastModified for chapter date
## 1.2.17
Minimum Komga version required: `0.63.2`
### Fix
* list of collections for filtering could be empty in some conditions
## 1.2.16
Minimum Komga version required: `0.59.0`
### Features
* filter by genres, tags and publishers
## 1.2.15
Minimum Komga version required: `0.56.0`
### Features
* remove the 1000 chapters limit
* display series description and tags (genres + tags)
## 1.2.14
Minimum Komga version required: `0.41.0`
### Features
* change chapter display name to use the display number instead of the sort number
## 1.2.13
Minimum Komga version required: `0.41.0`
### Features
* compatibility for the upcoming version of Komga which have changes in the API (IDs are String instead of Long)
## 1.2.12
Minimum Komga version required: `0.41.0`
### Features
* filter by collection
## 1.2.11
Minimum Komga version required: `0.35.2`
### Features
* Set password preferences inputTypes
## 1.2.10
Minimum Komga version required: `0.35.2`
### Features
* unread only filter (closes gotson/komga#180)
* prefix book titles with number (closes gotson/komga#169)
## 1.2.9
Minimum Komga version required: `0.22.0`
### Features
* use SourceFactory to have multiple Komga servers (3 for the moment)
## 1.2.8
Minimum Komga version required: `0.22.0`
### Features
* use book metadata title for chapter display name
* use book metadata sort number for chapter number
## 1.2.7
### Features
* use series metadata title for display name
* filter on series status
## 1.2.6
### Features
* Add support for AndroidX preferences
## 1.2.5
### Features
* add sort options in filter
## 1.2.4
### Features
* better handling of authentication
## 1.2.3
### Features
* filters by library
## 1.2.2
### Features
* request converted image from server if format is not supported
## 1.2.1
### Features
* first version

35
src/all/komga/README.md Normal file
View File

@ -0,0 +1,35 @@
# Komga
Table of Content
- [FAQ](#FAQ)
- [Why do I see no manga?](#why-do-i-see-no-manga)
- [Where can I get more information about Komga?](#where-can-i-get-more-information-about-komga)
- [The Komga extension stopped working?](#the-komga-extension-stopped-working)
- [Can I add more than one Komga server or user?](#can-i-add-more-than-one-komga-server-or-user)
- [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)
- [How do I add my Komga server to Tachiyomi?](#how-do-i-add-my-komga-server-to-tachiyomi)
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)
## FAQ
### Why do I see no manga?
Komga is a self-hosted comic/manga media server.
### Where can I get more information about Komga?
You can visit the [Komga](https://komga.org/) website for for more information.
### The Komga extension stopped working?
Make sure that your Komga server and extension are on the newest version.
### Can I add more than one Komga server or user?
Yes, currently you can add up to 3 different Komga instances to Tachiyomi.
### Can I test the Komga extension before setting up my own server?
Yes, you can try it out with the DEMO server `https://demo.komga.org`, username `demo@komga.org` and password `komga-demo`.
## Guides
### How do I add my Komga server to Tachiyomi?
Go into the settings of the Komga extension from the Extension tab in Browse and fill in your server address and login details.

View File

@ -0,0 +1,12 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlinx-serialization'
ext {
extName = 'Komga'
pkgNameSuffix = 'all.komga'
extClass = '.KomgaFactory'
extVersionCode = 50
}
apply from: "$rootDir/common.gradle"

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

View File

@ -0,0 +1,637 @@
package eu.kanade.tachiyomi.extension.all.komga
import android.app.Application
import android.content.SharedPreferences
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.util.Log
import android.widget.Button
import android.widget.Toast
import androidx.preference.EditTextPreference
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.AppInfo
import eu.kanade.tachiyomi.extension.all.komga.dto.AuthorDto
import eu.kanade.tachiyomi.extension.all.komga.dto.BookDto
import eu.kanade.tachiyomi.extension.all.komga.dto.CollectionDto
import eu.kanade.tachiyomi.extension.all.komga.dto.LibraryDto
import eu.kanade.tachiyomi.extension.all.komga.dto.PageDto
import eu.kanade.tachiyomi.extension.all.komga.dto.PageWrapperDto
import eu.kanade.tachiyomi.extension.all.komga.dto.ReadListDto
import eu.kanade.tachiyomi.extension.all.komga.dto.SeriesDto
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservable
import eu.kanade.tachiyomi.network.await
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.source.UnmeteredSource
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Credentials
import okhttp3.Dns
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import rx.Single
import rx.schedulers.Schedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
import java.security.MessageDigest
import java.util.Locale
open class Komga(private val suffix: String = "") : ConfigurableSource, UnmeteredSource, HttpSource() {
override fun popularMangaRequest(page: Int): Request =
GET("$baseUrl/api/v1/series?page=${page - 1}&deleted=false&sort=metadata.titleSort,asc", headers)
override fun popularMangaParse(response: Response): MangasPage =
processSeriesPage(response)
override fun latestUpdatesRequest(page: Int): Request =
GET("$baseUrl/api/v1/series/latest?page=${page - 1}&deleted=false", headers)
override fun latestUpdatesParse(response: Response): MangasPage =
processSeriesPage(response)
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val collectionId = (filters.find { it is CollectionSelect } as? CollectionSelect)?.let {
it.values[it.state].id
}
val type = when {
collectionId != null -> "collections/$collectionId/series"
filters.find { it is TypeSelect }?.state == 1 -> "readlists"
else -> "series"
}
val url = "$baseUrl/api/v1/$type?search=$query&page=${page - 1}&deleted=false".toHttpUrlOrNull()!!.newBuilder()
filters.forEach { filter ->
when (filter) {
is UnreadFilter -> {
if (filter.state) {
url.addQueryParameter("read_status", "UNREAD")
url.addQueryParameter("read_status", "IN_PROGRESS")
}
}
is InProgressFilter -> {
if (filter.state) {
url.addQueryParameter("read_status", "IN_PROGRESS")
}
}
is ReadFilter -> {
if (filter.state) {
url.addQueryParameter("read_status", "READ")
}
}
is LibraryGroup -> {
val libraryToInclude = mutableListOf<String>()
filter.state.forEach { content ->
if (content.state) {
libraryToInclude.add(content.id)
}
}
if (libraryToInclude.isNotEmpty()) {
url.addQueryParameter("library_id", libraryToInclude.joinToString(","))
}
}
is StatusGroup -> {
val statusToInclude = mutableListOf<String>()
filter.state.forEach { content ->
if (content.state) {
statusToInclude.add(content.name.uppercase(Locale.ROOT))
}
}
if (statusToInclude.isNotEmpty()) {
url.addQueryParameter("status", statusToInclude.joinToString(","))
}
}
is GenreGroup -> {
val genreToInclude = mutableListOf<String>()
filter.state.forEach { content ->
if (content.state) {
genreToInclude.add(content.name)
}
}
if (genreToInclude.isNotEmpty()) {
url.addQueryParameter("genre", genreToInclude.joinToString(","))
}
}
is TagGroup -> {
val tagToInclude = mutableListOf<String>()
filter.state.forEach { content ->
if (content.state) {
tagToInclude.add(content.name)
}
}
if (tagToInclude.isNotEmpty()) {
url.addQueryParameter("tag", tagToInclude.joinToString(","))
}
}
is PublisherGroup -> {
val publisherToInclude = mutableListOf<String>()
filter.state.forEach { content ->
if (content.state) {
publisherToInclude.add(content.name)
}
}
if (publisherToInclude.isNotEmpty()) {
url.addQueryParameter("publisher", publisherToInclude.joinToString(","))
}
}
is AuthorGroup -> {
val authorToInclude = mutableListOf<AuthorDto>()
filter.state.forEach { content ->
if (content.state) {
authorToInclude.add(content.author)
}
}
authorToInclude.forEach {
url.addQueryParameter("author", "${it.name},${it.role}")
}
}
is Filter.Sort -> {
var sortCriteria = when (filter.state?.index) {
0 -> if (type == "series") "metadata.titleSort" else "name"
1 -> "createdDate"
2 -> "lastModifiedDate"
else -> ""
}
if (sortCriteria.isNotEmpty()) {
sortCriteria += "," + if (filter.state?.ascending!!) "asc" else "desc"
url.addQueryParameter("sort", sortCriteria)
}
}
else -> {}
}
}
return GET(url.toString(), headers)
}
override fun searchMangaParse(response: Response): MangasPage =
processSeriesPage(response)
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
return client.newCall(GET(manga.url, headers))
.asObservable()
.map { response ->
mangaDetailsParse(response).apply { initialized = true }
}
}
override fun mangaDetailsRequest(manga: SManga): Request =
GET(manga.url.replaceFirst("api/v1/", "", ignoreCase = true), headers)
override fun mangaDetailsParse(response: Response): SManga {
return response.body.use { body ->
if (response.fromReadList()) {
val readList = json.decodeFromString<ReadListDto>(body.string())
readList.toSManga()
} else {
val series = json.decodeFromString<SeriesDto>(body.string())
series.toSManga()
}
}
}
override fun chapterListRequest(manga: SManga): Request =
GET("${manga.url}/books?unpaged=true&media_status=READY&deleted=false", headers)
override fun chapterListParse(response: Response): List<SChapter> {
val responseBody = response.body
val page = responseBody.use { json.decodeFromString<PageWrapperDto<BookDto>>(it.string()).content }
val r = page.mapIndexed { index, book ->
SChapter.create().apply {
chapter_number = if (!response.fromReadList()) book.metadata.numberSort else index + 1F
name = "${if (!response.fromReadList()) "${book.metadata.number} - " else "${book.seriesTitle} ${book.metadata.number}: "}${book.metadata.title} (${book.size})"
url = "$baseUrl/api/v1/books/${book.id}"
scanlator = book.metadata.authors.groupBy({ it.role }, { it.name })["translator"]?.joinToString()
date_upload = book.metadata.releaseDate?.let { parseDate(it) }
?: parseDateTime(book.fileLastModified)
}
}
return r.sortedByDescending { it.chapter_number }
}
override fun pageListRequest(chapter: SChapter): Request =
GET("${chapter.url}/pages")
override fun pageListParse(response: Response): List<Page> {
val responseBody = response.body
val pages = responseBody.use { json.decodeFromString<List<PageDto>>(it.string()) }
return pages.map {
val url = "${response.request.url}/${it.number}" +
if (!supportedImageTypes.contains(it.mediaType)) {
"?convert=png"
} else {
""
}
Page(
index = it.number - 1,
imageUrl = url,
)
}
}
override fun getMangaUrl(manga: SManga) = manga.url.replace("/api/v1", "")
override fun getChapterUrl(chapter: SChapter) = chapter.url.replace("/api/v1/books", "/book")
private fun processSeriesPage(response: Response): MangasPage {
val responseBody = response.body
return responseBody.use { body ->
if (response.fromReadList()) {
with(json.decodeFromString<PageWrapperDto<ReadListDto>>(body.string())) {
MangasPage(content.map { it.toSManga() }, !last)
}
} else {
with(json.decodeFromString<PageWrapperDto<SeriesDto>>(body.string())) {
MangasPage(content.map { it.toSManga() }, !last)
}
}
}
}
private fun SeriesDto.toSManga(): SManga =
SManga.create().apply {
title = metadata.title
url = "$baseUrl/api/v1/series/$id"
thumbnail_url = "$url/thumbnail"
status = when {
metadata.status == "ENDED" && metadata.totalBookCount != null && booksCount < metadata.totalBookCount -> SManga.PUBLISHING_FINISHED
metadata.status == "ENDED" -> SManga.COMPLETED
metadata.status == "ONGOING" -> SManga.ONGOING
metadata.status == "ABANDONED" -> SManga.CANCELLED
metadata.status == "HIATUS" -> SManga.ON_HIATUS
else -> SManga.UNKNOWN
}
genre = (metadata.genres + metadata.tags + booksMetadata.tags).distinct().joinToString(", ")
description = metadata.summary.ifBlank { booksMetadata.summary }
booksMetadata.authors.groupBy { it.role }.let { map ->
author = map["writer"]?.map { it.name }?.distinct()?.joinToString()
artist = map["penciller"]?.map { it.name }?.distinct()?.joinToString()
}
}
private fun ReadListDto.toSManga(): SManga =
SManga.create().apply {
title = name
description = summary
url = "$baseUrl/api/v1/readlists/$id"
thumbnail_url = "$url/thumbnail"
status = SManga.UNKNOWN
}
private fun Response.fromReadList() = request.url.toString().contains("/api/v1/readlists")
private fun parseDate(date: String?): Long =
if (date == null) {
0
} else {
try {
KomgaHelper.formatterDate.parse(date)?.time ?: 0
} catch (ex: Exception) {
0
}
}
private fun parseDateTime(date: String?): Long =
if (date == null) {
0
} else {
try {
KomgaHelper.formatterDateTime.parse(date)?.time ?: 0
} catch (ex: Exception) {
try {
KomgaHelper.formatterDateTimeMilli.parse(date)?.time ?: 0
} catch (ex: Exception) {
0
}
}
}
override fun imageUrlParse(response: Response): String = ""
private class TypeSelect : Filter.Select<String>("Search for", arrayOf(TYPE_SERIES, TYPE_READLISTS))
private class LibraryFilter(val id: String, name: String) : Filter.CheckBox(name, false)
private class LibraryGroup(libraries: List<LibraryFilter>) : Filter.Group<LibraryFilter>("Libraries", libraries)
private class CollectionSelect(collections: List<CollectionFilterEntry>) : Filter.Select<CollectionFilterEntry>("Collection", collections.toTypedArray())
private class SeriesSort : Filter.Sort("Sort", arrayOf("Alphabetically", "Date added", "Date updated"), Selection(0, true))
private class StatusFilter(name: String) : Filter.CheckBox(name, false)
private class StatusGroup(filters: List<StatusFilter>) : Filter.Group<StatusFilter>("Status", filters)
private class UnreadFilter : Filter.CheckBox("Unread", false)
private class InProgressFilter : Filter.CheckBox("In Progress", false)
private class ReadFilter : Filter.CheckBox("Read", false)
private class GenreFilter(genre: String) : Filter.CheckBox(genre, false)
private class GenreGroup(genres: List<GenreFilter>) : Filter.Group<GenreFilter>("Genres", genres)
private class TagFilter(tag: String) : Filter.CheckBox(tag, false)
private class TagGroup(tags: List<TagFilter>) : Filter.Group<TagFilter>("Tags", tags)
private class PublisherFilter(publisher: String) : Filter.CheckBox(publisher, false)
private class PublisherGroup(publishers: List<PublisherFilter>) : Filter.Group<PublisherFilter>("Publishers", publishers)
private class AuthorFilter(val author: AuthorDto) : Filter.CheckBox(author.name, false)
private class AuthorGroup(role: String, authors: List<AuthorFilter>) : Filter.Group<AuthorFilter>(role, authors)
private data class CollectionFilterEntry(
val name: String,
val id: String? = null,
) {
override fun toString() = name
}
override fun getFilterList(): FilterList {
val filters = try {
mutableListOf<Filter<*>>(
UnreadFilter(),
InProgressFilter(),
ReadFilter(),
TypeSelect(),
CollectionSelect(listOf(CollectionFilterEntry("None")) + collections.map { CollectionFilterEntry(it.name, it.id) }),
LibraryGroup(libraries.map { LibraryFilter(it.id, it.name) }.sortedBy { it.name.lowercase(Locale.ROOT) }),
StatusGroup(listOf("Ongoing", "Ended", "Abandoned", "Hiatus").map { StatusFilter(it) }),
GenreGroup(genres.map { GenreFilter(it) }),
TagGroup(tags.map { TagFilter(it) }),
PublisherGroup(publishers.map { PublisherFilter(it) }),
).also { list ->
list.addAll(authors.map { (role, authors) -> AuthorGroup(role, authors.map { AuthorFilter(it) }) })
list.add(SeriesSort())
}
} catch (e: Exception) {
Log.e(LOG_TAG, "error while creating filter list", e)
emptyList()
}
return FilterList(filters)
}
private var libraries = emptyList<LibraryDto>()
private var collections = emptyList<CollectionDto>()
private var genres = emptySet<String>()
private var tags = emptySet<String>()
private var publishers = emptySet<String>()
private var authors = emptyMap<String, List<AuthorDto>>() // roles to list of authors
// keep the previous ID when lang was "en", so that preferences and manga bindings are not lost
override val id by lazy {
val key = "komga${if (suffix.isNotBlank()) " ($suffix)" else ""}/en/$versionId"
val bytes = MessageDigest.getInstance("MD5").digest(key.toByteArray())
(0..7).map { bytes[it].toLong() and 0xff shl 8 * (7 - it) }.reduce(Long::or) and Long.MAX_VALUE
}
private val displayName by lazy { preferences.displayName }
final override val baseUrl by lazy { preferences.baseUrl }
private val username by lazy { preferences.username }
private val password by lazy { preferences.password }
private val json: Json by injectLazy()
override fun headersBuilder(): Headers.Builder =
Headers.Builder()
.add("User-Agent", "TachiyomiKomga/${AppInfo.getVersionName()}")
private val preferences: SharedPreferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
}
override val name = "Komga${displayName.ifBlank { suffix }.let { if (it.isNotBlank()) " ($it)" else "" }}"
override val lang = "all"
override val supportsLatest = true
private val LOG_TAG = "extension.all.komga${if (suffix.isNotBlank()) ".$suffix" else ""}"
override val client: OkHttpClient =
network.client.newBuilder()
.authenticator { _, response ->
if (response.request.header("Authorization") != null) {
null // Give up, we've already failed to authenticate.
} else {
response.request.newBuilder()
.addHeader("Authorization", Credentials.basic(username, password))
.build()
}
}
.dns(Dns.SYSTEM) // don't use DNS over HTTPS as it breaks IP addressing
.build()
override fun setupPreferenceScreen(screen: PreferenceScreen) {
screen.addEditTextPreference(
title = "Source display name",
default = suffix,
summary = displayName.ifBlank { "Here you can change the source displayed suffix" },
key = PREF_DISPLAYNAME,
)
screen.addEditTextPreference(
title = "Address",
default = ADDRESS_DEFAULT,
summary = baseUrl.ifBlank { "The server address" },
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI,
validate = { it.toHttpUrlOrNull() != null },
validationMessage = "The URL is invalid or malformed",
key = PREF_ADDRESS,
)
screen.addEditTextPreference(
title = "Username",
default = USERNAME_DEFAULT,
summary = username.ifBlank { "The user account email" },
key = PREF_USERNAME,
)
screen.addEditTextPreference(
title = "Password",
default = PASSWORD_DEFAULT,
summary = if (password.isBlank()) "The user account password" else "*".repeat(password.length),
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD,
key = PREF_PASSWORD,
)
}
private fun PreferenceScreen.addEditTextPreference(
title: String,
default: String,
summary: String,
inputType: Int? = null,
validate: ((String) -> Boolean)? = null,
validationMessage: String? = null,
key: String = title,
) {
val preference = EditTextPreference(context).apply {
this.key = key
this.title = title
this.summary = summary
this.setDefaultValue(default)
dialogTitle = title
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 res = preferences.edit().putString(this.key, newValue as String).commit()
Toast.makeText(context, "Restart Tachiyomi to apply new setting.", Toast.LENGTH_LONG).show()
res
} catch (e: Exception) {
e.printStackTrace()
false
}
}
}
addPreference(preference)
}
private val SharedPreferences.displayName
get() = getString(PREF_DISPLAYNAME, "")!!
private val SharedPreferences.baseUrl
get() = getString(PREF_ADDRESS, ADDRESS_DEFAULT)!!.removeSuffix("/")
private val SharedPreferences.username
get() = getString(PREF_USERNAME, USERNAME_DEFAULT)!!
private val SharedPreferences.password
get() = getString(PREF_PASSWORD, PASSWORD_DEFAULT)!!
init {
if (baseUrl.isNotBlank()) {
Single.fromCallable {
try {
client.newCall(GET("$baseUrl/api/v1/libraries", headers)).execute().use { response ->
libraries = try {
val responseBody = response.body
responseBody.use { json.decodeFromString(it.string()) }
} catch (e: Exception) {
Log.e(LOG_TAG, "error while decoding JSON for libraries filter", e)
emptyList()
}
}
} catch (e: Exception) {
Log.e(LOG_TAG, "error while loading libraries for filters", e)
}
try {
client.newCall(GET("$baseUrl/api/v1/collections?unpaged=true", headers)).execute().use { response ->
collections = try {
val responseBody = response.body
responseBody.use { json.decodeFromString<PageWrapperDto<CollectionDto>>(it.string()).content }
} catch (e: Exception) {
Log.e(LOG_TAG, "error while decoding JSON for collections filter", e)
emptyList()
}
}
} catch (e: Exception) {
Log.e(LOG_TAG, "error while loading collections for filters", e)
}
try {
client.newCall(GET("$baseUrl/api/v1/genres", headers)).execute().use { response ->
genres = try {
val responseBody = response.body
responseBody.use { json.decodeFromString(it.string()) }
} catch (e: Exception) {
Log.e(LOG_TAG, "error while decoding JSON for genres filter", e)
emptySet()
}
}
} catch (e: Exception) {
Log.e(LOG_TAG, "error while loading genres for filters", e)
}
try {
client.newCall(GET("$baseUrl/api/v1/tags", headers)).execute().use { response ->
tags = try {
response.body.use { json.decodeFromString(it.string()) }
} catch (e: Exception) {
Log.e(LOG_TAG, "error while decoding JSON for tags filter", e)
emptySet()
}
}
} catch (e: Exception) {
Log.e(LOG_TAG, "error while loading tags for filters", e)
}
try {
client.newCall(GET("$baseUrl/api/v1/publishers", headers)).execute().use { response ->
publishers = try {
response.body.use { json.decodeFromString(it.string()) }
} catch (e: Exception) {
Log.e(LOG_TAG, "error while decoding JSON for publishers filter", e)
emptySet()
}
}
} catch (e: Exception) {
Log.e(LOG_TAG, "error while loading publishers for filters", e)
}
try {
client.newCall(GET("$baseUrl/api/v1/authors", headers)).execute().use { response ->
authors = try {
response.body
.use { json.decodeFromString<List<AuthorDto>>(it.string()) }
.groupBy { it.role }
} catch (e: Exception) {
Log.e(LOG_TAG, "error while decoding JSON for authors filter", e)
emptyMap()
}
}
} catch (e: Exception) {
Log.e(LOG_TAG, "error while loading authors for filters", e)
}
}
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(
{},
{ tr ->
Log.e(LOG_TAG, "error while doing initial calls", tr)
},
)
}
}
companion object {
private const val PREF_DISPLAYNAME = "Source display name"
private const val PREF_ADDRESS = "Address"
private const val ADDRESS_DEFAULT = ""
private const val PREF_USERNAME = "Username"
private const val USERNAME_DEFAULT = ""
private const val PREF_PASSWORD = "Password"
private const val PASSWORD_DEFAULT = ""
private val supportedImageTypes = listOf("image/jpeg", "image/png", "image/gif", "image/webp", "image/jxl", "image/heif", "image/avif")
private const val TYPE_SERIES = "Series"
private const val TYPE_READLISTS = "Read lists"
}
}

View File

@ -0,0 +1,14 @@
package eu.kanade.tachiyomi.extension.all.komga
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceFactory
class KomgaFactory : SourceFactory {
override fun createSources(): List<Source> =
listOf(
Komga(),
Komga("2"),
Komga("3"),
)
}

View File

@ -0,0 +1,14 @@
package eu.kanade.tachiyomi.extension.all.komga
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
object KomgaHelper {
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") }
val formatterDateTimeMilli = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S", Locale.US)
.apply { timeZone = TimeZone.getTimeZone("UTC") }
}

View File

@ -0,0 +1,132 @@
package eu.kanade.tachiyomi.extension.all.komga.dto
import kotlinx.serialization.Serializable
@Serializable
data class LibraryDto(
val id: String,
val name: String,
)
@Serializable
data class SeriesDto(
val id: String,
val libraryId: String,
val name: String,
val created: String?,
val lastModified: String?,
val fileLastModified: String,
val booksCount: Int,
val metadata: SeriesMetadataDto,
val booksMetadata: BookMetadataAggregationDto,
)
@Serializable
data class SeriesMetadataDto(
val status: String,
val created: String?,
val lastModified: String?,
val title: String,
val titleSort: String,
val summary: String,
val summaryLock: Boolean,
val readingDirection: String,
val readingDirectionLock: Boolean,
val publisher: String,
val publisherLock: Boolean,
val ageRating: Int?,
val ageRatingLock: Boolean,
val language: String,
val languageLock: Boolean,
val genres: Set<String>,
val genresLock: Boolean,
val tags: Set<String>,
val tagsLock: Boolean,
val totalBookCount: Int? = null,
)
@Serializable
data class BookMetadataAggregationDto(
val authors: List<AuthorDto> = emptyList(),
val tags: Set<String> = emptySet(),
val releaseDate: String?,
val summary: String,
val summaryNumber: String,
val created: String,
val lastModified: String,
)
@Serializable
data class BookDto(
val id: String,
val seriesId: String,
val seriesTitle: String,
val name: String,
val number: Float,
val created: String?,
val lastModified: String?,
val fileLastModified: String,
val sizeBytes: Long,
val size: String,
val media: MediaDto,
val metadata: BookMetadataDto,
)
@Serializable
data class MediaDto(
val status: String,
val mediaType: String,
val pagesCount: Int,
)
@Serializable
data class PageDto(
val number: Int,
val fileName: String,
val mediaType: String,
)
@Serializable
data class BookMetadataDto(
val title: String,
val titleLock: Boolean,
val summary: String,
val summaryLock: Boolean,
val number: String,
val numberLock: Boolean,
val numberSort: Float,
val numberSortLock: Boolean,
val releaseDate: String?,
val releaseDateLock: Boolean,
val authors: List<AuthorDto>,
val authorsLock: Boolean,
)
@Serializable
data class AuthorDto(
val name: String,
val role: String,
)
@Serializable
data class CollectionDto(
val id: String,
val name: String,
val ordered: Boolean,
val seriesIds: List<String>,
val createdDate: String,
val lastModifiedDate: String,
val filtered: Boolean,
)
@Serializable
data class ReadListDto(
val id: String,
val name: String,
val summary: String,
val bookIds: List<String>,
val createdDate: String,
val lastModifiedDate: String,
val filtered: Boolean,
)

View File

@ -0,0 +1,16 @@
package eu.kanade.tachiyomi.extension.all.komga.dto
import kotlinx.serialization.Serializable
@Serializable
data class PageWrapperDto<T>(
val content: List<T>,
val empty: Boolean,
val first: Boolean,
val last: Boolean,
val number: Long,
val numberOfElements: Long,
val size: Long,
val totalElements: Long,
val totalPages: Long,
)

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest />

Some files were not shown because too many files have changed in this diff Show More