mirror of
https://github.com/KotatsuApp/kotatsu-dl.git
synced 2026-08-19 20:42:03 -07:00
Initial commit
This commit is contained in:
+45
@@ -0,0 +1,45 @@
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea/modules.xml
|
||||
.idea/jarRepositories.xml
|
||||
.idea/compiler.xml
|
||||
.idea/libraries/
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### Kotlin ###
|
||||
.kotlin
|
||||
|
||||
### Eclipse ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Mac OS ###
|
||||
.DS_Store
|
||||
Generated
+8
@@ -0,0 +1,8 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
misc.xml
|
||||
kotlinc.xml
|
||||
vcs.xml
|
||||
/inspectionProfiles/
|
||||
/artifacts/
|
||||
Generated
+17
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="gradleHome" value="" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
</set>
|
||||
</option>
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,48 @@
|
||||
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
|
||||
|
||||
plugins {
|
||||
kotlin("jvm") version "2.0.20"
|
||||
id("com.gradleup.shadow") version "8.3.3"
|
||||
}
|
||||
|
||||
group = "org.koitharu"
|
||||
version = "0.1"
|
||||
|
||||
tasks.withType<Jar> {
|
||||
manifest {
|
||||
attributes["Main-Class"] = "org.koitharu.kotatsu.dl.MainKt"
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<ShadowJar> {
|
||||
archiveBaseName = "kotatsu-dl"
|
||||
archiveClassifier = ""
|
||||
archiveVersion = ""
|
||||
minimize()
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
google()
|
||||
maven { setUrl("https://jitpack.io") }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation(kotlin("test"))
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.9.0")
|
||||
implementation("com.github.ajalt.clikt:clikt-core:5.0.1")
|
||||
implementation("com.github.KotatsuApp:kotatsu-parsers:481fb4f0d0")
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
implementation("com.squareup.okio:okio:3.9.0")
|
||||
implementation("io.webfolder:quickjs:1.1.0")
|
||||
implementation("org.json:json:20240303")
|
||||
implementation("me.tongfei:progressbar:0.10.1")
|
||||
implementation("androidx.collection:collection:1.4.4")
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
kotlin.code.style=official
|
||||
Vendored
BIN
Binary file not shown.
+6
@@ -0,0 +1,6 @@
|
||||
#Mon Oct 14 10:35:03 EEST 2024
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,234 @@
|
||||
#!/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/master/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
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# 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*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
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 \
|
||||
"$@"
|
||||
|
||||
# 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" "$@"
|
||||
Vendored
+89
@@ -0,0 +1,89 @@
|
||||
@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=.
|
||||
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%" == "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%"=="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!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,5 @@
|
||||
plugins {
|
||||
id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
|
||||
}
|
||||
rootProject.name = "kotatsu-dl"
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package org.koitharu.kotatsu.dl
|
||||
|
||||
import com.github.ajalt.clikt.command.main
|
||||
import com.github.ajalt.clikt.core.ProgramResult
|
||||
import com.github.ajalt.clikt.parameters.arguments.argument
|
||||
import com.github.ajalt.clikt.parameters.options.convert
|
||||
import com.github.ajalt.clikt.parameters.options.flag
|
||||
import com.github.ajalt.clikt.parameters.options.option
|
||||
import com.github.ajalt.clikt.parameters.options.validate
|
||||
import com.github.ajalt.clikt.parameters.types.enum
|
||||
import com.github.ajalt.clikt.parameters.types.file
|
||||
import org.koitharu.kotatsu.dl.download.DownloadFormat
|
||||
import org.koitharu.kotatsu.dl.download.MangaDownloader
|
||||
import org.koitharu.kotatsu.dl.parsers.MangaLoaderContextImpl
|
||||
import org.koitharu.kotatsu.dl.ui.askSelectBranch
|
||||
import org.koitharu.kotatsu.dl.util.AppCommand
|
||||
import org.koitharu.kotatsu.dl.util.ChaptersRange
|
||||
import org.koitharu.kotatsu.dl.util.colored
|
||||
import java.io.File
|
||||
|
||||
class Main : AppCommand(name = "kotatsu-dl") {
|
||||
|
||||
private val link: String by argument()
|
||||
private val destination: File? by option(
|
||||
names = arrayOf("--dest", "--destination"),
|
||||
help = "Output file or directory path",
|
||||
).convert {
|
||||
it.replaceFirst(Regex("^~"), System.getProperty("user.home"))
|
||||
}.file(
|
||||
mustExist = false,
|
||||
canBeFile = true,
|
||||
canBeDir = true,
|
||||
)
|
||||
private val format: DownloadFormat? by option(
|
||||
names = arrayOf("--format"),
|
||||
help = "Output format"
|
||||
).enum<DownloadFormat>(
|
||||
ignoreCase = true,
|
||||
key = { it.name.lowercase() },
|
||||
)
|
||||
private val throttle: Boolean by option(
|
||||
names = arrayOf("--throttle"),
|
||||
help = "Slow down downloading to avoid blocking your IP address by server",
|
||||
).flag(default = false)
|
||||
private val chaptersRange: ChaptersRange? by option(
|
||||
names = arrayOf("--chapters"),
|
||||
metavar = "<numbers or range>",
|
||||
help = "Numbers of chapters to download. Can be a single numbers or range, e.g. \"1-4,8,11\" or \"all\"",
|
||||
).convert {
|
||||
ChaptersRange.parse(it)
|
||||
}.validate { range -> range.validate() }
|
||||
|
||||
override suspend fun invoke(): Int {
|
||||
val context = MangaLoaderContextImpl()
|
||||
val linkResolver = context.newLinkResolver(link)
|
||||
print("Resolving link...")
|
||||
val source = linkResolver.getSource()
|
||||
if (source == null) {
|
||||
println()
|
||||
System.err.println("Unsupported manga source")
|
||||
return 1
|
||||
}
|
||||
println('\r')
|
||||
colored {
|
||||
print("Source: ".cyan)
|
||||
print(source.title.bold)
|
||||
println()
|
||||
}
|
||||
val manga = linkResolver.getManga()
|
||||
if (manga == null) {
|
||||
System.err.println("Manga not found")
|
||||
return 1
|
||||
}
|
||||
colored {
|
||||
print("Title: ".cyan)
|
||||
println(manga.title.bold)
|
||||
}
|
||||
var chapters = manga.chapters
|
||||
if (chapters.isNullOrEmpty()) {
|
||||
System.err.println("Manga contains no chapters")
|
||||
throw ProgramResult(1)
|
||||
}
|
||||
chapters = askSelectBranch(chapters)
|
||||
colored {
|
||||
print("Total chapters: ".cyan)
|
||||
println(chapters.size.bold)
|
||||
}
|
||||
val range = chaptersRange ?: if (chapters.size > 1) {
|
||||
colored {
|
||||
print("==>".green)
|
||||
println(" Chapters to download (e.g. \"1-4,8,11\" or empty for all):")
|
||||
print("==>".green)
|
||||
print(' ')
|
||||
}
|
||||
ChaptersRange.parse(readLine())
|
||||
} else {
|
||||
ChaptersRange.all()
|
||||
}
|
||||
val downloader = MangaDownloader(
|
||||
context = context,
|
||||
manga = manga,
|
||||
chapters = chapters,
|
||||
destination = destination,
|
||||
chaptersRange = range,
|
||||
format = format,
|
||||
throttle = throttle,
|
||||
)
|
||||
val file = downloader.download()
|
||||
colored {
|
||||
print("Done.".green.bold)
|
||||
print(" Saved to ")
|
||||
println(file.absolutePath.bold)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun main(args: Array<String>) = Main().main(args)
|
||||
@@ -0,0 +1,6 @@
|
||||
package org.koitharu.kotatsu.dl.download
|
||||
|
||||
enum class DownloadFormat {
|
||||
|
||||
CBZ, ZIP, DIR
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.koitharu.kotatsu.dl.download
|
||||
|
||||
import androidx.collection.MutableObjectLongMap
|
||||
import kotlinx.coroutines.delay
|
||||
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||
|
||||
class DownloadSlowdownDispatcher(
|
||||
private val defaultDelay: Long,
|
||||
) {
|
||||
private val timeMap = MutableObjectLongMap<MangaSource>()
|
||||
|
||||
suspend fun delay(source: MangaSource) {
|
||||
val lastRequest = synchronized(timeMap) {
|
||||
val res = timeMap.getOrDefault(source, 0L)
|
||||
timeMap[source] = System.currentTimeMillis()
|
||||
res
|
||||
}
|
||||
if (lastRequest != 0L) {
|
||||
delay(lastRequest + defaultDelay - System.currentTimeMillis())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package org.koitharu.kotatsu.dl.download
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.runInterruptible
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import okhttp3.internal.closeQuietly
|
||||
import org.koitharu.kotatsu.parsers.model.Manga
|
||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||
import org.koitharu.kotatsu.parsers.util.toFileNameSafe
|
||||
import java.io.File
|
||||
|
||||
class LocalMangaDirOutput(
|
||||
rootFile: File,
|
||||
manga: Manga,
|
||||
) : LocalMangaOutput(rootFile) {
|
||||
|
||||
private val chaptersOutput = HashMap<MangaChapter, ZipOutput>()
|
||||
private val index = MangaIndex(File(rootFile, ENTRY_NAME_INDEX).takeIf{ it.exists() }?.readText())
|
||||
private val mutex = Mutex()
|
||||
|
||||
init {
|
||||
index.setMangaInfo(manga)
|
||||
}
|
||||
|
||||
override suspend fun mergeWithExisting() = Unit
|
||||
|
||||
override suspend fun addCover(file: File, ext: String) = mutex.withLock {
|
||||
val name = buildString {
|
||||
append("cover")
|
||||
if (ext.isNotEmpty() && ext.length <= 4) {
|
||||
append('.')
|
||||
append(ext)
|
||||
}
|
||||
}
|
||||
runInterruptible(Dispatchers.IO) {
|
||||
file.copyTo(File(rootFile, name), overwrite = true)
|
||||
}
|
||||
index.setCoverEntry(name)
|
||||
flushIndex()
|
||||
}
|
||||
|
||||
override suspend fun addPage(chapter: IndexedValue<MangaChapter>, file: File, pageNumber: Int, ext: String) =
|
||||
mutex.withLock {
|
||||
val output = chaptersOutput.getOrPut(chapter.value) {
|
||||
ZipOutput(File(rootFile, chapterFileName(chapter) + SUFFIX_TMP))
|
||||
}
|
||||
val name = buildString {
|
||||
append(FILENAME_PATTERN.format(chapter.value.branch.hashCode(), chapter.index + 1, pageNumber))
|
||||
if (ext.isNotEmpty() && ext.length <= 4) {
|
||||
append('.')
|
||||
append(ext)
|
||||
}
|
||||
}
|
||||
runInterruptible(Dispatchers.IO) {
|
||||
output.put(name, file)
|
||||
}
|
||||
index.addChapter(chapter, chapterFileName(chapter))
|
||||
}
|
||||
|
||||
override suspend fun flushChapter(chapter: MangaChapter): Boolean = mutex.withLock {
|
||||
val output = chaptersOutput.remove(chapter) ?: return@withLock false
|
||||
output.flushAndFinish()
|
||||
flushIndex()
|
||||
true
|
||||
}
|
||||
|
||||
override suspend fun finish() = mutex.withLock {
|
||||
flushIndex()
|
||||
for (output in chaptersOutput.values) {
|
||||
output.flushAndFinish()
|
||||
}
|
||||
chaptersOutput.clear()
|
||||
}
|
||||
|
||||
override suspend fun cleanup() = mutex.withLock {
|
||||
for (output in chaptersOutput.values) {
|
||||
output.file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
for (output in chaptersOutput.values) {
|
||||
output.closeQuietly()
|
||||
}
|
||||
}
|
||||
|
||||
fun setIndex(newIndex: MangaIndex) {
|
||||
index.setFrom(newIndex)
|
||||
}
|
||||
|
||||
private suspend fun ZipOutput.flushAndFinish() = runInterruptible(Dispatchers.IO) {
|
||||
val e: Throwable? = try {
|
||||
finish()
|
||||
null
|
||||
} catch (e: Throwable) {
|
||||
e
|
||||
} finally {
|
||||
close()
|
||||
}
|
||||
if (e == null) {
|
||||
val resFile = File(file.absolutePath.removeSuffix(SUFFIX_TMP))
|
||||
file.renameTo(resFile)
|
||||
} else {
|
||||
file.delete()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private fun chapterFileName(chapter: IndexedValue<MangaChapter>): String {
|
||||
index.getChapterFileName(chapter.value.id)?.let {
|
||||
return it
|
||||
}
|
||||
val baseName = "${chapter.index}_${chapter.value.name.toFileNameSafe()}".take(32)
|
||||
var i = 0
|
||||
while (true) {
|
||||
val name = (if (i == 0) baseName else baseName + "_$i") + ".cbz"
|
||||
if (!File(rootFile, name).exists()) {
|
||||
return name
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun flushIndex() = runInterruptible(Dispatchers.IO) {
|
||||
File(rootFile, ENTRY_NAME_INDEX).writeText(index.toString())
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
private const val FILENAME_PATTERN = "%08d_%03d%03d"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package org.koitharu.kotatsu.dl.download
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.runInterruptible
|
||||
import okio.Closeable
|
||||
import org.koitharu.kotatsu.parsers.model.Manga
|
||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||
import org.koitharu.kotatsu.parsers.util.toFileNameSafe
|
||||
import java.io.File
|
||||
|
||||
sealed class LocalMangaOutput(
|
||||
val rootFile: File,
|
||||
) : Closeable {
|
||||
|
||||
abstract suspend fun mergeWithExisting()
|
||||
|
||||
abstract suspend fun addCover(file: File, ext: String)
|
||||
|
||||
abstract suspend fun addPage(chapter: IndexedValue<MangaChapter>, file: File, pageNumber: Int, ext: String)
|
||||
|
||||
abstract suspend fun flushChapter(chapter: MangaChapter): Boolean
|
||||
|
||||
abstract suspend fun finish()
|
||||
|
||||
abstract suspend fun cleanup()
|
||||
|
||||
companion object {
|
||||
|
||||
const val ENTRY_NAME_INDEX = "index.json"
|
||||
const val SUFFIX_TMP = ".tmp"
|
||||
|
||||
suspend fun create(
|
||||
target: File,
|
||||
manga: Manga,
|
||||
format: DownloadFormat?,
|
||||
): LocalMangaOutput = runInterruptible(Dispatchers.IO) {
|
||||
val targetFormat = format ?: if (manga.chapters.let { it != null && it.size <= 3 }) {
|
||||
DownloadFormat.CBZ
|
||||
} else {
|
||||
DownloadFormat.DIR
|
||||
}
|
||||
var file = if (target.isDirectory || (!target.exists() && format == DownloadFormat.DIR)) {
|
||||
if (!target.exists()) {
|
||||
target.mkdirs()
|
||||
}
|
||||
val baseName = manga.title.toFileNameSafe()
|
||||
when (targetFormat) {
|
||||
DownloadFormat.CBZ -> File(target, "$baseName.cbz")
|
||||
DownloadFormat.ZIP -> File(target, "$baseName.zip")
|
||||
DownloadFormat.DIR -> File(target, baseName)
|
||||
}
|
||||
} else {
|
||||
target.parentFile?.run {
|
||||
if (!exists()) mkdirs()
|
||||
}
|
||||
target
|
||||
}
|
||||
getNextAvailable(file, manga)
|
||||
}
|
||||
|
||||
private fun getNextAvailable(
|
||||
file: File,
|
||||
manga: Manga,
|
||||
): LocalMangaOutput {
|
||||
var i = 0
|
||||
val baseName = file.nameWithoutExtension
|
||||
val ext = file.extension.let { if (it.isNotEmpty()) ".$it" else "" }
|
||||
while (true) {
|
||||
val fileName = (if (i == 0) baseName else baseName + "_$i") + ext
|
||||
val target = File(file.parentFile, fileName)
|
||||
if (target.exists()) {
|
||||
i++
|
||||
} else {
|
||||
return when {
|
||||
target.isDirectory -> LocalMangaDirOutput(target, manga)
|
||||
else -> LocalMangaZipOutput(target, manga)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package org.koitharu.kotatsu.dl.download
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.runInterruptible
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import org.koitharu.kotatsu.parsers.model.Manga
|
||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||
import java.io.File
|
||||
import java.util.zip.ZipFile
|
||||
|
||||
class LocalMangaZipOutput(
|
||||
rootFile: File,
|
||||
manga: Manga,
|
||||
) : LocalMangaOutput(rootFile) {
|
||||
|
||||
private val output = ZipOutput(File(rootFile.path + ".tmp"))
|
||||
private val index = MangaIndex(null)
|
||||
private val mutex = Mutex()
|
||||
|
||||
init {
|
||||
index.setMangaInfo(manga)
|
||||
}
|
||||
|
||||
override suspend fun mergeWithExisting() = mutex.withLock {
|
||||
if (rootFile.exists()) {
|
||||
runInterruptible(Dispatchers.IO) {
|
||||
mergeWith(rootFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun addCover(file: File, ext: String) = mutex.withLock {
|
||||
val name = buildString {
|
||||
append(FILENAME_PATTERN.format(0, 0, 0))
|
||||
if (ext.isNotEmpty() && ext.length <= 4) {
|
||||
append('.')
|
||||
append(ext)
|
||||
}
|
||||
}
|
||||
runInterruptible(Dispatchers.IO) {
|
||||
output.put(name, file)
|
||||
}
|
||||
index.setCoverEntry(name)
|
||||
}
|
||||
|
||||
override suspend fun addPage(chapter: IndexedValue<MangaChapter>, file: File, pageNumber: Int, ext: String) =
|
||||
mutex.withLock {
|
||||
val name = buildString {
|
||||
append(FILENAME_PATTERN.format(chapter.value.branch.hashCode(), chapter.index + 1, pageNumber))
|
||||
if (ext.isNotEmpty() && ext.length <= 4) {
|
||||
append('.')
|
||||
append(ext)
|
||||
}
|
||||
}
|
||||
runInterruptible(Dispatchers.IO) {
|
||||
output.put(name, file)
|
||||
}
|
||||
index.addChapter(chapter, null)
|
||||
}
|
||||
|
||||
override suspend fun flushChapter(chapter: MangaChapter): Boolean = false
|
||||
|
||||
override suspend fun finish() = mutex.withLock {
|
||||
runInterruptible(Dispatchers.IO) {
|
||||
output.use { output ->
|
||||
output.put(ENTRY_NAME_INDEX, index.toString())
|
||||
output.finish()
|
||||
}
|
||||
}
|
||||
rootFile.delete()
|
||||
output.file.renameTo(rootFile)
|
||||
Unit
|
||||
}
|
||||
|
||||
override suspend fun cleanup() = mutex.withLock {
|
||||
output.file.delete()
|
||||
Unit
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
output.close()
|
||||
}
|
||||
|
||||
private fun mergeWith(other: File) {
|
||||
var otherIndex: MangaIndex? = null
|
||||
ZipFile(other).use { zip ->
|
||||
for (entry in zip.entries()) {
|
||||
if (entry.name == ENTRY_NAME_INDEX) {
|
||||
otherIndex = MangaIndex(
|
||||
zip.getInputStream(entry).use {
|
||||
it.reader().readText()
|
||||
},
|
||||
)
|
||||
} else {
|
||||
output.copyEntryFrom(zip, entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
otherIndex?.getMangaInfo()?.chapters?.withIndex()?.let { chapters ->
|
||||
for (chapter in chapters) {
|
||||
index.addChapter(chapter, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
const val FILENAME_PATTERN = "%08d_%03d%03d"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package org.koitharu.kotatsu.dl.download
|
||||
|
||||
import androidx.collection.MutableIntList
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import me.tongfei.progressbar.ProgressBar
|
||||
import me.tongfei.progressbar.ProgressBarBuilder
|
||||
import me.tongfei.progressbar.ProgressBarStyle
|
||||
import okhttp3.Request
|
||||
import okhttp3.internal.closeQuietly
|
||||
import okio.IOException
|
||||
import okio.buffer
|
||||
import okio.sink
|
||||
import org.koitharu.kotatsu.dl.util.*
|
||||
import org.koitharu.kotatsu.parsers.MangaLoaderContext
|
||||
import org.koitharu.kotatsu.parsers.exception.TooManyRequestExceptions
|
||||
import org.koitharu.kotatsu.parsers.model.Manga
|
||||
import org.koitharu.kotatsu.parsers.model.MangaChapter
|
||||
import org.koitharu.kotatsu.parsers.model.MangaParserSource
|
||||
import org.koitharu.kotatsu.parsers.model.MangaSource
|
||||
import org.koitharu.kotatsu.parsers.util.await
|
||||
import org.koitharu.kotatsu.parsers.util.requireBody
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.util.*
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
|
||||
class MangaDownloader(
|
||||
private val context: MangaLoaderContext,
|
||||
private val manga: Manga,
|
||||
private val chapters: List<MangaChapter>,
|
||||
private val destination: File?,
|
||||
private val chaptersRange: ChaptersRange,
|
||||
private val format: DownloadFormat?,
|
||||
private val throttle: Boolean,
|
||||
) {
|
||||
|
||||
private val progressBarStyle = ProgressBarStyle.builder()
|
||||
.rightBracket("]")
|
||||
.leftBracket("[")
|
||||
.colorCode(ColoredConsole.BRIGHT_YELLOW.toByte())
|
||||
.block('#')
|
||||
.build()
|
||||
|
||||
suspend fun download(): File {
|
||||
val progressBar = ProgressBarBuilder()
|
||||
.setStyle(progressBarStyle)
|
||||
.setTaskName("Downloading")
|
||||
.clearDisplayOnFinish()
|
||||
.build()
|
||||
progressBar.setExtraMessage("Preparing...")
|
||||
val output = LocalMangaOutput.create(destination ?: File(""), manga, format)
|
||||
val tempDir = Files.createTempDirectory("kdl_").toFile()
|
||||
val counters = MutableIntList()
|
||||
val totalChapters = chaptersRange.size(chapters)
|
||||
try {
|
||||
val parser = context.newParserInstance(manga.source as MangaParserSource)
|
||||
val coverUrl = manga.largeCoverUrl.ifNullOrEmpty { manga.coverUrl }
|
||||
if (coverUrl.isNotEmpty()) {
|
||||
downloadFile(coverUrl, tempDir, parser.source).let { file ->
|
||||
output.addCover(file, getFileExtensionFromUrl(coverUrl).orEmpty())
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
for (chapter in chapters.withIndex()) {
|
||||
progressBar.setExtraMessage(chapter.value.name)
|
||||
if (chapter.index !in chaptersRange) {
|
||||
continue
|
||||
}
|
||||
val pages = runFailsafe(progressBar) { parser.getPages(chapter.value) }
|
||||
counters.add(pages.size)
|
||||
progressBar.maxHint(counters.sum().toLong() + (totalChapters - counters.size) * pages.size)
|
||||
for ((pageIndex, page) in pages.withIndex()) {
|
||||
runFailsafe(progressBar) {
|
||||
val url = parser.getPageUrl(page)
|
||||
val file = downloadFile(url, tempDir, parser.source)
|
||||
output.addPage(
|
||||
chapter = chapter,
|
||||
file = file,
|
||||
pageNumber = pageIndex,
|
||||
ext = getFileExtensionFromUrl(url).orEmpty(),
|
||||
)
|
||||
progressBar.step()
|
||||
if (file.extension == "tmp") {
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
output.flushChapter(chapter.value)
|
||||
}
|
||||
progressBar.setExtraMessage("Finalizing...")
|
||||
output.mergeWithExisting()
|
||||
output.finish()
|
||||
progressBar.close()
|
||||
return output.rootFile.canonicalFile
|
||||
} catch (e: Throwable) {
|
||||
progressBar.close()
|
||||
throw e
|
||||
} finally {
|
||||
withContext(NonCancellable) {
|
||||
output.cleanup()
|
||||
output.closeQuietly()
|
||||
tempDir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> runFailsafe(progressBar: ProgressBar, block: suspend () -> T): T {
|
||||
var countDown = MAX_FAILSAFE_ATTEMPTS
|
||||
failsafe@ while (true) {
|
||||
try {
|
||||
return block()
|
||||
} catch (e: IOException) {
|
||||
val retryDelay = if (e is TooManyRequestExceptions) {
|
||||
e.getRetryDelay()
|
||||
} else {
|
||||
DOWNLOAD_ERROR_DELAY
|
||||
}
|
||||
if (countDown <= 0 || retryDelay < 0 || retryDelay > MAX_RETRY_DELAY) {
|
||||
throw e
|
||||
} else {
|
||||
countDown--
|
||||
progressBar.pause()
|
||||
try {
|
||||
delay(retryDelay)
|
||||
} finally {
|
||||
progressBar.resume()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun downloadFile(
|
||||
url: String,
|
||||
destination: File,
|
||||
source: MangaSource,
|
||||
): File {
|
||||
if (throttle) {
|
||||
slowdownDispatcher.delay(source)
|
||||
}
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.get()
|
||||
.header(CommonHeaders.ACCEPT, "image/webp,image/png;q=0.9,image/jpeg,*/*;q=0.8")
|
||||
.cacheControl(CommonHeaders.CACHE_CONTROL_NO_STORE)
|
||||
.tag(MangaSource::class.java, source)
|
||||
.build()
|
||||
return context.httpClient.newCall(request).await()
|
||||
.ensureSuccess()
|
||||
.use { response ->
|
||||
val file = File(destination, UUID.randomUUID().toString() + ".tmp")
|
||||
try {
|
||||
response.requireBody().use { body ->
|
||||
file.sink(append = false).buffer().use {
|
||||
it.writeAll(body.source())
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
file.delete()
|
||||
throw e
|
||||
}
|
||||
file
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
|
||||
const val MAX_FAILSAFE_ATTEMPTS = 2
|
||||
const val DOWNLOAD_ERROR_DELAY = 2_000L
|
||||
const val MAX_RETRY_DELAY = 7_200_000L // 2 hours
|
||||
private const val SLOWDOWN_DELAY = 500L
|
||||
|
||||
val slowdownDispatcher = DownloadSlowdownDispatcher(SLOWDOWN_DELAY)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package org.koitharu.kotatsu.dl.download
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.koitharu.kotatsu.parsers.model.*
|
||||
import org.koitharu.kotatsu.parsers.util.find
|
||||
import org.koitharu.kotatsu.parsers.util.json.*
|
||||
import org.koitharu.kotatsu.parsers.util.toTitleCase
|
||||
import java.io.File
|
||||
|
||||
class MangaIndex(source: String?) {
|
||||
|
||||
private val json: JSONObject = source?.let(::JSONObject) ?: JSONObject()
|
||||
|
||||
fun setMangaInfo(manga: Manga) {
|
||||
json.put("id", manga.id)
|
||||
json.put("title", manga.title)
|
||||
json.put("title_alt", manga.altTitle)
|
||||
json.put("url", manga.url)
|
||||
json.put("public_url", manga.publicUrl)
|
||||
json.put("author", manga.author)
|
||||
json.put("cover", manga.coverUrl)
|
||||
json.put("description", manga.description)
|
||||
json.put("rating", manga.rating)
|
||||
json.put("nsfw", manga.isNsfw)
|
||||
json.put("state", manga.state?.name)
|
||||
json.put("source", manga.source.name)
|
||||
json.put("cover_large", manga.largeCoverUrl)
|
||||
json.put(
|
||||
"tags",
|
||||
JSONArray().also { a ->
|
||||
for (tag in manga.tags) {
|
||||
val jo = JSONObject()
|
||||
jo.put("key", tag.key)
|
||||
jo.put("title", tag.title)
|
||||
a.put(jo)
|
||||
}
|
||||
},
|
||||
)
|
||||
if (!json.has("chapters")) {
|
||||
json.put("chapters", JSONObject())
|
||||
}
|
||||
json.put("app_id", "kotatsu-dl")
|
||||
json.put("app_version", "0.1")
|
||||
}
|
||||
|
||||
fun getMangaInfo(): Manga? = if (json.length() == 0) null else runCatching {
|
||||
val source = requireNotNull(MangaParserSource.entries.find(json.getString("source"))) {
|
||||
"Invalid manga source "
|
||||
}
|
||||
Manga(
|
||||
id = json.getLong("id"),
|
||||
title = json.getString("title"),
|
||||
altTitle = json.getStringOrNull("title_alt"),
|
||||
url = json.getString("url"),
|
||||
publicUrl = json.getStringOrNull("public_url").orEmpty(),
|
||||
author = json.getStringOrNull("author"),
|
||||
largeCoverUrl = json.getStringOrNull("cover_large"),
|
||||
source = source,
|
||||
rating = json.getDouble("rating").toFloat(),
|
||||
isNsfw = json.getBooleanOrDefault("nsfw", false),
|
||||
coverUrl = json.getString("cover"),
|
||||
state = json.getStringOrNull("state")?.let { stateString ->
|
||||
MangaState.entries.find(stateString)
|
||||
},
|
||||
description = json.getStringOrNull("description"),
|
||||
tags = json.getJSONArray("tags").mapJSONToSet { x ->
|
||||
MangaTag(
|
||||
title = x.getString("title").toTitleCase(),
|
||||
key = x.getString("key"),
|
||||
source = source,
|
||||
)
|
||||
},
|
||||
chapters = getChapters(json.getJSONObject("chapters"), source),
|
||||
)
|
||||
}.getOrNull()
|
||||
|
||||
fun getCoverEntry(): String? = json.getStringOrNull("cover_entry")
|
||||
|
||||
fun addChapter(chapter: IndexedValue<MangaChapter>, filename: String?) {
|
||||
val chapters = json.getJSONObject("chapters")
|
||||
if (!chapters.has(chapter.value.id.toString())) {
|
||||
val jo = JSONObject()
|
||||
jo.put("number", chapter.value.number)
|
||||
jo.put("volume", chapter.value.volume)
|
||||
jo.put("url", chapter.value.url)
|
||||
jo.put("name", chapter.value.name)
|
||||
jo.put("uploadDate", chapter.value.uploadDate)
|
||||
jo.put("scanlator", chapter.value.scanlator)
|
||||
jo.put("branch", chapter.value.branch)
|
||||
jo.put("entries", "%08d_%03d\\d{3}".format(chapter.value.branch.hashCode(), chapter.index + 1))
|
||||
jo.put("file", filename)
|
||||
chapters.put(chapter.value.id.toString(), jo)
|
||||
}
|
||||
}
|
||||
|
||||
fun removeChapter(id: Long): Boolean {
|
||||
return json.has("chapters") && json.getJSONObject("chapters").remove(id.toString()) != null
|
||||
}
|
||||
|
||||
fun getChapterFileName(chapterId: Long): String? {
|
||||
return json.optJSONObject("chapters")?.optJSONObject(chapterId.toString())?.getStringOrNull("file")
|
||||
}
|
||||
|
||||
fun setCoverEntry(name: String) {
|
||||
json.put("cover_entry", name)
|
||||
}
|
||||
|
||||
fun getChapterNamesPattern(chapter: MangaChapter) = Regex(
|
||||
json.getJSONObject("chapters")
|
||||
.getJSONObject(chapter.id.toString())
|
||||
.getString("entries"),
|
||||
)
|
||||
|
||||
fun clear() {
|
||||
val keys = json.keys()
|
||||
while (keys.hasNext()) {
|
||||
json.remove(keys.next())
|
||||
}
|
||||
}
|
||||
|
||||
fun setFrom(other: MangaIndex) {
|
||||
clear()
|
||||
other.json.keys().forEach { key ->
|
||||
json.putOpt(key, other.json.opt(key))
|
||||
}
|
||||
}
|
||||
|
||||
private fun getChapters(json: JSONObject, source: MangaSource): List<MangaChapter> {
|
||||
val chapters = ArrayList<MangaChapter>(json.length())
|
||||
for (k in json.keys()) {
|
||||
val v = json.getJSONObject(k)
|
||||
chapters.add(
|
||||
MangaChapter(
|
||||
id = k.toLong(),
|
||||
name = v.getString("name"),
|
||||
url = v.getString("url"),
|
||||
number = v.getFloatOrDefault("number", 0f),
|
||||
volume = v.getIntOrDefault("volume", 0),
|
||||
uploadDate = v.getLongOrDefault("uploadDate", 0L),
|
||||
scanlator = v.getStringOrNull("scanlator"),
|
||||
branch = v.getStringOrNull("branch"),
|
||||
source = source,
|
||||
),
|
||||
)
|
||||
}
|
||||
return chapters.sortedBy { it.number }
|
||||
}
|
||||
|
||||
override fun toString(): String = json.toString(4)
|
||||
|
||||
companion object {
|
||||
|
||||
fun read(file: File): MangaIndex? {
|
||||
if (file.exists() && file.canRead()) {
|
||||
val text = file.readText()
|
||||
if (text.length > 2) {
|
||||
return MangaIndex(text)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package org.koitharu.kotatsu.dl.download
|
||||
|
||||
import okio.Closeable
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.nio.file.Files
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.zip.Deflater
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipFile
|
||||
import java.util.zip.ZipOutputStream
|
||||
import kotlin.io.path.name
|
||||
|
||||
class ZipOutput(
|
||||
val file: File,
|
||||
compressionLevel: Int = Deflater.DEFAULT_COMPRESSION,
|
||||
) : Closeable {
|
||||
|
||||
private val entryNames = HashSet<String>()
|
||||
private val isClosed = AtomicBoolean(false)
|
||||
private val output = ZipOutputStream(file.outputStream()).apply {
|
||||
setLevel(compressionLevel)
|
||||
// FIXME: Deflater has been closed
|
||||
}
|
||||
|
||||
fun put(name: String, file: File): Boolean {
|
||||
return output.appendFile(file, name)
|
||||
}
|
||||
|
||||
fun put(name: String, content: String): Boolean {
|
||||
return output.appendText(content, name)
|
||||
}
|
||||
|
||||
fun addDirectory(name: String): Boolean {
|
||||
val entry = if (name.endsWith("/")) {
|
||||
ZipEntry(name)
|
||||
} else {
|
||||
ZipEntry("$name/")
|
||||
}
|
||||
return if (entryNames.add(entry.name)) {
|
||||
output.putNextEntry(entry)
|
||||
output.closeEntry()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun copyEntryFrom(other: ZipFile, entry: ZipEntry): Boolean {
|
||||
return if (entryNames.add(entry.name)) {
|
||||
val zipEntry = ZipEntry(entry.name)
|
||||
output.putNextEntry(zipEntry)
|
||||
try {
|
||||
other.getInputStream(entry).use { input ->
|
||||
input.copyTo(output)
|
||||
}
|
||||
} finally {
|
||||
output.closeEntry()
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun finish() {
|
||||
output.finish()
|
||||
output.flush()
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
if (isClosed.compareAndSet(false, true)) {
|
||||
output.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun ZipOutputStream.appendFile(fileToZip: File, name: String): Boolean {
|
||||
if (fileToZip.isDirectory) {
|
||||
val entry = if (name.endsWith("/")) {
|
||||
ZipEntry(name)
|
||||
} else {
|
||||
ZipEntry("$name/")
|
||||
}
|
||||
if (!entryNames.add(entry.name)) {
|
||||
return false
|
||||
}
|
||||
putNextEntry(entry)
|
||||
closeEntry()
|
||||
Files.newDirectoryStream(fileToZip.toPath()).use {
|
||||
it.forEach { childFile ->
|
||||
appendFile(childFile.toFile(), "$name/${childFile.name}")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
FileInputStream(fileToZip).use { fis ->
|
||||
if (!entryNames.add(name)) {
|
||||
return false
|
||||
}
|
||||
val zipEntry = ZipEntry(name)
|
||||
putNextEntry(zipEntry)
|
||||
try {
|
||||
fis.copyTo(this)
|
||||
} finally {
|
||||
closeEntry()
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun ZipOutputStream.appendText(content: String, name: String): Boolean {
|
||||
if (!entryNames.add(name)) {
|
||||
return false
|
||||
}
|
||||
val zipEntry = ZipEntry(name)
|
||||
putNextEntry(zipEntry)
|
||||
try {
|
||||
content.byteInputStream().copyTo(this)
|
||||
} finally {
|
||||
closeEntry()
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package org.koitharu.kotatsu.dl.parsers
|
||||
|
||||
import org.koitharu.kotatsu.parsers.bitmap.Bitmap
|
||||
import org.koitharu.kotatsu.parsers.bitmap.Rect
|
||||
import java.awt.image.BufferedImage
|
||||
import java.io.ByteArrayOutputStream
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
class BitmapImpl(
|
||||
val image: BufferedImage,
|
||||
) : Bitmap {
|
||||
|
||||
override val width: Int
|
||||
get() = image.width
|
||||
|
||||
override val height: Int
|
||||
get() = image.height
|
||||
|
||||
override fun drawBitmap(
|
||||
sourceBitmap: Bitmap,
|
||||
src: Rect,
|
||||
dst: Rect,
|
||||
) {
|
||||
val graphics = image.createGraphics()
|
||||
val subImage = (sourceBitmap as BitmapImpl).image.getSubimage(
|
||||
src.left, src.top, src.width, src.height,
|
||||
)
|
||||
graphics.drawImage(subImage, dst.left, dst.top, dst.width, dst.height, null)
|
||||
graphics.dispose()
|
||||
}
|
||||
|
||||
fun compress(format: String): ByteArray = ByteArrayOutputStream().also { stream ->
|
||||
ImageIO.write(image, format, stream)
|
||||
}.toByteArray()
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user