Compare commits
58 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8f6c390dc2 | |||
| 0cf75fd6f9 | |||
| b823c913b5 | |||
| 01e6e9873e | |||
| d299e91a93 | |||
| 430e5712fa | |||
| 551425c018 | |||
| 665bca00ea | |||
| 2ec6032673 | |||
| d52f630775 | |||
| 3e7f51e9ae | |||
| bc977fd0cb | |||
| deef93172b | |||
| fa8b69a630 | |||
| abd8d65914 | |||
| c71dda77d4 | |||
| c2caee6ef9 | |||
| e2588908c1 | |||
| 9b36043a00 | |||
| 72fe3bb0f3 | |||
| 9f75945cf6 | |||
| 82f2b4e3b5 | |||
| bdb7eb4521 | |||
| c42f0a0bb0 | |||
| a33db07583 | |||
| 2b99c3d17d | |||
| 6ea1ecb43d | |||
| bbe5ccea81 | |||
| da3a589c88 | |||
| 26b312372e | |||
| 39dc3ec8d6 | |||
| 560848f5d5 | |||
| 0bbd0da68c | |||
| bbdd569522 | |||
| 937e789b67 | |||
| f8647a8e49 | |||
| f93bceb136 | |||
| e8d343893f | |||
| 769ff36352 | |||
| 1253f44413 | |||
| 1c802c5e3b | |||
| a19b374cb4 | |||
| 420603f911 | |||
| 7a6710dc0b | |||
| 7262f1d249 | |||
| 5c12540071 | |||
| 7fbdd92117 | |||
| 5c818be5ab | |||
| 1b25acba26 | |||
| 434d03615c | |||
| 9bde9528df | |||
| 191975f0f9 | |||
| f8895b80b4 | |||
| e5c73615f1 | |||
| 800eb5ee30 | |||
| 721b7edf1c | |||
| 27501b223d | |||
| 0e5c4b8243 |
@@ -45,7 +45,7 @@ body:
|
||||
label: LNReader version
|
||||
description: You can find your LNReader version in **More → About**.
|
||||
placeholder: |
|
||||
Example: "1.1.17"
|
||||
Example: "2.0.0"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
@@ -88,7 +88,7 @@ body:
|
||||
required: true
|
||||
- label: If this is an issue with a source, I should be opening an issue in the [sources repository](https://github.com/lnreader/lnreader-sources/issues/new/choose).
|
||||
required: true
|
||||
- label: I have updated the app to version **[1.1.17](https://github.com/lnreader/lnreader/releases/latest)**.
|
||||
- label: I have updated the app to version **[2.0.0](https://github.com/lnreader/lnreader/releases/latest)**.
|
||||
required: true
|
||||
- label: I will fill out all of the requested information in this form.
|
||||
required: true
|
||||
|
||||
@@ -34,7 +34,7 @@ body:
|
||||
required: true
|
||||
- label: If this is an issue with a source, I should be opening an issue in the [sources repository](https://github.com/LNReader/lnreader-sources/issues/new/choose).
|
||||
required: true
|
||||
- label: I have updated the app to version **[1.1.14](https://github.com/LNReader/lnreader/releases/latest)**.
|
||||
- label: I have updated the app to version **[2.0.0](https://github.com/LNReader/lnreader/releases/latest)**.
|
||||
required: true
|
||||
- label: I will fill out all of the requested information in this form.
|
||||
required: true
|
||||
|
||||
@@ -2,7 +2,7 @@ name: CI
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
jobs:
|
||||
build-android:
|
||||
name: Build App
|
||||
@@ -14,11 +14,16 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '16'
|
||||
node-version: '18'
|
||||
- name: Install Dependencies
|
||||
run: |
|
||||
npm install
|
||||
|
||||
- name: Create .env
|
||||
run: |
|
||||
cat > .env << EOF
|
||||
MYANIMELIST_CLIENT_ID=${{ vars.MYANIMELIST_CLIENT_ID }}
|
||||
ANILIST_CLIENT_ID=${{ vars.ANILIST_CLIENT_ID }}
|
||||
EOF
|
||||
- name: Cache Gradle Wrapper
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
|
||||
@@ -13,11 +13,9 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Moderate issues
|
||||
uses: tachiyomiorg/issue-moderator-action@v2
|
||||
uses: tachiyomiorg/issue-moderator-action@v1
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
duplicate-label: Duplicate
|
||||
|
||||
auto-close-rules: |
|
||||
[
|
||||
{
|
||||
@@ -31,4 +29,3 @@ jobs:
|
||||
"message": "Requested information in the template was not filled out."
|
||||
}
|
||||
]
|
||||
auto-close-ignore-label: do-not-autoclose
|
||||
@@ -2,10 +2,10 @@ name: CI
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -14,6 +14,6 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Install modules
|
||||
run: npm i
|
||||
run: npm install
|
||||
- name: Run ESLint
|
||||
run: npm run lint
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
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@v4
|
||||
with:
|
||||
github-token: ${{ github.token }}
|
||||
issue-inactive-days: '2'
|
||||
pr-inactive-days: '2'
|
||||
@@ -9,7 +9,7 @@ npm-debug.*
|
||||
*.orig.*
|
||||
web-build/
|
||||
.env
|
||||
|
||||
reader_playground/index.html
|
||||
# macOS
|
||||
.DS_Store
|
||||
|
||||
@@ -74,7 +74,4 @@ web-build/
|
||||
# @end expo-cli
|
||||
|
||||
.vscode/
|
||||
src/sources/en/generators/
|
||||
|
||||
# jenv
|
||||
.java-version
|
||||
src/sources/en/generators/
|
||||
@@ -0,0 +1 @@
|
||||
18
|
||||
@@ -9,21 +9,18 @@ import { GestureHandlerRootView } from 'react-native-gesture-handler';
|
||||
import LottieSplashScreen from 'react-native-lottie-splash-screen';
|
||||
import { SafeAreaProvider } from 'react-native-safe-area-context';
|
||||
import { Provider as PaperProvider } from 'react-native-paper';
|
||||
import { Provider } from 'react-redux';
|
||||
import { PersistGate } from 'redux-persist/lib/integration/react';
|
||||
import * as Notifications from 'expo-notifications';
|
||||
import BackgroundService from 'react-native-background-actions';
|
||||
|
||||
import { createDatabase } from '@database/db';
|
||||
import { persistor, store } from '@redux/store';
|
||||
import { createTables } from '@database/db';
|
||||
import AppErrorBoundary from '@components/AppErrorBoundary/AppErrorBoundary';
|
||||
import { collectPlugins } from '@plugins/pluginManager';
|
||||
|
||||
import Main from './src/navigators/Main';
|
||||
import { BottomSheetModalProvider } from '@gorhom/bottom-sheet';
|
||||
|
||||
// Initialize trackers
|
||||
import './src/services/Trackers/index';
|
||||
import './src/services/Trackers/aniList';
|
||||
import './src/services/Trackers/myAnimeList';
|
||||
import { usePlugins } from '@hooks/persisted';
|
||||
import { MMKVStorage } from '@utils/mmkv/mmkv';
|
||||
import { BACKGROUND_ACTION } from '@services/constants';
|
||||
|
||||
Notifications.setNotificationHandler({
|
||||
handleNotification: async () => {
|
||||
@@ -36,26 +33,27 @@ Notifications.setNotificationHandler({
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
const { refreshPlugins } = usePlugins();
|
||||
useEffect(() => {
|
||||
LottieSplashScreen.hide();
|
||||
createDatabase();
|
||||
createTables();
|
||||
collectPlugins().then(() => LottieSplashScreen.hide());
|
||||
refreshPlugins();
|
||||
if (!BackgroundService.isRunning()) {
|
||||
MMKVStorage.delete(BACKGROUND_ACTION);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<AppErrorBoundary>
|
||||
<Provider store={store}>
|
||||
<PersistGate loading={null} persistor={persistor}>
|
||||
<SafeAreaProvider>
|
||||
<PaperProvider>
|
||||
<BottomSheetModalProvider>
|
||||
<StatusBar translucent={true} backgroundColor="transparent" />
|
||||
<Main />
|
||||
</BottomSheetModalProvider>
|
||||
</PaperProvider>
|
||||
</SafeAreaProvider>
|
||||
</PersistGate>
|
||||
</Provider>
|
||||
<SafeAreaProvider>
|
||||
<PaperProvider>
|
||||
<BottomSheetModalProvider>
|
||||
<StatusBar translucent={true} backgroundColor="transparent" />
|
||||
<Main />
|
||||
</BottomSheetModalProvider>
|
||||
</PaperProvider>
|
||||
</SafeAreaProvider>
|
||||
</AppErrorBoundary>
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
@@ -57,3 +57,46 @@ codebase, however you can always check to see if the source code is compliant by
|
||||
```bash
|
||||
npm run lint
|
||||
```
|
||||
# Database
|
||||
```mermaid
|
||||
erDiagram
|
||||
Category ||--|{ NovelCategory : contains
|
||||
Category{
|
||||
INTEGER id PK
|
||||
TEXT name
|
||||
INTEGER sort
|
||||
}
|
||||
NovelCategory{
|
||||
INTEGER id PK
|
||||
INTEGER novelId FK
|
||||
INTEGER categoryId FK "default: whose sort = 1"
|
||||
}
|
||||
Novel ||--|{ NovelCategory : contains
|
||||
Novel{
|
||||
INTEGER id PK
|
||||
TEXT url
|
||||
TEXT pluginId
|
||||
TEXT name
|
||||
TEXT cover
|
||||
TEXT summary
|
||||
TEXT author
|
||||
TEXT artist
|
||||
TEXT status
|
||||
TEXT genres
|
||||
INTEGER inLibrary "default: 0"
|
||||
}
|
||||
Novel ||--o| Chapter : has
|
||||
Chapter{
|
||||
INTEGER id PK
|
||||
INTEGER novelId FK
|
||||
text url
|
||||
TEXT name
|
||||
TEXT releaseTime
|
||||
INTEGER bookmark "default: 0"
|
||||
INTEGER unread "default: 1"
|
||||
TEXT readTime
|
||||
INTEGER isDownloaded "default: 0"
|
||||
TEXT updatedTime
|
||||
TEXT chapterNumber
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1,129 +1,87 @@
|
||||
apply plugin: "com.android.application"
|
||||
apply plugin: "com.facebook.react"
|
||||
|
||||
import com.android.build.OutputFile
|
||||
|
||||
/**
|
||||
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
|
||||
* and bundleReleaseJsAndAssets).
|
||||
* These basically call `react-native bundle` with the correct arguments during the Android build
|
||||
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
|
||||
* bundle directly from the development server. Below you can see all the possible configurations
|
||||
* and their defaults. If you decide to add a configuration block, make sure to add it before the
|
||||
* `apply from: "../../node_modules/react-native/react.gradle"` line.
|
||||
*
|
||||
* project.ext.react = [
|
||||
* // the name of the generated asset file containing your JS bundle
|
||||
* bundleAssetName: "index.android.bundle",
|
||||
*
|
||||
* // the entry file for bundle generation. If none specified and
|
||||
* // "index.android.js" exists, it will be used. Otherwise "index.js" is
|
||||
* // default. Can be overridden with ENTRY_FILE environment variable.
|
||||
* entryFile: "index.android.js",
|
||||
*
|
||||
* // https://reactnative.dev/docs/performance#enable-the-ram-format
|
||||
* bundleCommand: "ram-bundle",
|
||||
*
|
||||
* // whether to bundle JS and assets in debug mode
|
||||
* bundleInDebug: false,
|
||||
*
|
||||
* // whether to bundle JS and assets in release mode
|
||||
* bundleInRelease: true,
|
||||
*
|
||||
* // whether to bundle JS and assets in another build variant (if configured).
|
||||
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
|
||||
* // The configuration property can be in the following formats
|
||||
* // 'bundleIn${productFlavor}${buildType}'
|
||||
* // 'bundleIn${buildType}'
|
||||
* // bundleInFreeDebug: true,
|
||||
* // bundleInPaidRelease: true,
|
||||
* // bundleInBeta: true,
|
||||
*
|
||||
* // whether to disable dev mode in custom build variants (by default only disabled in release)
|
||||
* // for example: to disable dev mode in the staging build type (if configured)
|
||||
* devDisabledInStaging: true,
|
||||
* // The configuration property can be in the following formats
|
||||
* // 'devDisabledIn${productFlavor}${buildType}'
|
||||
* // 'devDisabledIn${buildType}'
|
||||
*
|
||||
* // the root of your project, i.e. where "package.json" lives
|
||||
* root: "../../",
|
||||
*
|
||||
* // where to put the JS bundle asset in debug mode
|
||||
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
|
||||
*
|
||||
* // where to put the JS bundle asset in release mode
|
||||
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
|
||||
*
|
||||
* // where to put drawable resources / React Native assets, e.g. the ones you use via
|
||||
* // require('./image.png')), in debug mode
|
||||
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
|
||||
*
|
||||
* // where to put drawable resources / React Native assets, e.g. the ones you use via
|
||||
* // require('./image.png')), in release mode
|
||||
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
|
||||
*
|
||||
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
|
||||
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
|
||||
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
|
||||
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
|
||||
* // for example, you might want to remove it from here.
|
||||
* inputExcludes: ["android/**", "ios/**"],
|
||||
*
|
||||
* // override which node gets called and with what additional arguments
|
||||
* nodeExecutableAndArgs: ["node"],
|
||||
*
|
||||
* // supply additional arguments to the packager
|
||||
* extraPackagerArgs: []
|
||||
* ]
|
||||
* This is the configuration block to customize your React Native Android app.
|
||||
* By default you don't need to apply any configuration, just uncomment the lines you need.
|
||||
*/
|
||||
react {
|
||||
/* Folders */
|
||||
// The root of your project, i.e. where "package.json" lives. Default is '..'
|
||||
// root = file("../")
|
||||
// The folder where the react-native NPM package is. Default is ../node_modules/react-native
|
||||
// reactNativeDir = file("../node_modules/react-native")
|
||||
// The folder where the react-native Codegen package is. Default is ../node_modules/react-native-codegen
|
||||
// codegenDir = file("../node_modules/react-native-codegen")
|
||||
// The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
|
||||
// cliFile = file("../node_modules/react-native/cli.js")
|
||||
|
||||
project.ext.react = [
|
||||
entryFile: "index.js",
|
||||
enableHermes: true, // clean and rebuild if changing
|
||||
hermesCommand: '../../node_modules/react-native/sdks/hermesc/%OS-BIN%/hermesc',
|
||||
]
|
||||
/* Variants */
|
||||
// The list of variants to that are debuggable. For those we're going to
|
||||
// skip the bundling of the JS bundle and the assets. By default is just 'debug'.
|
||||
// If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
|
||||
// debuggableVariants = ["liteDebug", "prodDebug"]
|
||||
|
||||
apply from: "../../node_modules/react-native/react.gradle"
|
||||
/* Bundling */
|
||||
// A list containing the node command and its flags. Default is just 'node'.
|
||||
// nodeExecutableAndArgs = ["node"]
|
||||
//
|
||||
// The command to run when bundling. By default is 'bundle'
|
||||
// bundleCommand = "ram-bundle"
|
||||
//
|
||||
// The path to the CLI configuration file. Default is empty.
|
||||
// bundleConfig = file(../rn-cli.config.js)
|
||||
//
|
||||
// The name of the generated asset file containing your JS bundle
|
||||
// bundleAssetName = "MyApplication.android.bundle"
|
||||
//
|
||||
// The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
|
||||
// entryFile = file("../js/index.android.js")
|
||||
//
|
||||
// A list of extra flags to pass to the 'bundle' commands.
|
||||
// See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
|
||||
// extraPackagerArgs = []
|
||||
|
||||
/* Hermes Commands */
|
||||
// The hermes compiler command to run. By default it is 'hermesc'
|
||||
// hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
|
||||
//
|
||||
// The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
|
||||
// hermesFlags = ["-O", "-output-source-map"]
|
||||
}
|
||||
|
||||
/**
|
||||
* Set this to true to create two separate APKs instead of one:
|
||||
* - An APK that only works on ARM devices
|
||||
* - An APK that only works on x86 devices
|
||||
* The advantage is the size of the APK is reduced by about 4MB.
|
||||
* Upload all the APKs to the Play Store and people will download
|
||||
* the correct one based on the CPU architecture of their device.
|
||||
* Set this to true to create four separate APKs instead of one,
|
||||
* one for each native architecture. This is useful if you don't
|
||||
* use App Bundles (https://developer.android.com/guide/app-bundle/)
|
||||
* and want to have separate APKs to upload to the Play Store.
|
||||
*/
|
||||
def enableSeparateBuildPerCPUArchitecture = false
|
||||
|
||||
/**
|
||||
* Run Proguard to shrink the Java bytecode in release builds.
|
||||
* Set this to true to Run Proguard on Release builds to minify the Java bytecode.
|
||||
*/
|
||||
def enableProguardInReleaseBuilds = false
|
||||
|
||||
/**
|
||||
* The preferred build flavor of JavaScriptCore.
|
||||
* The preferred build flavor of JavaScriptCore (JSC).
|
||||
*
|
||||
* For example, to use the international variant, you can use:
|
||||
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
|
||||
*
|
||||
* The international variant includes ICU i18n library and necessary data
|
||||
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
|
||||
* give correct results when using with locales other than en-US. Note that
|
||||
* give correct results when using with locales other than en-US. Note that
|
||||
* this variant is about 6MiB larger per architecture than default.
|
||||
*/
|
||||
def jscFlavor = 'org.webkit:android-jsc:+'
|
||||
|
||||
/**
|
||||
* Whether to enable the Hermes VM.
|
||||
*
|
||||
* This should be set on project.ext.react and mirrored here. If it is not set
|
||||
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
|
||||
* and the benefits of using Hermes will therefore be sharply reduced.
|
||||
*/
|
||||
def enableHermes = project.ext.react.get("enableHermes", false);
|
||||
|
||||
/**
|
||||
* Architectures to build native code for.
|
||||
* Private function to get the list of Native Architectures you want to build.
|
||||
* This reads the value from reactNativeArchitectures in your gradle.properties
|
||||
* file and works together with the --active-arch-only flag of react-native run-android.
|
||||
*/
|
||||
def reactNativeArchitectures() {
|
||||
def value = project.getProperties().get("reactNativeArchitectures")
|
||||
@@ -131,16 +89,16 @@ def reactNativeArchitectures() {
|
||||
}
|
||||
|
||||
ext {
|
||||
versionMajor = 1
|
||||
versionMinor = 1
|
||||
versionPatch = 17
|
||||
versionMajor = 2
|
||||
versionMinor = 0
|
||||
versionPatch = 0
|
||||
}
|
||||
|
||||
android {
|
||||
ndkVersion rootProject.ext.ndkVersion
|
||||
|
||||
compileSdkVersion rootProject.ext.compileSdkVersion
|
||||
|
||||
namespace "com.rajarsheechatterjee.LNReader"
|
||||
defaultConfig {
|
||||
applicationId 'com.rajarsheechatterjee.LNReader'
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
@@ -148,7 +106,6 @@ android {
|
||||
// Generated version code. Supports versions up to 1024.1024.2048
|
||||
versionCode ((((versionMajor << 10) | versionMinor) << 11) | versionPatch)
|
||||
versionName "$versionMajor.$versionMinor.$versionPatch"
|
||||
buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
|
||||
}
|
||||
splits {
|
||||
abi {
|
||||
@@ -196,17 +153,14 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation fileTree(dir: "libs", include: ["*.jar"])
|
||||
//noinspection GradleDynamicVersion
|
||||
implementation "com.facebook.react:react-native:+" // From node_modules
|
||||
// The version of react-native is set by the React Native Gradle Plugin
|
||||
implementation("com.facebook.react:react-android")
|
||||
implementation 'com.facebook.soloader:soloader:0.10.5+'
|
||||
|
||||
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
|
||||
implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.0.0")
|
||||
|
||||
implementation project(':react-native-lottie-splash-screen')
|
||||
implementation project(':react-native-fs')
|
||||
implementation 'com.github.bumptech.glide:glide:4.12.0'
|
||||
|
||||
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
|
||||
|
||||
def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
|
||||
def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
|
||||
@@ -231,41 +185,11 @@ dependencies {
|
||||
}
|
||||
}
|
||||
|
||||
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
|
||||
exclude group:'com.facebook.fbjni'
|
||||
}
|
||||
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
|
||||
exclude group:'com.facebook.flipper'
|
||||
exclude group:'com.squareup.okhttp3', module:'okhttp'
|
||||
}
|
||||
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
|
||||
exclude group:'com.facebook.flipper'
|
||||
}
|
||||
|
||||
if (enableHermes) {
|
||||
//noinspection GradleDynamicVersion
|
||||
implementation("com.facebook.react:hermes-engine:+") { // From node_modules
|
||||
exclude group:'com.facebook.fbjni'
|
||||
}
|
||||
if (hermesEnabled.toBoolean()) {
|
||||
implementation("com.facebook.react:hermes-android")
|
||||
} else {
|
||||
implementation jscFlavor
|
||||
}
|
||||
}
|
||||
|
||||
// Run this once to be able to run the application with BUCK
|
||||
// puts all compile dependencies into folder libs for BUCK to use
|
||||
task copyDownloadableDepsToLibs(type: Copy) {
|
||||
from configurations.implementation
|
||||
into 'libs'
|
||||
}
|
||||
|
||||
apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
|
||||
applyNativeModulesAppBuildGradle(project)
|
||||
|
||||
def isNewArchitectureEnabled() {
|
||||
// To opt-in for the New Architecture, you can either:
|
||||
// - Set `newArchEnabled` to true inside the `gradle.properties` file
|
||||
// - Invoke gradle with `-newArchEnabled=true`
|
||||
// - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
|
||||
return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
|
||||
}
|
||||
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
"""Helper definitions to glob .aar and .jar targets"""
|
||||
|
||||
def create_aar_targets(aarfiles):
|
||||
for aarfile in aarfiles:
|
||||
name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")]
|
||||
lib_deps.append(":" + name)
|
||||
android_prebuilt_aar(
|
||||
name = name,
|
||||
aar = aarfile,
|
||||
)
|
||||
|
||||
def create_jar_targets(jarfiles):
|
||||
for jarfile in jarfiles:
|
||||
name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")]
|
||||
lib_deps.append(":" + name)
|
||||
prebuilt_jar(
|
||||
name = name,
|
||||
binary_jar = jarfile,
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "1093792259511",
|
||||
"project_id": "lnreader-test",
|
||||
"storage_bucket": "lnreader-test.appspot.com"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:1093792259511:android:aab0078285720642369c32",
|
||||
"android_client_info": {
|
||||
"package_name": "com.rajarsheechatterjee.LNReader"
|
||||
}
|
||||
},
|
||||
"oauth_client": [
|
||||
{
|
||||
"client_id": "1093792259511-9kftu28l4ku1k3cco7pn83jbrlsc4fr5.apps.googleusercontent.com",
|
||||
"client_type": 1,
|
||||
"android_info": {
|
||||
"package_name": "com.rajarsheechatterjee.LNReader",
|
||||
"certificate_hash": "5e8f16062ea3cd2c4a0d547876baa6f38cabf625"
|
||||
}
|
||||
},
|
||||
{
|
||||
"client_id": "1093792259511-ml5ko1gmnvihqb2j9nnteehoeom2umnt.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyDuumsGzm6iE4u7E8pkk8FcNH9wL5GzoI8"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": [
|
||||
{
|
||||
"client_id": "1093792259511-ml5ko1gmnvihqb2j9nnteehoeom2umnt.apps.googleusercontent.com",
|
||||
"client_type": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
@@ -12,11 +12,3 @@
|
||||
-keep class com.facebook.react.turbomodule.** { *; }
|
||||
-keep class com.facebook.hermes.unicode.** { *; }
|
||||
-keep class com.facebook.jni.** { *; }
|
||||
-keep public class com.dylanvann.fastimage.* {*;}
|
||||
-keep public class com.dylanvann.fastimage.** {*;}
|
||||
-keep public class * implements com.bumptech.glide.module.GlideModule
|
||||
-keep public class * extends com.bumptech.glide.module.AppGlideModule
|
||||
-keep public enum com.bumptech.glide.load.ImageHeaderParser$** {
|
||||
**[] $VALUES;
|
||||
public *;
|
||||
}
|
||||
@@ -9,4 +9,4 @@
|
||||
tools:ignore="GoogleAppIndexingWarning">
|
||||
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" android:exported="false"/>
|
||||
</application>
|
||||
</manifest>
|
||||
</manifest>
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
|
||||
* directory of this source tree.
|
||||
*/
|
||||
package com.lnreader;
|
||||
|
||||
import android.content.Context;
|
||||
import com.facebook.flipper.android.AndroidFlipperClient;
|
||||
import com.facebook.flipper.android.utils.FlipperUtils;
|
||||
import com.facebook.flipper.core.FlipperClient;
|
||||
import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
|
||||
import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
|
||||
import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
|
||||
import com.facebook.flipper.plugins.inspector.DescriptorMapping;
|
||||
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
|
||||
import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
|
||||
import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
|
||||
import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
|
||||
import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
|
||||
import com.facebook.react.ReactInstanceEventListener;
|
||||
import com.facebook.react.ReactInstanceManager;
|
||||
import com.facebook.react.bridge.ReactContext;
|
||||
import com.facebook.react.modules.network.NetworkingModule;
|
||||
import okhttp3.OkHttpClient;
|
||||
|
||||
public class ReactNativeFlipper {
|
||||
public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
|
||||
if (FlipperUtils.shouldEnableFlipper(context)) {
|
||||
final FlipperClient client = AndroidFlipperClient.getInstance(context);
|
||||
client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
|
||||
client.addPlugin(new ReactFlipperPlugin());
|
||||
client.addPlugin(new DatabasesFlipperPlugin(context));
|
||||
client.addPlugin(new SharedPreferencesFlipperPlugin(context));
|
||||
client.addPlugin(CrashReporterPlugin.getInstance());
|
||||
NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
|
||||
NetworkingModule.setCustomClientBuilder(
|
||||
new NetworkingModule.CustomClientBuilder() {
|
||||
@Override
|
||||
public void apply(OkHttpClient.Builder builder) {
|
||||
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
|
||||
}
|
||||
});
|
||||
client.addPlugin(networkFlipperPlugin);
|
||||
client.start();
|
||||
// Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
|
||||
// Hence we run if after all native modules have been initialized
|
||||
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
|
||||
if (reactContext == null) {
|
||||
reactInstanceManager.addReactInstanceEventListener(
|
||||
new ReactInstanceEventListener() {
|
||||
@Override
|
||||
public void onReactContextInitialized(ReactContext reactContext) {
|
||||
reactInstanceManager.removeReactInstanceEventListener(this);
|
||||
reactContext.runOnNativeModulesQueueThread(
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
client.addPlugin(new FrescoFlipperPlugin());
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
client.addPlugin(new FrescoFlipperPlugin());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.rajarsheechatterjee.LNReader">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.rajarsheechatterjee.LNReader">
|
||||
|
||||
<!-- Internet -->
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
overflow-x: hidden;
|
||||
padding-top: var(--StatusBar-currentHeight);
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
body {
|
||||
padding-left: var(--readerSettings-padding);
|
||||
padding-right: var(--readerSettings-padding);
|
||||
padding-bottom: 40px;
|
||||
|
||||
font-size: var(--readerSettings-textSize);
|
||||
color: var(--readerSettings-textColor);
|
||||
text-align: var(--readerSettings-textAlign);
|
||||
line-height: var(--readerSettings-lineHeight);
|
||||
font-family: var(--readerSettings-fontFamily);
|
||||
}
|
||||
|
||||
chapter {
|
||||
display: block;
|
||||
}
|
||||
|
||||
hr {
|
||||
margin-top: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--theme-primary);
|
||||
}
|
||||
|
||||
img {
|
||||
display: block;
|
||||
width: auto;
|
||||
height: auto;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.nextButton,
|
||||
.infoText {
|
||||
width: 100%;
|
||||
border-radius: 50px;
|
||||
border-width: 1;
|
||||
color: var(--theme-onPrimary);
|
||||
background-color: var(--theme-primary);
|
||||
font-family: var(--readerSettings-fontFamily);
|
||||
font-size: 16px;
|
||||
border-width: 0;
|
||||
}
|
||||
|
||||
.nextButton {
|
||||
min-height: 40px;
|
||||
text-overflow: ellipsis;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
padding: 0 16px;
|
||||
}
|
||||
|
||||
.infoText {
|
||||
background-color: transparent;
|
||||
text-align: center;
|
||||
border: none;
|
||||
margin: 0px;
|
||||
color: inherit;
|
||||
padding-top: 16px;
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
|
||||
.chapterCtn {
|
||||
min-height: var(--chapterCtn-height);
|
||||
margin-bottom: auto;
|
||||
}
|
||||
|
||||
.d-none {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#ScrollBar {
|
||||
position: fixed;
|
||||
right: 5vw;
|
||||
top: 27.5vh;
|
||||
height: 45vh;
|
||||
width: 2.4rem;
|
||||
border-radius: 1.2rem;
|
||||
background-color: var(--theme-surface-0-9);
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.scrollbar-item {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
color: var(--theme-onSurface);
|
||||
}
|
||||
|
||||
.scrollbar-item.scrollbar-text {
|
||||
height: 12.5%;
|
||||
}
|
||||
|
||||
.scrollbar-item#scrollbar-slider {
|
||||
height: 75%;
|
||||
align-items: unset;
|
||||
}
|
||||
|
||||
#scrollbar-track {
|
||||
width: 0.1rem;
|
||||
height: 100%;
|
||||
background-color: var(--theme-outline);
|
||||
}
|
||||
|
||||
#scrollbar-progress {
|
||||
width: 0.1rem;
|
||||
height: 0;
|
||||
background-color: var(--theme-primary);
|
||||
transform: translateX(-0.1rem);
|
||||
}
|
||||
|
||||
#scrollbar-thumb-wrapper {
|
||||
position: relative;
|
||||
top: 100%;
|
||||
height: 2rem;
|
||||
width: 2rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transform: translate(-0.95rem, -1rem);
|
||||
}
|
||||
|
||||
#scrollbar-thumb {
|
||||
top: 100%;
|
||||
height: 1rem;
|
||||
width: 1rem;
|
||||
border-radius: 100%;
|
||||
background-color: var(--theme-primary);
|
||||
}
|
||||
|
||||
#reader-percentage {
|
||||
position: fixed;
|
||||
padding-top: 0.5rem;
|
||||
min-height: 2rem;
|
||||
width: 100%;
|
||||
background-color: var(--readerSettings-theme);
|
||||
color: var(--readerSettings-textColor);
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
font-size: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
t-t-s.tts-highlight {
|
||||
color: var(--theme-onSecondary);
|
||||
background-color: var(--theme-secondary);
|
||||
}
|
||||
|
After Width: | Height: | Size: 17 KiB |
@@ -0,0 +1,181 @@
|
||||
class Reader {
|
||||
constructor() {
|
||||
this.percentage =
|
||||
showScrollPercentage && document.getElementById('reader-percentage');
|
||||
this.paddingTop = parseInt(
|
||||
getComputedStyle(document.querySelector('html')).getPropertyValue(
|
||||
'padding-top',
|
||||
),
|
||||
);
|
||||
this.chapter = document.querySelector('chapter');
|
||||
this.chapterHeight = this.chapter.scrollHeight + this.paddingTop;
|
||||
this.layoutHeight = window.innerHeight;
|
||||
this.pluginId = this.chapter.getAttribute('data-plugin-id');
|
||||
this.novelId = this.chapter.getAttribute('data-novel-id');
|
||||
this.chapterId = this.chapter.getAttribute('data-chapter-id');
|
||||
this.saveProgressInterval = setInterval(
|
||||
() =>
|
||||
this.post({
|
||||
type: 'save',
|
||||
data: {
|
||||
offsetY: window.scrollY,
|
||||
percentage: parseInt(
|
||||
((window.scrollY + this.layoutHeight) / this.chapterHeight) * 100,
|
||||
),
|
||||
},
|
||||
}),
|
||||
autoSaveInterval,
|
||||
);
|
||||
}
|
||||
|
||||
refresh = () => {
|
||||
this.chapterHeight = this.chapter.scrollHeight + this.paddingTop;
|
||||
};
|
||||
post = obj => window.ReactNativeWebView.postMessage(JSON.stringify(obj));
|
||||
}
|
||||
class ScrollHandler {
|
||||
constructor(reader) {
|
||||
this.reader = reader;
|
||||
this.$ = document.getElementById('ScrollBar');
|
||||
this.$.innerHTML = `
|
||||
<div class="scrollbar-item scrollbar-text d-none" id="scrollbar-percentage">
|
||||
0
|
||||
</div>
|
||||
<div class="scrollbar-item" id="scrollbar-slider">
|
||||
<div id="scrollbar-track">
|
||||
</div>
|
||||
<div id="scrollbar-progress">
|
||||
<div id="scrollbar-thumb-wrapper">
|
||||
<div id="scrollbar-thumb"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="scrollbar-item scrollbar-text">
|
||||
100
|
||||
</div>
|
||||
`;
|
||||
this.percentage = this.$.querySelector('#scrollbar-percentage');
|
||||
this.progress = this.$.querySelector('#scrollbar-progress');
|
||||
this.thumb = this.$.querySelector('#scrollbar-thumb-wrapper');
|
||||
this.slider = this.$.querySelector('#scrollbar-slider');
|
||||
this.sliderHeight = this.slider.clientHeight;
|
||||
this.sliderOffsetY = this.slider.offsetTop + this.$.offsetTop;
|
||||
this.lock = false;
|
||||
this.visible = false; // scrollbar
|
||||
window.onscroll = () => !this.lock && this.update();
|
||||
this.thumb.ontouchstart = () => (this.lock = true);
|
||||
this.thumb.ontouchend = () => (this.lock = false);
|
||||
this.thumb.ontouchmove = e => {
|
||||
const ratio =
|
||||
(e.changedTouches[0].clientY - this.sliderOffsetY) / this.sliderHeight;
|
||||
this.update(ratio < 0 ? 0 : ratio);
|
||||
};
|
||||
}
|
||||
update = ratio => {
|
||||
if (ratio === undefined) {
|
||||
ratio =
|
||||
(window.scrollY + this.reader.layoutHeight) / this.reader.chapterHeight;
|
||||
}
|
||||
if (ratio > 1) {
|
||||
ratio = 1;
|
||||
}
|
||||
const percentage = parseInt(ratio * 100);
|
||||
if (this.visible) {
|
||||
this.progress.style.height = percentage + '%';
|
||||
this.percentage.innerText = percentage;
|
||||
}
|
||||
if (this.lock) {
|
||||
window.scrollTo({
|
||||
top: this.reader.chapterHeight * ratio - this.reader.layoutHeight,
|
||||
behavior: 'instant',
|
||||
});
|
||||
}
|
||||
if (this.reader.percentage) {
|
||||
this.reader.percentage.innerText = percentage + '%';
|
||||
}
|
||||
};
|
||||
refresh = () => {
|
||||
this.sliderHeight = this.slider.clientHeight;
|
||||
this.sliderOffsetY = this.slider.offsetTop + this.$.offsetTop;
|
||||
};
|
||||
hide = () => {
|
||||
this.$.classList.add('d-none');
|
||||
this.visible = false;
|
||||
};
|
||||
show = () => {
|
||||
this.reader.refresh();
|
||||
this.visible = true;
|
||||
this.$.classList.remove('d-none');
|
||||
this.refresh();
|
||||
this.update();
|
||||
};
|
||||
}
|
||||
|
||||
class SwipeHandler {
|
||||
constructor(reader) {
|
||||
this.reader = reader;
|
||||
this.initialX = null;
|
||||
this.initialY = null;
|
||||
if (swipeGestures) {
|
||||
this.enable();
|
||||
}
|
||||
}
|
||||
|
||||
touchStartHandler = e => {
|
||||
this.initialX = e.changedTouches[0].screenX;
|
||||
this.initialY = e.changedTouches[0].screenY;
|
||||
};
|
||||
|
||||
touchEndHandler = e => {
|
||||
let diffX = e.changedTouches[0].screenX - this.initialX;
|
||||
let diffY = e.changedTouches[0].screenY - this.initialY;
|
||||
if (Math.abs(diffX) > Math.abs(diffY) && Math.abs(diffX) > 10) {
|
||||
e.preventDefault();
|
||||
this.reader.post({ type: diffX < 0 ? 'next' : 'prev' });
|
||||
}
|
||||
};
|
||||
|
||||
enable = () => {
|
||||
document.addEventListener('touchstart', this.touchStartHandler);
|
||||
document.addEventListener('touchend', this.touchEndHandler);
|
||||
};
|
||||
|
||||
disable = () => {
|
||||
document.removeEventListener('touchstart', this.touchStartHandler);
|
||||
document.removeEventListener('touchend', this.touchEndHandler);
|
||||
};
|
||||
}
|
||||
|
||||
class TextToSpeech {
|
||||
constructor(reader) {
|
||||
this.reader = reader;
|
||||
this.elements = this.reader.chapter.querySelectorAll('t-t-s');
|
||||
this.previous = null;
|
||||
}
|
||||
play = index => {
|
||||
if (index >= 0 && index < this.elements.length) {
|
||||
if (this.previous !== null) {
|
||||
this.unhighlight(this.previous);
|
||||
}
|
||||
this.highlight(index);
|
||||
this.previous = index;
|
||||
}
|
||||
};
|
||||
|
||||
highlight = index => {
|
||||
if (index >= 0 && index < this.elements.length) {
|
||||
this.elements[index].classList.add('tts-highlight');
|
||||
}
|
||||
};
|
||||
|
||||
unhighlight = index => {
|
||||
if (index >= 0 && index < this.elements.length) {
|
||||
this.elements[index].classList.remove('tts-highlight');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const reader = new Reader();
|
||||
const scrollHandler = new ScrollHandler(reader);
|
||||
const swipeHandler = new SwipeHandler(reader);
|
||||
const tts = new TextToSpeech(reader);
|
||||
@@ -0,0 +1,174 @@
|
||||
package com.rajarsheechatterjee.EpubParser;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.facebook.react.bridge.Promise;
|
||||
import com.facebook.react.bridge.ReactApplicationContext;
|
||||
import com.facebook.react.bridge.ReactContextBaseJavaModule;
|
||||
import com.facebook.react.bridge.ReactMethod;
|
||||
import com.facebook.react.bridge.ReadableArray;
|
||||
import com.facebook.react.bridge.ReadableMap;
|
||||
import com.facebook.react.bridge.WritableArray;
|
||||
import com.facebook.react.bridge.WritableMap;
|
||||
import com.facebook.react.bridge.WritableNativeArray;
|
||||
import com.facebook.react.bridge.WritableNativeMap;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.xpath.XPath;
|
||||
import javax.xml.xpath.XPathConstants;
|
||||
import javax.xml.xpath.XPathFactory;
|
||||
|
||||
public class EpubParser extends ReactContextBaseJavaModule {
|
||||
String rootPath;
|
||||
String contentDirPath;
|
||||
XPath xPath = XPathFactory.newInstance().newXPath();
|
||||
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
|
||||
|
||||
EpubParser(ReactApplicationContext context) throws Exception {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String getName() {
|
||||
return "EpubParser";
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void parse(String epubFilePath, String epubDirPath, Promise promise) {
|
||||
try{
|
||||
this.rootPath = epubDirPath;
|
||||
String novelCover = this.unzip(epubFilePath, epubDirPath);
|
||||
File contentFile = this.parseContainer(epubDirPath);
|
||||
this.contentDirPath = contentFile.getParent();
|
||||
WritableMap novel = (WritableMap) this.parseContent(contentFile);
|
||||
if(novelCover != null){
|
||||
novel.putString("cover", new File(epubDirPath, novelCover).getAbsolutePath());
|
||||
}
|
||||
promise.resolve(novel);
|
||||
} catch (Exception e) {
|
||||
promise.reject(e.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
public File parseContainer(String epubDir) throws Exception {
|
||||
Document doc = this.parserDocument(new File(epubDir, "META-INF/container.xml"));
|
||||
return new File(this.rootPath,
|
||||
((Element) doc.getElementsByTagName("rootfile").item(0)).getAttribute("full-path"));
|
||||
}
|
||||
|
||||
public ReadableMap parseContent(File contentFile) throws Exception {
|
||||
Document content = this.parserDocument(contentFile);
|
||||
WritableMap novel = new WritableNativeMap();
|
||||
novel.putString("name", this.getFirstElementByTag(content, "dc:title").getTextContent().trim());
|
||||
novel.putString("url", contentFile.getParent());
|
||||
novel.putString("author", this.getFirstElementByTag(content, "dc:creator").getTextContent().trim());
|
||||
novel.putArray("chapters", this.getChapters(content));
|
||||
return novel;
|
||||
}
|
||||
|
||||
public ReadableArray getChapters(Document doc) throws Exception {
|
||||
WritableArray chapters = new WritableNativeArray();
|
||||
Document toc = null;
|
||||
if (this.getFirstElementByTag(doc, "spine").getAttribute("toc") != null) {
|
||||
toc = this.parserDocument(new File(this.contentDirPath, "toc.ncx"));
|
||||
}
|
||||
NodeList itemrefs = this.getNodeListByTag(doc, "itemref");
|
||||
for (int i = 0; i < itemrefs.getLength(); i++) {
|
||||
WritableMap chapter = new WritableNativeMap();
|
||||
Element itemref = (Element) itemrefs.item(i);
|
||||
chapter.putString("name", itemref.getAttribute("idref"));
|
||||
Element item = this.getElementById(doc, chapter.getString("name"));
|
||||
chapter.putString("url", new File(this.contentDirPath, item.getAttribute("href")).getAbsolutePath());
|
||||
if(toc != null){
|
||||
chapter.putString("name", this.getChapterName(toc, item.getAttribute(("href"))));
|
||||
if(chapter.getString("name") == null) continue;
|
||||
}
|
||||
chapters.pushMap(chapter);
|
||||
}
|
||||
return chapters;
|
||||
}
|
||||
|
||||
public String getChapterName(Document doc, String href) throws Exception {
|
||||
String path = String.format("//*[starts-with(@src,'%1$s')]", href);
|
||||
Node node = ((NodeList) this.xPath.compile(path).evaluate(doc, XPathConstants.NODESET)).item(0);
|
||||
if(node != null){
|
||||
String text = node.getPreviousSibling().getTextContent().trim();
|
||||
if(text.isEmpty()) text = node.getPreviousSibling().getPreviousSibling().getTextContent().trim();
|
||||
return !text.isEmpty() ? text : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Element getElementById(Document doc, String id) throws Exception {
|
||||
return (Element) ((NodeList) this.xPath
|
||||
.compile(String.format("//*[@id='%1$s']", id))
|
||||
.evaluate(doc, XPathConstants.NODESET))
|
||||
.item(0);
|
||||
}
|
||||
|
||||
public NodeList getNodeListByTag(Document doc, String tag) throws Exception {
|
||||
return (NodeList)
|
||||
(
|
||||
this.xPath.compile(String.format("//*[contains(name(), '%1$s')]", tag))
|
||||
.evaluate(doc, XPathConstants.NODESET)
|
||||
);
|
||||
}
|
||||
|
||||
public Element getFirstElementByTag(Document doc, String tag) throws Exception {
|
||||
return (Element) this.getNodeListByTag(doc, tag).item(0);
|
||||
}
|
||||
|
||||
public Document parserDocument(File docFile) throws Exception {
|
||||
Document doc = this.db.parse(docFile);
|
||||
doc.getDocumentElement().normalize();
|
||||
return doc;
|
||||
}
|
||||
|
||||
public String escapeFilePath(String filePath){
|
||||
return filePath.replaceAll(":", "\uA789");
|
||||
}
|
||||
|
||||
public String unzip(String epubFilePath, String epubDirPath) throws Exception {
|
||||
ZipInputStream zis = new ZipInputStream(new FileInputStream(epubFilePath));
|
||||
ZipEntry zipEntry;
|
||||
int len;
|
||||
String novelCover = null;
|
||||
byte[] buffer = new byte[4096];
|
||||
while ((zipEntry = zis.getNextEntry()) != null) {
|
||||
String escapedFilePath = escapeFilePath(zipEntry.getName());
|
||||
if(Pattern.compile(".*cover.*\\.(png|jpeg|jpg)", Pattern.CASE_INSENSITIVE).matcher(escapedFilePath).matches()){
|
||||
novelCover = escapedFilePath;
|
||||
}
|
||||
File newFile = new File(epubDirPath, escapedFilePath);
|
||||
if(newFile.exists()) continue;
|
||||
newFile.getParentFile().mkdirs();
|
||||
FileOutputStream fos = new FileOutputStream(newFile);
|
||||
int writeCount = 0;
|
||||
while ((len = zis.read(buffer)) > 0) {
|
||||
writeCount += 1;
|
||||
fos.write(buffer, 0, len);
|
||||
}
|
||||
fos.close();
|
||||
if(writeCount == 0){
|
||||
newFile.delete();
|
||||
}
|
||||
}
|
||||
zis.closeEntry();
|
||||
zis.close();
|
||||
return novelCover;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.rajarsheechatterjee.EpubParser;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.facebook.react.ReactPackage;
|
||||
import com.facebook.react.bridge.NativeModule;
|
||||
import com.facebook.react.bridge.ReactApplicationContext;
|
||||
import com.facebook.react.uimanager.ViewManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class EpubParserPackage implements ReactPackage {
|
||||
@NonNull
|
||||
@Override
|
||||
public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactApplicationContext) {
|
||||
List<NativeModule> modules = new ArrayList<>();
|
||||
try {
|
||||
modules.add(new EpubParser(reactApplicationContext));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return modules;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactApplicationContext) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,9 @@ import android.view.WindowManager;
|
||||
import expo.modules.ReactActivityDelegateWrapper;
|
||||
import com.facebook.react.ReactActivity;
|
||||
import com.facebook.react.ReactActivityDelegate;
|
||||
import com.facebook.react.ReactRootView;
|
||||
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
|
||||
import com.facebook.react.defaults.DefaultReactActivityDelegate;
|
||||
import com.rajarsheechatterjee.VolumeButtonListener.VolumeButtonListener;
|
||||
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
|
||||
|
||||
import org.devio.rn.splashscreen.SplashScreen;
|
||||
|
||||
@@ -46,7 +46,7 @@ public class MainActivity extends ReactActivity {
|
||||
case KeyEvent.KEYCODE_VOLUME_UP:
|
||||
if (action == KeyEvent.ACTION_DOWN) {
|
||||
// volup
|
||||
VolumeButtonListener.up(VolumeButtonListener.getScrollAmount());
|
||||
VolumeButtonListener.up();
|
||||
if (!VolumeButtonListener.prevent)
|
||||
return super.dispatchKeyEvent(event);
|
||||
}
|
||||
@@ -54,7 +54,7 @@ public class MainActivity extends ReactActivity {
|
||||
case KeyEvent.KEYCODE_VOLUME_DOWN:
|
||||
if (action == KeyEvent.ACTION_DOWN) {
|
||||
// voldown
|
||||
VolumeButtonListener.down(VolumeButtonListener.getScrollAmount());
|
||||
VolumeButtonListener.down();
|
||||
if (!VolumeButtonListener.prevent)
|
||||
return super.dispatchKeyEvent(event);
|
||||
}
|
||||
@@ -77,29 +77,13 @@ public class MainActivity extends ReactActivity {
|
||||
|
||||
@Override
|
||||
protected ReactActivityDelegate createReactActivityDelegate() {
|
||||
return new ReactActivityDelegateWrapper(this, BuildConfig.IS_NEW_ARCHITECTURE_ENABLED,
|
||||
new MainActivityDelegate(this, getMainComponentName()
|
||||
return new ReactActivityDelegateWrapper(this, BuildConfig.IS_NEW_ARCHITECTURE_ENABLED, new DefaultReactActivityDelegate(
|
||||
this,
|
||||
getMainComponentName(),
|
||||
// If you opted-in for the New Architecture, we enable the Fabric Renderer.
|
||||
DefaultNewArchitectureEntryPoint.getFabricEnabled(), // fabricEnabled
|
||||
// If you opted-in for the New Architecture, we enable Concurrent React (i.e. React 18).
|
||||
DefaultNewArchitectureEntryPoint.getConcurrentReactEnabled() // concurrentRootEnabled
|
||||
));
|
||||
}
|
||||
|
||||
public static class MainActivityDelegate extends ReactActivityDelegate {
|
||||
public MainActivityDelegate(ReactActivity activity, String mainComponentName) {
|
||||
super(activity, mainComponentName);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ReactRootView createRootView() {
|
||||
ReactRootView reactRootView = new ReactRootView(getContext());
|
||||
// If you opted-in for the New Architecture, we enable the Fabric Renderer.
|
||||
reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);
|
||||
return reactRootView;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isConcurrentRootEnabled() {
|
||||
// If you opted-in for the New Architecture, we enable Concurrent Root (i.e. React 18).
|
||||
// More on this on https://reactjs.org/blog/2022/03/29/react-v18.html
|
||||
return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,34 +1,30 @@
|
||||
package com.rajarsheechatterjee.LNReader;
|
||||
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
import android.content.res.Configuration;
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.facebook.react.PackageList;
|
||||
import com.facebook.react.ReactApplication;
|
||||
import com.facebook.react.ReactInstanceManager;
|
||||
import com.facebook.react.ReactNativeHost;
|
||||
import com.facebook.react.ReactPackage;
|
||||
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
|
||||
import com.facebook.react.defaults.DefaultReactNativeHost;
|
||||
import com.facebook.soloader.SoLoader;
|
||||
|
||||
import com.rajarsheechatterjee.NavigationBarColor.NavigationBarColorPackage;
|
||||
import com.rajarsheechatterjee.VolumeButtonListener.VolumeButtonListenerPackage;
|
||||
import com.rajarsheechatterjee.EpubParser.EpubParserPackage;
|
||||
|
||||
import expo.modules.ApplicationLifecycleDispatcher;
|
||||
import expo.modules.ReactNativeHostWrapper;
|
||||
|
||||
import com.facebook.react.bridge.JSIModulePackage;
|
||||
import com.swmansion.reanimated.ReanimatedJSIModulePackage;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.List;
|
||||
|
||||
import org.devio.rn.splashscreen.SplashScreenReactPackage;
|
||||
import com.rnfs.RNFSPackage;
|
||||
|
||||
public class MainApplication extends Application implements ReactApplication {
|
||||
|
||||
private final ReactNativeHost mReactNativeHost =
|
||||
new ReactNativeHostWrapper(this, new ReactNativeHost(this) {
|
||||
new ReactNativeHostWrapper(this, new DefaultReactNativeHost(this) {
|
||||
@Override
|
||||
public boolean getUseDeveloperSupport() {
|
||||
return BuildConfig.DEBUG;
|
||||
@@ -36,10 +32,10 @@ public class MainApplication extends Application implements ReactApplication {
|
||||
|
||||
@Override
|
||||
protected List<ReactPackage> getPackages() {
|
||||
@SuppressWarnings("UnnecessaryLocalVariable")
|
||||
List<ReactPackage> packages = new PackageList(this).getPackages();
|
||||
packages.add(new com.rajarsheechatterjee.LNReader.NavigationBarColorPackage());
|
||||
packages.add(new NavigationBarColorPackage());
|
||||
packages.add(new VolumeButtonListenerPackage());
|
||||
packages.add(new EpubParserPackage());
|
||||
return packages;
|
||||
}
|
||||
|
||||
@@ -49,11 +45,14 @@ public class MainApplication extends Application implements ReactApplication {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JSIModulePackage getJSIModulePackage() {
|
||||
return new ReanimatedJSIModulePackage();
|
||||
protected boolean isNewArchEnabled() {
|
||||
return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
|
||||
}
|
||||
}
|
||||
);
|
||||
@Override
|
||||
protected Boolean isHermesEnabled() {
|
||||
return BuildConfig.IS_HERMES_ENABLED;
|
||||
}
|
||||
});
|
||||
|
||||
@Override
|
||||
public ReactNativeHost getReactNativeHost() {
|
||||
@@ -64,41 +63,11 @@ public class MainApplication extends Application implements ReactApplication {
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
SoLoader.init(this, /* native exopackage */ false);
|
||||
|
||||
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
|
||||
ApplicationLifecycleDispatcher.onApplicationCreate(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads Flipper in React Native templates. Call this in the onCreate method
|
||||
* with something like
|
||||
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
|
||||
*
|
||||
* @param context
|
||||
* @param reactInstanceManager
|
||||
*/
|
||||
private static void initializeFlipper(
|
||||
Context context, ReactInstanceManager reactInstanceManager) {
|
||||
if (BuildConfig.DEBUG) {
|
||||
try {
|
||||
/*
|
||||
* We use reflection here to pick up the class that initializes Flipper,
|
||||
* since Flipper library is not available in release mode
|
||||
*/
|
||||
Class<?> aClass = Class.forName("com.rajarsheechatterjee.LNReader.ReactNativeFlipper");
|
||||
aClass
|
||||
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
|
||||
.invoke(null, context, reactInstanceManager);
|
||||
} catch (ClassNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (NoSuchMethodException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvocationTargetException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
|
||||
// If you opted-in for the New Architecture, we load the native entry point for this app.
|
||||
DefaultNewArchitectureEntryPoint.load();
|
||||
}
|
||||
ApplicationLifecycleDispatcher.onApplicationCreate(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -106,4 +75,4 @@ public class MainApplication extends Application implements ReactApplication {
|
||||
super.onConfigurationChanged(newConfig);
|
||||
ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,18 @@
|
||||
package com.rajarsheechatterjee.LNReader;
|
||||
package com.rajarsheechatterjee.NavigationBarColor;
|
||||
|
||||
import android.animation.ArgbEvaluator;
|
||||
import android.animation.ValueAnimator;
|
||||
import android.annotation.TargetApi;
|
||||
import android.graphics.Color;
|
||||
import android.os.Build;
|
||||
import android.app.Activity;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
import androidx.annotation.UiThread;
|
||||
import com.facebook.react.bridge.Arguments;
|
||||
import com.facebook.react.bridge.Promise;
|
||||
import com.facebook.react.bridge.ReactApplicationContext;
|
||||
import com.facebook.react.bridge.ReactContextBaseJavaModule;
|
||||
import com.facebook.react.bridge.ReactMethod;
|
||||
import com.facebook.react.bridge.UiThreadUtil;
|
||||
import com.facebook.react.bridge.WritableMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.rajarsheechatterjee.LNReader;
|
||||
package com.rajarsheechatterjee.NavigationBarColor;
|
||||
import com.facebook.react.ReactPackage;
|
||||
import com.facebook.react.bridge.NativeModule;
|
||||
import com.facebook.react.bridge.ReactApplicationContext;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package com.rajarsheechatterjee.VolumeButtonListener;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import com.facebook.react.bridge.Arguments;
|
||||
import com.facebook.react.bridge.ReactApplicationContext;
|
||||
import com.facebook.react.bridge.ReactContextBaseJavaModule;
|
||||
import com.facebook.react.bridge.ReactMethod;
|
||||
import com.facebook.react.bridge.Promise;
|
||||
import com.facebook.react.bridge.WritableMap;
|
||||
import com.facebook.react.modules.core.DeviceEventManagerModule;
|
||||
|
||||
@@ -27,10 +27,9 @@ public class VolumeButtonListener extends ReactContextBaseJavaModule {
|
||||
|
||||
public static boolean prevent = false;
|
||||
|
||||
public static void sendEvent(boolean up, int amount) {
|
||||
public static void sendEvent(boolean up) {
|
||||
if (active) {
|
||||
WritableMap args = Arguments.createMap();
|
||||
args.putInt("scrollAmount", amount); // add scroll amount to event data
|
||||
if (up)
|
||||
appContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("VolumeUp", args);
|
||||
else
|
||||
@@ -38,22 +37,12 @@ public class VolumeButtonListener extends ReactContextBaseJavaModule {
|
||||
}
|
||||
}
|
||||
|
||||
public static void down(int amount) {
|
||||
sendEvent(false, amount);
|
||||
public static void down() {
|
||||
sendEvent(false);
|
||||
}
|
||||
|
||||
public static void up(int amount) {
|
||||
sendEvent(true, amount);
|
||||
}
|
||||
|
||||
private static int scrollAmount = 100;
|
||||
|
||||
public static void setScrollAmount(int amount) {
|
||||
scrollAmount = amount;
|
||||
}
|
||||
|
||||
public static int getScrollAmount() {
|
||||
return scrollAmount;
|
||||
public static void up() {
|
||||
sendEvent(true);
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
@@ -101,14 +90,4 @@ public class VolumeButtonListener extends ReactContextBaseJavaModule {
|
||||
public void removeListeners(Integer count) {
|
||||
// Keep: Required for RN built in Event Emitter Calls.
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void setVolumeButtonScrollAmount(int amount) {
|
||||
setScrollAmount(amount);
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void getVolumeButtonScrollAmount(Promise promise) {
|
||||
promise.resolve(getScrollAmount());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 936 B |
|
Before Width: | Height: | Size: 558 B |
|
Before Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 5.3 KiB |
@@ -25,4 +25,4 @@
|
||||
<!-- <item name="icon">@drawable/no_icon</item> -->
|
||||
<item name="android:windowBackground">@drawable/splashscreen</item>
|
||||
</style>
|
||||
</resources>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
|
||||
* directory of this source tree.
|
||||
*/
|
||||
package com.rajarsheechatterjee.LNReader;
|
||||
|
||||
import android.content.Context;
|
||||
import com.facebook.react.ReactInstanceManager;
|
||||
|
||||
/**
|
||||
* Class responsible of loading Flipper inside your React Native application. This is the release
|
||||
* flavor of it so it's empty as we don't want to load Flipper.
|
||||
*/
|
||||
public class ReactNativeFlipper {
|
||||
public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
|
||||
// Do nothing as we don't want to initialize Flipper on Release.
|
||||
}
|
||||
}
|
||||
@@ -4,66 +4,20 @@ import org.apache.tools.ant.taskdefs.condition.Os
|
||||
|
||||
buildscript {
|
||||
ext {
|
||||
buildToolsVersion = "31.0.0"
|
||||
buildToolsVersion = "33.0.0"
|
||||
minSdkVersion = 21
|
||||
compileSdkVersion = 31
|
||||
targetSdkVersion = 31
|
||||
compileSdkVersion = 33
|
||||
targetSdkVersion = 33
|
||||
|
||||
if (System.properties['os.arch'] == "aarch64") {
|
||||
// For M1 Users we need to use the NDK 24 which added support for aarch64
|
||||
ndkVersion = "24.0.8215888"
|
||||
} else {
|
||||
// Otherwise we default to the side-by-side NDK version from AGP.
|
||||
ndkVersion = "21.4.7075529"
|
||||
}
|
||||
// We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
|
||||
ndkVersion = "23.1.7779620"
|
||||
}
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath("com.android.tools.build:gradle:7.1.2")
|
||||
classpath("com.android.tools.build:gradle:7.4.1")
|
||||
classpath("com.facebook.react:react-native-gradle-plugin")
|
||||
classpath("de.undercouch:gradle-download-task:5.0.1")
|
||||
|
||||
// NOTE: Do not place your application dependencies here; they belong
|
||||
// in the individual module build.gradle files
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
exclusiveContent {
|
||||
// We get React Native's Android binaries exclusively through npm,
|
||||
// from a local Maven repo inside node_modules/react-native/.
|
||||
// (The use of exclusiveContent prevents looking elsewhere like Maven Central
|
||||
// and potentially getting a wrong version.)
|
||||
filter {
|
||||
includeGroup "com.facebook.react"
|
||||
}
|
||||
forRepository {
|
||||
maven {
|
||||
url "$rootDir/../node_modules/react-native/android"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
maven {
|
||||
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
|
||||
url(new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../android"))
|
||||
}
|
||||
maven {
|
||||
// Android JSC is installed from npm
|
||||
url(new File(["node", "--print", "require.resolve('jsc-android/package.json')"].execute(null, rootDir).text.trim(), "../dist"))
|
||||
}
|
||||
mavenCentral {
|
||||
// We don't want to fetch react-native from Maven Central as there are
|
||||
// older versions over there.
|
||||
content {
|
||||
excludeGroup "com.facebook.react"
|
||||
}
|
||||
}
|
||||
google()
|
||||
maven { url 'https://www.jitpack.io' }
|
||||
}
|
||||
}
|
||||
@@ -27,8 +27,6 @@ android.useAndroidX=true
|
||||
# Automatically convert third-party libraries to use AndroidX
|
||||
android.enableJetifier=true
|
||||
|
||||
# Version of flipper SDK to use with React Native
|
||||
FLIPPER_VERSION=0.125.0
|
||||
# Use this property to specify which architecture you want to build.
|
||||
# You can also override it from the CLI using
|
||||
# ./gradlew <task> -PreactNativeArchitectures=x86_64
|
||||
@@ -40,10 +38,14 @@ reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
|
||||
# are providing them.
|
||||
newArchEnabled=false
|
||||
|
||||
# Use this property to enable or disable the Hermes JS engine.
|
||||
# If set to false, you will be using JSC instead.
|
||||
hermesEnabled=true
|
||||
|
||||
# Enable GIF support in React Native images (~200 B increase)
|
||||
expo.gif.enabled=false
|
||||
# Enable webp support in React Native images (~85 KB increase)
|
||||
expo.webp.enabled=false
|
||||
# Enable animated webp support (~3.4 MB increase)
|
||||
# Disabled by default because iOS doesn't support animated webp
|
||||
expo.webp.animated=false
|
||||
expo.webp.animated=false
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
|
||||
@@ -231,4 +231,4 @@ eval "set -- $(
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
exec "$JAVACMD" "$@"
|
||||
|
||||
@@ -1,89 +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
|
||||
@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
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
rootProject.name = 'LNReader'
|
||||
|
||||
apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
|
||||
applyNativeModulesSettingsGradle(settings)
|
||||
|
||||
apply from: new File(["node", "--print", "require.resolve('expo/package.json')"].execute(null, rootDir).text.trim(), "../scripts/autolinking.gradle")
|
||||
useExpoModules()
|
||||
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
|
||||
|
||||
include ':app'
|
||||
includeBuild('../node_modules/react-native-gradle-plugin')
|
||||
|
||||
apply from: new File(["node", "--print", "require.resolve('expo/package.json')"].execute(null, rootDir).text.trim(), "../scripts/autolinking.gradle")
|
||||
useExpoModules()
|
||||
|
||||
include ':react-native-lottie-splash-screen'
|
||||
project(':react-native-lottie-splash-screen').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-lottie-splash-screen/android')
|
||||
|
||||
include ':react-native-fs'
|
||||
project(':react-native-fs').projectDir = new File(settingsDir, '../node_modules/react-native-fs/android')
|
||||
project(':react-native-fs').projectDir = new File(settingsDir, '../node_modules/react-native-fs/android')
|
||||
|
||||
@@ -3,9 +3,8 @@
|
||||
"name": "LNReader",
|
||||
"slug": "LNReader",
|
||||
"scheme": "lnreader",
|
||||
"notification": {
|
||||
"icon": "./assets/notification.png",
|
||||
"color": "#00adb5"
|
||||
}
|
||||
"plugins": [
|
||||
"expo-localization"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
module.exports = function (api) {
|
||||
api.cache(true);
|
||||
return {
|
||||
presets: ['babel-preset-expo'],
|
||||
presets: ['babel-preset-expo', 'module:metro-react-native-babel-preset'],
|
||||
plugins: [
|
||||
[
|
||||
'module-resolver',
|
||||
@@ -14,9 +14,12 @@ module.exports = function (api) {
|
||||
'@strings': './strings',
|
||||
'@redux': './src/redux',
|
||||
'@services': './src/services',
|
||||
'@sources': './src/sources',
|
||||
'@plugins': './src/plugins',
|
||||
'@utils': './src/utils',
|
||||
'@theme': './src/theme',
|
||||
'@navigators': './src/navigators',
|
||||
'@native': './src/native',
|
||||
'@api': './src/api',
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
module.exports = {
|
||||
preset: 'react-native',
|
||||
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
|
||||
};
|
||||
@@ -1,99 +1,90 @@
|
||||
{
|
||||
"name": "lnreader",
|
||||
"version": "1.1.17",
|
||||
"version": "2.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"android": "react-native run-android",
|
||||
"android": "react-native run-android --active-arch-only",
|
||||
"ios": "react-native run-ios",
|
||||
"start": "react-native start",
|
||||
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
|
||||
"prettier": "prettier --write \"./src/**/*.{js,jsx,ts,tsx}\"",
|
||||
"buildRelease": "cd android && ./gradlew clean && ./gradlew assembleRelease",
|
||||
"open": "open ./android/app/build/outputs/apk/release/",
|
||||
"sources:madara": "node scripts/generateMadaraSource.cjs",
|
||||
"source:generator": "node scripts/generateSource.cjs",
|
||||
"strings": "node scripts/stringTypes.cjs",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
"dependencies": {
|
||||
"@gorhom/bottom-sheet": "^4.4.5",
|
||||
"@react-native-async-storage/async-storage": "^1.18.1",
|
||||
"@react-native-community/clipboard": "^1.5.1",
|
||||
"@react-native-community/slider": "4.2.3",
|
||||
"@react-native-cookies/cookies": "^6.2.1",
|
||||
"@react-native-picker/picker": "2.4.9",
|
||||
"@react-navigation/drawer": "^6.0.1",
|
||||
"@react-native-community/slider": "4.4.2",
|
||||
"@react-native-google-signin/google-signin": "^11.0.0",
|
||||
"@react-native-picker/picker": "2.4.8",
|
||||
"@react-navigation/material-bottom-tabs": "^6.0.9",
|
||||
"@react-navigation/native": "^6.0.6",
|
||||
"@react-navigation/native": "^6.1.9",
|
||||
"@react-navigation/stack": "^6.0.11",
|
||||
"@reduxjs/toolkit": "^1.9.5",
|
||||
"@shopify/flash-list": "1.1.0",
|
||||
"@shopify/flash-list": "1.4.0",
|
||||
"cheerio": "^1.0.0-rc.10",
|
||||
"color": "^4.2.3",
|
||||
"dayjs": "^1.11.4",
|
||||
"expo": "^46.0.21",
|
||||
"expo-document-picker": "~10.3.0",
|
||||
"expo-file-system": "~14.1.0",
|
||||
"expo-haptics": "~11.3.0",
|
||||
"expo-keep-awake": "~10.2.0",
|
||||
"expo-linear-gradient": "~11.4.0",
|
||||
"expo-linking": "~3.2.4",
|
||||
"expo-localization": "~13.1.0",
|
||||
"expo-notifications": "~0.16.1",
|
||||
"expo-sqlite": "~10.3.0",
|
||||
"expo-web-browser": "~11.0.0",
|
||||
"expo": "^48.0.21",
|
||||
"expo-clipboard": "~4.1.2",
|
||||
"expo-document-picker": "~11.2.2",
|
||||
"expo-file-system": "~15.2.2",
|
||||
"expo-haptics": "~12.2.1",
|
||||
"expo-keep-awake": "~12.0.1",
|
||||
"expo-linear-gradient": "~12.1.2",
|
||||
"expo-linking": "~4.0.1",
|
||||
"expo-localization": "~14.1.1",
|
||||
"expo-notifications": "~0.18.1",
|
||||
"expo-speech": "~11.1.1",
|
||||
"expo-sqlite": "~11.1.1",
|
||||
"expo-web-browser": "~12.1.1",
|
||||
"i18n-js": "^3.8.0",
|
||||
"lodash-es": "^4.17.21",
|
||||
"qs": "^6.10.3",
|
||||
"react": "18.0.0",
|
||||
"react-fast-compare": "^3.2.1",
|
||||
"react-native": "^0.69.9",
|
||||
"react-native-background-actions": "^2.6.5",
|
||||
"react": "18.2.0",
|
||||
"react-native": "0.71.14",
|
||||
"react-native-background-actions": "^3.0.1",
|
||||
"react-native-device-info": "^8.4.7",
|
||||
"react-native-dotenv": "^3.4.9",
|
||||
"react-native-easing-gradient": "^1.0.0",
|
||||
"react-native-error-boundary": "^1.1.16",
|
||||
"react-native-fast-image": "^8.5.11",
|
||||
"react-native-fs": "^2.20.0",
|
||||
"react-native-gesture-handler": "~2.5.0",
|
||||
"react-native-gesture-handler": "~2.9.0",
|
||||
"react-native-lottie-splash-screen": "^1.0.1",
|
||||
"react-native-mmkv": "2.5.1",
|
||||
"react-native-pager-view": "^6.2.0",
|
||||
"react-native-paper": "^5.7.2",
|
||||
"react-native-reanimated": "~2.9.1",
|
||||
"react-native-safe-area-context": "4.3.1",
|
||||
"react-native-screens": "~3.15.0",
|
||||
"react-native-mmkv": "^2.11.0",
|
||||
"react-native-pager-view": "6.1.2",
|
||||
"react-native-paper": "^5.12.0",
|
||||
"react-native-reanimated": "^2.17.0",
|
||||
"react-native-safe-area-context": "4.5.0",
|
||||
"react-native-screens": "~3.20.0",
|
||||
"react-native-shimmer-placeholder": "^2.0.9",
|
||||
"react-native-tab-view": "^3.1.1",
|
||||
"react-native-tts": "^4.1.0",
|
||||
"react-native-tab-view": "^3.5.2",
|
||||
"react-native-vector-icons": "^9.0.0",
|
||||
"react-native-webview": "11.23.0",
|
||||
"react-redux": "^7.2.6",
|
||||
"redux-persist": "^6.0.0",
|
||||
"rn-fetch-blob": "^0.12.0",
|
||||
"react-native-webview": "11.26.0",
|
||||
"sanitize-html": "^2.7.0",
|
||||
"text-vide": "^1.7.0"
|
||||
"urlencode": "^2.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.21.4",
|
||||
"@react-native-community/eslint-config": "^3.0.1",
|
||||
"@babel/core": "^7.20.0",
|
||||
"@babel/runtime": "^7.20.0",
|
||||
"@react-native-community/eslint-config": "^3.2.0",
|
||||
"@tsconfig/react-native": "^2.0.2",
|
||||
"@types/color": "^3.0.3",
|
||||
"@types/i18n-js": "^3.8.2",
|
||||
"@types/jest": "^27.4.0",
|
||||
"@types/lodash-es": "^4.17.6",
|
||||
"@types/react-native": "~0.69.1",
|
||||
"@types/react": "^18.0.24",
|
||||
"@types/react-native-vector-icons": "^6.4.10",
|
||||
"@types/react-test-renderer": "^17.0.1",
|
||||
"@types/sanitize-html": "^2.6.2",
|
||||
"@typescript-eslint/eslint-plugin": "^5.57.1",
|
||||
"@typescript-eslint/parser": "^5.57.1",
|
||||
"@typescript-eslint/eslint-plugin": "^5.10.2",
|
||||
"@typescript-eslint/parser": "^5.10.2",
|
||||
"babel-plugin-module-resolver": "^4.1.0",
|
||||
"eslint": "^8.0.0",
|
||||
"eslint-plugin-react-native": "^4.0.0",
|
||||
"eslint": "^8.19.0",
|
||||
"eslint-plugin-react-native": "^4.1.0",
|
||||
"husky": "^7.0.4",
|
||||
"lint-staged": "^12.3.7",
|
||||
"prettier": "^2.8.8",
|
||||
"typescript": "^4.6.3"
|
||||
"metro-react-native-babel-preset": "^0.73.10",
|
||||
"prettier": "^2.4.1",
|
||||
"react-native-dotenv": "^3.4.9",
|
||||
"typescript": "4.8.4"
|
||||
},
|
||||
"resolutions": {
|
||||
"@types/react": "^17"
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
#!/usr/bin/python -u
|
||||
|
||||
'''
|
||||
Copyright 2009, The Android Open Source Project
|
||||
|
||||
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.
|
||||
'''
|
||||
|
||||
# Script to highlight adb logcat output for console
|
||||
# Originally written by Jeff Sharkey, http://jsharkey.org/
|
||||
# Piping detection and popen() added by other Android team members
|
||||
# Package filtering and output improvements by Jake Wharton, http://jakewharton.com
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import re
|
||||
import subprocess
|
||||
from subprocess import PIPE
|
||||
from ctypes import *
|
||||
from platform import win32_ver
|
||||
|
||||
__version__ = '2.1.0+Win10'
|
||||
|
||||
win_ver = win32_ver()[0]
|
||||
show_colors = (win_ver == '10' or win_ver == '') and sys.stdout.isatty()
|
||||
|
||||
LOG_LEVELS = 'VDIWEF'
|
||||
LOG_LEVELS_MAP = dict([(LOG_LEVELS[i], i) for i in range(len(LOG_LEVELS))])
|
||||
parser = argparse.ArgumentParser(description='Filter logcat by package name')
|
||||
parser.add_argument('package', nargs='*', help='Application package name(s)')
|
||||
parser.add_argument('-w', '--tag-width', metavar='N', dest='tag_width', type=int, default=23, help='Width of log tag')
|
||||
parser.add_argument('-l', '--min-level', dest='min_level', type=str, choices=LOG_LEVELS+LOG_LEVELS.lower(), default='V', help='Minimum level to be displayed')
|
||||
parser.add_argument('--color-gc', dest='color_gc', action='store_true', help='Color garbage collection')
|
||||
parser.add_argument('--always-display-tags', dest='always_tags', action='store_true',help='Always display the tag name')
|
||||
parser.add_argument('--current', dest='current_app', action='store_true',help='Filter logcat by current running app')
|
||||
parser.add_argument('-s', '--serial', dest='device_serial', help='Device serial number (adb -s option)')
|
||||
parser.add_argument('-d', '--device', dest='use_device', action='store_true', help='Use first device for log input (adb -d option)')
|
||||
parser.add_argument('-e', '--emulator', dest='use_emulator', action='store_true', help='Use first emulator for log input (adb -e option)')
|
||||
parser.add_argument('-c', '--clear', dest='clear_logcat', action='store_true', help='Clear the entire log before running')
|
||||
parser.add_argument('-t', '--tag', dest='tag', action='append', help='Filter output by specified tag(s)')
|
||||
parser.add_argument('-i', '--ignore-tag', dest='ignored_tag', action='append', help='Filter output by ignoring specified tag(s)')
|
||||
parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__, help='Print the version number and exit')
|
||||
parser.add_argument('-a', '--all', dest='all', action='store_true', default=False, help='Print all log messages')
|
||||
parser.add_argument('-o', '--output', dest='output', type=str, default='', help='Output filename')
|
||||
parser.add_argument('-n', '--no-color', dest='no_color', action='store_true', help='Disable colors')
|
||||
parser.add_argument('-r', '--regex', dest='regex', type=str, help='Print only when matches REGEX and REGEX is regular expression logcat -e REGEX')
|
||||
|
||||
args = parser.parse_args()
|
||||
min_level = LOG_LEVELS_MAP[args.min_level.upper()]
|
||||
|
||||
if (args.no_color):
|
||||
show_colors = False
|
||||
|
||||
package = args.package
|
||||
if len(package) == 0:
|
||||
package.append('com.rajarsheechatterjee.LNReader')
|
||||
|
||||
# enabling Windows 10 VT100 support
|
||||
def enableVT100():
|
||||
STD_OUTPUT_HANDLE = -11
|
||||
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
|
||||
|
||||
stdout = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
|
||||
if stdout == -1:
|
||||
raise WinError()
|
||||
|
||||
mode = c_uint()
|
||||
if windll.kernel32.GetConsoleMode(stdout, byref(mode)) == 0:
|
||||
raise WinError()
|
||||
|
||||
mode.value = mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
||||
|
||||
if windll.kernel32.SetConsoleMode(stdout, mode) == 0:
|
||||
raise WinError()
|
||||
|
||||
if (show_colors):
|
||||
enableVT100()
|
||||
|
||||
output_file = False
|
||||
if (args.output):
|
||||
output_file = open(args.output, 'a+')
|
||||
|
||||
base_adb_command = ['adb']
|
||||
if args.device_serial:
|
||||
base_adb_command.extend(['-s', args.device_serial])
|
||||
if args.use_device:
|
||||
base_adb_command.append('-d')
|
||||
if args.use_emulator:
|
||||
base_adb_command.append('-e')
|
||||
|
||||
if args.current_app:
|
||||
system_dump_command = base_adb_command + ["shell", "dumpsys", "activity", "activities"]
|
||||
system_dump = subprocess.Popen(system_dump_command, stdout=PIPE, stderr=PIPE).communicate()[0]
|
||||
running_package_name = re.search(".*TaskRecord.*A[= ]([^ ^}]*)", system_dump).group(1)
|
||||
package.append(running_package_name)
|
||||
|
||||
if len(package) == 0:
|
||||
args.all = True
|
||||
|
||||
# Store the names of packages for which to match all processes.
|
||||
catchall_package = list(filter(lambda package: package.find(":") == -1, package))
|
||||
# Store the name of processes to match exactly.
|
||||
named_processes = filter(lambda package: package.find(":") != -1, package)
|
||||
# Convert default process names from <package>: (cli notation) to <package> (android notation) in the exact names match group.
|
||||
named_processes = map(lambda package: package if package.find(":") != len(package) - 1 else package[:-1], named_processes)
|
||||
|
||||
header_size = args.tag_width + 1 + 3 + 1 # space, level, space
|
||||
|
||||
width = -1
|
||||
try:
|
||||
# Get the current terminal width
|
||||
import fcntl, termios, struct
|
||||
h, width = struct.unpack('hh', fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack('hh', 0, 0)))
|
||||
except:
|
||||
pass
|
||||
|
||||
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
|
||||
|
||||
RESET = '\033[0m'
|
||||
|
||||
def termcolor(fg=None, bg=None):
|
||||
codes = []
|
||||
if fg is not None: codes.append('3%d' % fg)
|
||||
if bg is not None: codes.append('10%d' % bg)
|
||||
return '\033[%sm' % ';'.join(codes) if codes else ''
|
||||
|
||||
def colorize(message, fg=None, bg=None):
|
||||
return termcolor(fg, bg) + message + RESET
|
||||
|
||||
def indent_wrap(message):
|
||||
if width == -1:
|
||||
return message
|
||||
message = message.replace('\t', ' ')
|
||||
wrap_area = width - header_size
|
||||
messagebuf = ''
|
||||
current = 0
|
||||
while current < len(message):
|
||||
next = min(current + wrap_area, len(message))
|
||||
messagebuf += message[current:next]
|
||||
if next < len(message):
|
||||
messagebuf += '\n'
|
||||
messagebuf += ' ' * header_size
|
||||
current = next
|
||||
return messagebuf
|
||||
|
||||
|
||||
LAST_USED = [RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN]
|
||||
KNOWN_TAGS = {
|
||||
'dalvikvm': WHITE,
|
||||
'Process': WHITE,
|
||||
'ActivityManager': WHITE,
|
||||
'ActivityThread': WHITE,
|
||||
'AndroidRuntime': CYAN,
|
||||
'jdwp': WHITE,
|
||||
'StrictMode': WHITE,
|
||||
'DEBUG': YELLOW,
|
||||
}
|
||||
|
||||
def allocate_color(tag):
|
||||
# this will allocate a unique format for the given tag
|
||||
# since we dont have very many colors, we always keep track of the LRU
|
||||
if tag not in KNOWN_TAGS:
|
||||
KNOWN_TAGS[tag] = LAST_USED[0]
|
||||
color = KNOWN_TAGS[tag]
|
||||
if color in LAST_USED:
|
||||
LAST_USED.remove(color)
|
||||
LAST_USED.append(color)
|
||||
return color
|
||||
|
||||
NO_COLOR = re.compile(r'\033\[.*?m')
|
||||
|
||||
def output(line):
|
||||
line_nocolor = '' if show_colors and not output_file else NO_COLOR.sub('', line)
|
||||
print(line if show_colors else line_nocolor)
|
||||
if (output_file):
|
||||
output_file.write(line_nocolor + '\n')
|
||||
|
||||
RULES = {
|
||||
# StrictMode policy violation; ~duration=319 ms: android.os.StrictMode$StrictModeDiskWriteViolation: policy=31 violation=1
|
||||
re.compile(r'^(StrictMode policy violation)(; ~duration=)(\d+ ms)')
|
||||
: r'%s\1%s\2%s\3%s' % (termcolor(RED), RESET, termcolor(YELLOW), RESET),
|
||||
}
|
||||
|
||||
# Only enable GC coloring if the user opted-in
|
||||
if args.color_gc:
|
||||
# GC_CONCURRENT freed 3617K, 29% free 20525K/28648K, paused 4ms+5ms, total 85ms
|
||||
key = re.compile(r'^(GC_(?:CONCURRENT|FOR_M?ALLOC|EXTERNAL_ALLOC|EXPLICIT) )(freed <?\d+.)(, \d+\% free \d+./\d+., )(paused \d+ms(?:\+\d+ms)?)')
|
||||
val = r'\1%s\2%s\3%s\4%s' % (termcolor(GREEN), RESET, termcolor(YELLOW), RESET)
|
||||
|
||||
RULES[key] = val
|
||||
|
||||
|
||||
TAGTYPES = {
|
||||
'V': colorize(' V ', fg=WHITE, bg=BLACK),
|
||||
'D': colorize(' D ', fg=BLACK, bg=BLUE),
|
||||
'I': colorize(' I ', fg=BLACK, bg=GREEN),
|
||||
'W': colorize(' W ', fg=BLACK, bg=YELLOW),
|
||||
'E': colorize(' E ', fg=BLACK, bg=RED),
|
||||
'F': colorize(' F ', fg=BLACK, bg=RED),
|
||||
}
|
||||
|
||||
PID_LINE = re.compile(r'^\w+\s+(\w+)\s+\w+\s+\w+\s+\w+\s+\w+\s+\w+\s+\w\s([\w|\.|\/]+)$')
|
||||
PID_START = re.compile(r'^.*: Start proc ([a-zA-Z0-9._:]+) for ([a-z]+ [^:]+): pid=(\d+) uid=(\d+) gids=(.*)$')
|
||||
PID_START_5_1 = re.compile(r'^.*: Start proc (\d+):([a-zA-Z0-9._:]+)/[a-z0-9]+ for (.*)$')
|
||||
PID_START_DALVIK = re.compile(r'^E/dalvikvm\(\s*(\d+)\): >>>>> ([a-zA-Z0-9._:]+) \[ userId:0 \| appId:(\d+) \]$')
|
||||
PID_KILL = re.compile(r'^Killing (\d+):([a-zA-Z0-9._:]+)/[^:]+: (.*)$')
|
||||
PID_LEAVE = re.compile(r'^No longer want ([a-zA-Z0-9._:]+) \(pid (\d+)\): .*$')
|
||||
PID_DEATH = re.compile(r'^Process ([a-zA-Z0-9._:]+) \(pid (\d+)\) has died.?$')
|
||||
LOG_LINE = re.compile(r'^([A-Z])/(.+?)\( *(\d+)\): (.*?)$')
|
||||
BUG_LINE = re.compile(r'.*nativeGetEnabledTags.*')
|
||||
BACKTRACE_LINE = re.compile(r'^#(.*?)pc\s(.*?)$')
|
||||
|
||||
adb_command = base_adb_command[:]
|
||||
adb_command.append('logcat')
|
||||
adb_command.extend(['-v', 'brief'])
|
||||
if args.regex:
|
||||
adb_command.extend(['-e',args.regex])
|
||||
|
||||
# Clear log before starting logcat
|
||||
if args.clear_logcat:
|
||||
adb_clear_command = list(adb_command)
|
||||
adb_clear_command.append('-c')
|
||||
adb_clear = subprocess.Popen(adb_clear_command)
|
||||
|
||||
while adb_clear.poll() is None:
|
||||
pass
|
||||
|
||||
# This is a ducktype of the subprocess.Popen object
|
||||
class FakeStdinProcess():
|
||||
def __init__(self):
|
||||
self.stdout = sys.stdin
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
if sys.stdin.isatty():
|
||||
adb = subprocess.Popen(adb_command, stdin=PIPE, stdout=PIPE)
|
||||
else:
|
||||
adb = FakeStdinProcess()
|
||||
pids = set()
|
||||
last_tag = None
|
||||
app_pid = None
|
||||
|
||||
def match_packages(token):
|
||||
if len(package) == 0:
|
||||
return True
|
||||
if token in named_processes:
|
||||
return True
|
||||
index = token.find(':')
|
||||
return (token in catchall_package) if index == -1 else (token[:index] in catchall_package)
|
||||
|
||||
def parse_death(tag, message):
|
||||
if tag != 'ActivityManager':
|
||||
return None, None
|
||||
kill = PID_KILL.match(message)
|
||||
if kill:
|
||||
pid = kill.group(1)
|
||||
package_line = kill.group(2)
|
||||
if match_packages(package_line) and pid in pids:
|
||||
return pid, package_line
|
||||
leave = PID_LEAVE.match(message)
|
||||
if leave:
|
||||
pid = leave.group(2)
|
||||
package_line = leave.group(1)
|
||||
if match_packages(package_line) and pid in pids:
|
||||
return pid, package_line
|
||||
death = PID_DEATH.match(message)
|
||||
if death:
|
||||
pid = death.group(2)
|
||||
package_line = death.group(1)
|
||||
if match_packages(package_line) and pid in pids:
|
||||
return pid, package_line
|
||||
return None, None
|
||||
|
||||
def parse_start_proc(line):
|
||||
start = PID_START_5_1.match(line)
|
||||
if start is not None:
|
||||
line_pid, line_package, target = start.groups()
|
||||
return line_package, target, line_pid, '', ''
|
||||
start = PID_START.match(line)
|
||||
if start is not None:
|
||||
line_package, target, line_pid, line_uid, line_gids = start.groups()
|
||||
return line_package, target, line_pid, line_uid, line_gids
|
||||
start = PID_START_DALVIK.match(line)
|
||||
if start is not None:
|
||||
line_pid, line_package, line_uid = start.groups()
|
||||
return line_package, '', line_pid, line_uid, ''
|
||||
return None
|
||||
|
||||
def tag_in_tags_regex(tag, tags):
|
||||
return any(re.match(r'^' + t + r'$', tag) for t in map(str.strip, tags))
|
||||
|
||||
ps_command = base_adb_command + ['shell', 'ps']
|
||||
ps_pid = subprocess.Popen(ps_command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
|
||||
while True:
|
||||
try:
|
||||
line = ps_pid.stdout.readline().decode('utf-8', 'replace').strip()
|
||||
except KeyboardInterrupt:
|
||||
break
|
||||
if len(line) == 0:
|
||||
break
|
||||
|
||||
pid_match = PID_LINE.match(line)
|
||||
if pid_match is not None:
|
||||
pid = pid_match.group(1)
|
||||
proc = pid_match.group(2)
|
||||
if proc in catchall_package:
|
||||
seen_pids = True
|
||||
pids.add(pid)
|
||||
|
||||
while adb.poll() is None:
|
||||
try:
|
||||
line = adb.stdout.readline().decode('utf-8', 'replace').strip()
|
||||
except KeyboardInterrupt:
|
||||
break
|
||||
if len(line) == 0:
|
||||
break
|
||||
|
||||
bug_line = BUG_LINE.match(line)
|
||||
if bug_line is not None:
|
||||
continue
|
||||
|
||||
log_line = LOG_LINE.match(line)
|
||||
if log_line is None:
|
||||
continue
|
||||
|
||||
level, tag, owner, message = log_line.groups()
|
||||
tag = tag.strip()
|
||||
start = parse_start_proc(line)
|
||||
if start:
|
||||
line_package, target, line_pid, line_uid, line_gids = start
|
||||
if match_packages(line_package):
|
||||
pids.add(line_pid)
|
||||
|
||||
app_pid = line_pid
|
||||
|
||||
linebuf = '\n'
|
||||
linebuf += colorize(' ' * (header_size - 1), bg=WHITE)
|
||||
linebuf += indent_wrap(' Process %s created for %s\n' % (line_package, target))
|
||||
linebuf += colorize(' ' * (header_size - 1), bg=WHITE)
|
||||
linebuf += ' PID: %s UID: %s GIDs: %s' % (line_pid, line_uid, line_gids)
|
||||
linebuf += '\n'
|
||||
output(linebuf)
|
||||
last_tag = None # Ensure next log gets a tag printed
|
||||
|
||||
dead_pid, dead_pname = parse_death(tag, message)
|
||||
if dead_pid:
|
||||
pids.remove(dead_pid)
|
||||
linebuf = '\n'
|
||||
linebuf += colorize(' ' * (header_size - 1), bg=RED)
|
||||
linebuf += ' Process %s (PID: %s) ended' % (dead_pname, dead_pid)
|
||||
linebuf += '\n'
|
||||
output(linebuf)
|
||||
last_tag = None # Ensure next log gets a tag printed
|
||||
|
||||
# Make sure the backtrace is printed after a native crash
|
||||
if tag == 'DEBUG':
|
||||
bt_line = BACKTRACE_LINE.match(message.lstrip())
|
||||
if bt_line is not None:
|
||||
message = message.lstrip()
|
||||
owner = app_pid
|
||||
|
||||
if not args.all and owner not in pids:
|
||||
continue
|
||||
if level in LOG_LEVELS_MAP and LOG_LEVELS_MAP[level] < min_level:
|
||||
continue
|
||||
if args.ignored_tag and tag_in_tags_regex(tag, args.ignored_tag):
|
||||
continue
|
||||
if args.tag and not tag_in_tags_regex(tag, args.tag):
|
||||
continue
|
||||
|
||||
linebuf = ''
|
||||
|
||||
if args.tag_width > 0:
|
||||
# right-align tag title and allocate color if needed
|
||||
if tag != last_tag or args.always_tags:
|
||||
last_tag = tag
|
||||
color = allocate_color(tag)
|
||||
tag = tag[-args.tag_width:].rjust(args.tag_width)
|
||||
linebuf += colorize(tag, fg=color)
|
||||
else:
|
||||
linebuf += ' ' * args.tag_width
|
||||
linebuf += ' '
|
||||
|
||||
# write out level colored edge
|
||||
if level in TAGTYPES:
|
||||
linebuf += TAGTYPES[level]
|
||||
else:
|
||||
linebuf += ' ' + level + ' '
|
||||
linebuf += ' '
|
||||
|
||||
# format tag message using rules
|
||||
for matcher in RULES:
|
||||
replace = RULES[matcher]
|
||||
message = matcher.sub(replace, message)
|
||||
|
||||
linebuf += indent_wrap(message)
|
||||
output(linebuf)
|
||||
|
||||
if (output_file):
|
||||
output_file.close()
|
||||
@@ -1,7 +0,0 @@
|
||||
module.exports = {
|
||||
project: {
|
||||
ios: {},
|
||||
android: {},
|
||||
},
|
||||
assets: ['./assets/fonts/'],
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
1. Create `index.html` with [template](./template.index.html) content in this folder/
|
||||
2. Replace `${hmtl}` by your chapter text.
|
||||
3. Edit files in `/android/app/src/main/assets` folder.
|
||||
4. Open index.html in browse for quick test.
|
||||
5. rebuild the app to test in real reader.
|
||||
@@ -0,0 +1,71 @@
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
|
||||
<style>
|
||||
:root {
|
||||
--StatusBar-currentHeight: 30px;
|
||||
--readerSettings-theme: #292832;
|
||||
--readerSettings-padding: 2%;
|
||||
--readerSettings-textSize: 16px;
|
||||
--readerSettings-textColor: #CCCCCC;
|
||||
--readerSettings-textAlign: left;
|
||||
--readerSettings-lineHeight: 1.5;
|
||||
--readerSettings-fontFamily: ;
|
||||
--theme-primary: rgb(0, 87, 206);
|
||||
--theme-onPrimary: rgb(255, 255, 255);
|
||||
--theme-secondary: rgb(88, 94, 113);
|
||||
--theme-onSecondary: rgb(255, 255, 255);
|
||||
--theme-surface: rgb(254, 251, 255);
|
||||
--theme-surface-0-9: rgba(254, 251, 255, 0.9);
|
||||
--theme-onSurface: rgb(27, 27, 31);
|
||||
--theme-outline: rgb(117, 119, 128);
|
||||
--chapterCtn-height: 700px;
|
||||
}
|
||||
body {
|
||||
background-color: var(--readerSettings-theme);
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Lora';
|
||||
src: url("../android/app/src/main/assets/fonts/lora.ttf");
|
||||
}
|
||||
</style>
|
||||
<script>
|
||||
let hidden = true;
|
||||
window.ReactNativeWebView = {};
|
||||
window.ReactNativeWebView.postMessage = (data) => {
|
||||
const event = JSON.parse(data);
|
||||
switch (event.type) {
|
||||
case 'hide':
|
||||
if(!hidden) {
|
||||
scrollHandler.hide()
|
||||
}else{
|
||||
scrollHandler.show();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
console.log('unsupported event', event.type);
|
||||
break;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
<link rel="stylesheet" href="../android/app/src/main/assets/css/index.css">
|
||||
<script async>
|
||||
var showScrollPercentage = true;
|
||||
var swipeGestures = false;
|
||||
var autoSaveInterval = 2222;
|
||||
</script>
|
||||
<script defer src="../android/app/src/main/assets/js/index.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="chapterCtn" onclick="reader.post({type:'hide'})">
|
||||
<chapter data-plugin-id='pluginId' data-novel-id='novelId' data-chapter-id='chapterId'>
|
||||
${html}
|
||||
</chapter>
|
||||
<div class="d-none" id="ScrollBar"></div>
|
||||
<div id="reader-percentage"></div>
|
||||
</div>
|
||||
</body>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,79 +0,0 @@
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const prettier = require('prettier');
|
||||
const prettierConfig = require('../.prettierrc');
|
||||
|
||||
const MadaraSources = require('../src/sources/multisrc/madara/MadaraSources.json');
|
||||
const AllSources = require('../src/sources/sources.json');
|
||||
|
||||
const getScraperName = scraperName => {
|
||||
let name = scraperName
|
||||
.replace(/\s+/g, '')
|
||||
.replace(/-/g, 'Dash')
|
||||
.replace(/\./g, 'Dot')
|
||||
.replace('1st', 'First');
|
||||
|
||||
return name;
|
||||
};
|
||||
|
||||
let content =
|
||||
"/**\n * This file is auto-generated\n */\n\nimport MadaraScraper from './MadaraScraper';\n\n";
|
||||
|
||||
MadaraSources.forEach(source => {
|
||||
content =
|
||||
content +
|
||||
`export const ${getScraperName(
|
||||
source.sourceName,
|
||||
)}Scraper = new MadaraScraper(${source.sourceId}, "${source.baseUrl}", "${
|
||||
source.sourceName
|
||||
}", ${source.options ? JSON.stringify(source.options) : ''});\n\n`;
|
||||
});
|
||||
|
||||
content = prettier.format(content, {
|
||||
parser: 'typescript',
|
||||
...prettierConfig,
|
||||
});
|
||||
|
||||
fs.writeFile(
|
||||
path.resolve(process.cwd(), 'src/sources/multisrc/madara/MadaraGenerator.ts'),
|
||||
content,
|
||||
error => {
|
||||
if (error) {
|
||||
console.log(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
MadaraSources.forEach(madaraSource => {
|
||||
if (!AllSources.some(source => source.sourceId === madaraSource.sourceId)) {
|
||||
let allSourcesContent = AllSources;
|
||||
|
||||
allSourcesContent.push({
|
||||
sourceId: madaraSource.sourceId,
|
||||
sourceName: madaraSource.sourceName,
|
||||
icon: `https://github.com/LNReader/lnreader-sources/blob/main/multisrc/madara/icons/${madaraSource.sourceName
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()}.png?raw=true`,
|
||||
url: madaraSource.baseUrl,
|
||||
lang: madaraSource.options.lang || 'English',
|
||||
});
|
||||
|
||||
allSourcesContent = JSON.stringify(allSourcesContent);
|
||||
|
||||
allSourcesContent = prettier.format(allSourcesContent, {
|
||||
parser: 'json5',
|
||||
quoteProps: 'preserve',
|
||||
trailingComma: 'none',
|
||||
});
|
||||
|
||||
fs.writeFile(
|
||||
path.resolve(process.cwd(), 'src/sources/sources.json'),
|
||||
allSourcesContent,
|
||||
error => {
|
||||
if (error) {
|
||||
console.log(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -1,327 +0,0 @@
|
||||
/**
|
||||
* This script can be used to generate sources
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const prettier = require('prettier');
|
||||
const prettierConfig = require('../.prettierrc');
|
||||
|
||||
const AllSources = require('../src/sources/sources.json');
|
||||
|
||||
const getLanguageCode = language => {
|
||||
const codes = {
|
||||
English: 'en',
|
||||
Arabic: 'ar',
|
||||
French: 'fr',
|
||||
Turkish: 'tr',
|
||||
Chinese: 'cn',
|
||||
Japanese: 'jp',
|
||||
Vietnamese: 'vi',
|
||||
Korean: 'kr',
|
||||
};
|
||||
|
||||
return codes[language];
|
||||
};
|
||||
|
||||
try {
|
||||
if (process.argv[2]) {
|
||||
const source = JSON.parse(
|
||||
fs.readFileSync(path.resolve(process.cwd(), process.argv[2]), 'utf8'),
|
||||
);
|
||||
|
||||
const isDuplicate = AllSources.some(
|
||||
item => item.sourceId === source.sourceId,
|
||||
);
|
||||
|
||||
const content = `
|
||||
import * as cheerio from 'cheerio';
|
||||
import { isUrlAbsolute } from '../../utils/isAbsoluteUrl';
|
||||
${
|
||||
source?.options?.imports?.toaster
|
||||
? "import { showToast } from '../../hooks/showToast'"
|
||||
: ''
|
||||
};
|
||||
import {
|
||||
SourceChapter,
|
||||
SourceChapterItem,
|
||||
SourceNovel,
|
||||
SourceNovelItem,
|
||||
} from '../types';
|
||||
|
||||
const sourceId = ${source.sourceId};
|
||||
const sourceName = "${source.sourceName}";
|
||||
const baseUrl = "${source.baseUrl}";
|
||||
|
||||
${
|
||||
!source.popularNovels.url.includes('${page}')
|
||||
? '// eslint-disable-next-line @typescript-eslint/no-unused-vars'
|
||||
: ''
|
||||
}
|
||||
const popularNovels = async (page: number) => {
|
||||
const url = \`${source.popularNovels.url}\`;
|
||||
|
||||
const result = await fetch(url);
|
||||
const body = await result.text();
|
||||
|
||||
const loadedCheerio = cheerio.load(body);
|
||||
|
||||
const novels: SourceNovelItem[] = [];
|
||||
|
||||
loadedCheerio('${
|
||||
source.popularNovels.selectors.novelList
|
||||
}').each(function () {
|
||||
let novelUrl = loadedCheerio(this).find('${
|
||||
source.popularNovels.selectors.novelUrl
|
||||
}').attr('href');
|
||||
|
||||
if (novelUrl && !isUrlAbsolute(novelUrl)) {
|
||||
novelUrl = baseUrl + novelUrl;
|
||||
}
|
||||
|
||||
if (novelUrl) {
|
||||
const novelName = loadedCheerio(this).find('${
|
||||
source.popularNovels.selectors.novelName
|
||||
}').text().trim();
|
||||
let novelCover = loadedCheerio(this).find('${
|
||||
source.popularNovels.selectors.novelCover
|
||||
}').attr('src');
|
||||
|
||||
if (novelCover && !isUrlAbsolute(novelCover)) {
|
||||
novelCover = baseUrl + novelCover;
|
||||
}
|
||||
|
||||
const novel = {
|
||||
sourceId,
|
||||
novelUrl,
|
||||
novelName,
|
||||
novelCover,
|
||||
};
|
||||
|
||||
novels.push(novel);
|
||||
}
|
||||
});
|
||||
|
||||
return { novels };
|
||||
|
||||
const parseNovelAndChapters = async (novelUrl: string) => {
|
||||
const url = novelUrl;
|
||||
|
||||
const result = await fetch(url);
|
||||
const body = await result.text();
|
||||
|
||||
let loadedCheerio = cheerio.load(body);
|
||||
|
||||
const novel: SourceNovel = {
|
||||
sourceId,
|
||||
sourceName,
|
||||
url: novelUrl,
|
||||
novelUrl,
|
||||
chapters: [],
|
||||
};
|
||||
|
||||
novel.novelName = loadedCheerio('${
|
||||
source.novelAndChapters.selectors.novelName
|
||||
}').text();
|
||||
|
||||
let novelCover = loadedCheerio('${
|
||||
source.novelAndChapters.selectors.novelCover
|
||||
}').attr('src');
|
||||
|
||||
novel.novelCover = novelCover
|
||||
? isUrlAbsolute(novelCover)
|
||||
? novelCover
|
||||
: baseUrl + novelCover
|
||||
: undefined;
|
||||
|
||||
novel.summary = loadedCheerio('${
|
||||
source.novelAndChapters.selectors.summary
|
||||
}').text().trim();
|
||||
|
||||
novel.author = loadedCheerio('${
|
||||
source.novelAndChapters.selectors.author
|
||||
}').text().trim();
|
||||
|
||||
novel.genre = loadedCheerio('${
|
||||
source.novelAndChapters.selectors.genre
|
||||
}').text().trim()${source?.options?.status?.replace || ''};
|
||||
|
||||
|
||||
novel.status = loadedCheerio('${
|
||||
source.novelAndChapters.selectors.status
|
||||
}').text().trim();
|
||||
|
||||
loadedCheerio('${
|
||||
source.novelAndChapters.selectors.chapterList
|
||||
}').each(function () {
|
||||
let chapterUrl = loadedCheerio(this).find('a').attr('href');
|
||||
|
||||
if (chapterUrl && !isUrlAbsolute(chapterUrl)) {
|
||||
chapterUrl = baseUrl + chapterUrl;
|
||||
}
|
||||
|
||||
if (chapterUrl) {
|
||||
const chapterName = loadedCheerio(this).find('${
|
||||
source.novelAndChapters.selectors.chapterName
|
||||
}').text().trim();
|
||||
const releaseDate = ${
|
||||
source.novelAndChapters.selectors.releaseDate
|
||||
? `loadedCheerio(this).find('${source.novelAndChapters.selectors.releaseDate}').text();`
|
||||
: null
|
||||
}
|
||||
|
||||
const chapter: SourceChapterItem = {
|
||||
chapterName,
|
||||
releaseDate,
|
||||
chapterUrl,
|
||||
};
|
||||
|
||||
novel.chapters?.push(chapter);
|
||||
}
|
||||
});
|
||||
|
||||
return novel;
|
||||
};
|
||||
|
||||
const parseChapter = async (novelUrl: string, chapterUrl: string) => {
|
||||
const url = chapterUrl;
|
||||
|
||||
const result = await fetch(url);
|
||||
const body = await result.text();
|
||||
|
||||
const loadedCheerio = cheerio.load(body);
|
||||
|
||||
const chapterName = loadedCheerio('${
|
||||
source.chapter.selectors.chapterName
|
||||
}').text();
|
||||
const chapterText = loadedCheerio('${
|
||||
source.chapter.selectors.chapterText
|
||||
}').html() || '';
|
||||
|
||||
const chapter: SourceChapter = {
|
||||
sourceId,
|
||||
novelUrl,
|
||||
chapterUrl,
|
||||
chapterName,
|
||||
chapterText,
|
||||
};
|
||||
|
||||
return chapter;
|
||||
};
|
||||
|
||||
${
|
||||
!source.search.url.includes('${searchTerm}')
|
||||
? '// eslint-disable-next-line @typescript-eslint/no-unused-vars'
|
||||
: ''
|
||||
}
|
||||
const searchNovels = async (searchTerm: string) => {
|
||||
${
|
||||
source.search
|
||||
? `
|
||||
const url = \`${source.search.url}\`;
|
||||
|
||||
const result = await fetch(url);
|
||||
const body = await result.text();
|
||||
|
||||
const loadedCheerio = cheerio.load(body);
|
||||
|
||||
const novels: SourceNovelItem[] = [];
|
||||
|
||||
loadedCheerio('${source.search.selectors.novelList}').each(function () {
|
||||
let novelUrl = loadedCheerio(this).find('${source.search.selectors.novelUrl}').attr('href');
|
||||
|
||||
if (novelUrl && !isUrlAbsolute(novelUrl)) {
|
||||
novelUrl = baseUrl + novelUrl;
|
||||
}
|
||||
|
||||
if (novelUrl) {
|
||||
const novelName = loadedCheerio(this).find('${source.search.selectors.novelName}').text();
|
||||
let novelCover = loadedCheerio(this).find('${source.search.selectors.novelCover}').attr('src');
|
||||
|
||||
if (novelCover && !isUrlAbsolute(novelCover)) {
|
||||
novelCover = baseUrl + novelCover;
|
||||
}
|
||||
|
||||
novels.push({
|
||||
sourceId,
|
||||
novelUrl,
|
||||
novelName,
|
||||
novelCover,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return novels;`
|
||||
: `
|
||||
showToast('${source.sourceName}: Search is not available in this source')
|
||||
|
||||
return [];
|
||||
`
|
||||
}
|
||||
};
|
||||
|
||||
const ${source.sourceName}Scraper = {
|
||||
popularNovels,
|
||||
parseNovelAndChapters,
|
||||
parseChapter,
|
||||
searchNovels,
|
||||
};
|
||||
|
||||
export default ${source.sourceName}Scraper;
|
||||
|
||||
`;
|
||||
|
||||
const formatContent = prettier.format(content, {
|
||||
parser: 'typescript',
|
||||
...prettierConfig,
|
||||
});
|
||||
|
||||
fs.writeFile(
|
||||
path.resolve(
|
||||
process.cwd(),
|
||||
`src/sources/${getLanguageCode(source.lang)}/${source.sourceName}.ts`,
|
||||
),
|
||||
formatContent,
|
||||
error => {
|
||||
if (error) {
|
||||
console.log(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (!isDuplicate) {
|
||||
let allSourcesContent = AllSources;
|
||||
|
||||
allSourcesContent.push({
|
||||
sourceId: source.sourceId,
|
||||
sourceName: source.sourceName,
|
||||
icon: `https://github.com/LNReader/lnreader-sources/blob/main/src/${getLanguageCode(
|
||||
source.lang,
|
||||
)}/${source.sourceName.toLowerCase()}/icon.png?raw=true`,
|
||||
url: source.baseUrl,
|
||||
lang: source.lang || 'English',
|
||||
});
|
||||
|
||||
allSourcesContent = prettier.format(JSON.stringify(allSourcesContent), {
|
||||
parser: 'json',
|
||||
...prettierConfig,
|
||||
});
|
||||
|
||||
fs.writeFile(
|
||||
path.resolve(process.cwd(), 'src/sources/sources.json'),
|
||||
allSourcesContent,
|
||||
error => {
|
||||
if (error) {
|
||||
console.log(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
} else {
|
||||
console.log('Source with same id already exists');
|
||||
}
|
||||
} else {
|
||||
console.log('Template path not provided');
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export const PATH_SEPARATOR = '&&';
|
||||
@@ -0,0 +1,111 @@
|
||||
import { create, download, getJson, list } from './request';
|
||||
import { DriveCreateRequestData, DriveFile } from './types';
|
||||
|
||||
const LNREADER_DRIVE_MARK = '(Do not change this!) LNReader-Drive';
|
||||
|
||||
export const exists = async (
|
||||
fileName: string,
|
||||
isFolder?: boolean,
|
||||
parentId?: string,
|
||||
marked?: boolean,
|
||||
) => {
|
||||
let q = `name = '${fileName}' and trashed = false `;
|
||||
if (marked) {
|
||||
q += ` and fullText contains '${LNREADER_DRIVE_MARK}' `;
|
||||
}
|
||||
if (isFolder) {
|
||||
q += " and mimeType = 'application/vnd.google-apps.folder' ";
|
||||
}
|
||||
if (parentId) {
|
||||
q += ` and '${parentId}' in parents `;
|
||||
}
|
||||
const res = await list({ q });
|
||||
return res.files.find(file => file.name === fileName);
|
||||
};
|
||||
|
||||
export const makeDir = async (fileName: string, parentId?: string) => {
|
||||
const existedDir = await exists(fileName, true, parentId);
|
||||
if (existedDir) {
|
||||
return existedDir;
|
||||
}
|
||||
const data: DriveCreateRequestData = {
|
||||
metadata: {
|
||||
name: fileName,
|
||||
mimeType: 'application/vnd.google-apps.folder',
|
||||
description: LNREADER_DRIVE_MARK,
|
||||
},
|
||||
};
|
||||
if (parentId) {
|
||||
data.metadata.parents = [parentId];
|
||||
}
|
||||
return create(data);
|
||||
};
|
||||
|
||||
export const createFile = async (
|
||||
fileName: string,
|
||||
mimeType: string,
|
||||
content: string,
|
||||
parentId?: string,
|
||||
) => {
|
||||
const existedFile = await exists(fileName, false, parentId);
|
||||
if (existedFile) {
|
||||
return existedFile;
|
||||
}
|
||||
const data: DriveCreateRequestData = {
|
||||
metadata: {
|
||||
name: fileName,
|
||||
mimeType: mimeType,
|
||||
description: LNREADER_DRIVE_MARK,
|
||||
},
|
||||
content: content,
|
||||
};
|
||||
if (parentId) {
|
||||
data.metadata.parents = [parentId];
|
||||
}
|
||||
return create(data);
|
||||
};
|
||||
|
||||
export const getBackups = async (parentId: string, marked?: boolean) => {
|
||||
let q = `
|
||||
name contains '.backup' and trashed = false
|
||||
and mimeType = 'application/vnd.google-apps.folder' and '${parentId}' in parents
|
||||
`;
|
||||
if (marked) {
|
||||
q += ` and fullText contains '${LNREADER_DRIVE_MARK}' `;
|
||||
}
|
||||
return list({
|
||||
q,
|
||||
}).then(res => res.files);
|
||||
};
|
||||
|
||||
export const readDir = async (parentId: string, marked?: boolean) => {
|
||||
let fileList: DriveFile[] = [];
|
||||
let pageToken = '';
|
||||
let q = `
|
||||
trashed = false and mimeType != 'application/vnd.google-apps.folder'
|
||||
and '${parentId}' in parents
|
||||
`;
|
||||
if (marked) {
|
||||
q += ` and fullText contains '${LNREADER_DRIVE_MARK}' `;
|
||||
}
|
||||
let hasNextPage = true;
|
||||
while (hasNextPage) {
|
||||
const query = pageToken ? q + ` and pageToken = '${pageToken}'` : q;
|
||||
const { nextPageToken, files } = await list({ q: query });
|
||||
if (!nextPageToken) {
|
||||
hasNextPage = false;
|
||||
} else {
|
||||
pageToken = nextPageToken;
|
||||
}
|
||||
fileList = fileList.concat(files);
|
||||
}
|
||||
return fileList;
|
||||
};
|
||||
|
||||
export const readFile = async (file: DriveFile, type: 'json' | 'media') => {
|
||||
if (type === 'json') {
|
||||
return getJson(file.id);
|
||||
} else {
|
||||
return download(file);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,117 @@
|
||||
import { GoogleSignin } from '@react-native-google-signin/google-signin';
|
||||
import { downloadFile, mkdir, exists } from 'react-native-fs';
|
||||
import {
|
||||
DriveCreateRequestData,
|
||||
DriveFile,
|
||||
DriveReponse,
|
||||
DriveRequestParams,
|
||||
} from './types';
|
||||
import { AppDownloadFolder } from '@utils/constants/download';
|
||||
import { PATH_SEPARATOR } from '@api/constants';
|
||||
|
||||
const BASE_URL = 'https://www.googleapis.com/drive/v3/files';
|
||||
const MEDIA_UPLOAD_URL = 'https://www.googleapis.com/upload/drive/v3/files';
|
||||
|
||||
const buildParams = (params: DriveRequestParams) => {
|
||||
return Object.entries(params)
|
||||
.map(pair => pair.map(encodeURIComponent).join('='))
|
||||
.join('&');
|
||||
};
|
||||
|
||||
export const list = async (
|
||||
params: DriveRequestParams,
|
||||
): Promise<DriveReponse> => {
|
||||
const { accessToken } = await GoogleSignin.getTokens();
|
||||
|
||||
if (!params.fields) {
|
||||
params.fields =
|
||||
'nextPageToken, files(id, name, description, createdTime, parents)';
|
||||
}
|
||||
|
||||
const url = BASE_URL + '?' + buildParams(params);
|
||||
|
||||
return fetch(url, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
}).then(res => res.json());
|
||||
};
|
||||
|
||||
export const create = async (
|
||||
data: DriveCreateRequestData,
|
||||
): Promise<DriveFile> => {
|
||||
const { accessToken } = await GoogleSignin.getTokens();
|
||||
|
||||
const params: DriveRequestParams = {
|
||||
fields: 'id, name, description, createdTime, parents',
|
||||
uploadType: 'multipart',
|
||||
};
|
||||
const url =
|
||||
(data.content ? MEDIA_UPLOAD_URL : BASE_URL) + '?' + buildParams(params);
|
||||
let body: any;
|
||||
data.metadata.name = data.metadata.name.replace(/\//g, PATH_SEPARATOR);
|
||||
if (data.content) {
|
||||
body = new FormData();
|
||||
body.append('metadata', {
|
||||
string: JSON.stringify(data.metadata),
|
||||
type: 'application/json',
|
||||
});
|
||||
if (data.metadata.mimeType === 'application/json') {
|
||||
body.append('media', {
|
||||
string: data.content,
|
||||
type: data.metadata.mimeType,
|
||||
});
|
||||
} else {
|
||||
body.append('media', {
|
||||
name: data.metadata.name,
|
||||
uri: data.content,
|
||||
type: data.metadata.mimeType,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
body = JSON.stringify(data.metadata);
|
||||
}
|
||||
|
||||
return fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body,
|
||||
}).then(res => res.json());
|
||||
};
|
||||
|
||||
export const getJson = async (id: string) => {
|
||||
const { accessToken } = await GoogleSignin.getTokens();
|
||||
const url = BASE_URL + '/' + id + '?alt=media';
|
||||
return fetch(url, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
}).then(res => res.json());
|
||||
};
|
||||
|
||||
export const download = async (file: DriveFile) => {
|
||||
const { accessToken } = await GoogleSignin.getTokens();
|
||||
const url = BASE_URL + '/' + file.id + '?alt=media';
|
||||
const regex = new RegExp(`${PATH_SEPARATOR}`, 'g');
|
||||
const filePath = AppDownloadFolder + '/' + file.name.replace(regex, '/');
|
||||
const dirPath = filePath.split('/').slice(0, -1).join('/');
|
||||
return exists(filePath).then(existed => {
|
||||
if (!existed) {
|
||||
return mkdir(dirPath).then(() => {
|
||||
return downloadFile({
|
||||
fromUrl: url,
|
||||
toFile: filePath,
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
export interface DriveFile {
|
||||
kind: string;
|
||||
mimeType?: string;
|
||||
parents: string[];
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
createdTime?: string;
|
||||
}
|
||||
|
||||
export interface DriveReponse {
|
||||
nextPageToken?: string;
|
||||
kind: string;
|
||||
incompleteSearch: boolean;
|
||||
files: DriveFile[];
|
||||
}
|
||||
|
||||
export interface DriveRequestParams {
|
||||
q?: string;
|
||||
orderBy?: string;
|
||||
pageSize?: number;
|
||||
fields?: string;
|
||||
pageToken?: string;
|
||||
uploadType?: string; // only for upload
|
||||
}
|
||||
|
||||
export interface DriveCreateRequestData {
|
||||
metadata: {
|
||||
name: string;
|
||||
mimeType: string;
|
||||
description?: string;
|
||||
parents?: string[];
|
||||
};
|
||||
content?: string; // uri if upload file
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { PATH_SEPARATOR } from '@api/constants';
|
||||
import { BackupPackage } from '@services/backup/types';
|
||||
import { AppDownloadFolder } from '@utils/constants/download';
|
||||
import { fetchTimeout } from '@utils/fetch/fetch';
|
||||
import { downloadFile, mkdir } from 'react-native-fs';
|
||||
|
||||
const commonHeaders = {
|
||||
'Connection': 'keep-alive',
|
||||
'Accept':
|
||||
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
|
||||
'Accept-Encoding': 'gzip, deflate, br',
|
||||
};
|
||||
|
||||
export const upload = (host: string, data: BackupPackage) => {
|
||||
const url = host + '/' + 'upload';
|
||||
const body = new FormData();
|
||||
data.name = data.name.replace(/\//g, PATH_SEPARATOR);
|
||||
body.append('metadata', JSON.stringify(data));
|
||||
if (data.mimeType === 'application/json') {
|
||||
body.append('media', {
|
||||
string: data.content,
|
||||
type: data.mimeType,
|
||||
});
|
||||
} else {
|
||||
body.append('media', {
|
||||
name: data.name,
|
||||
uri: data.content,
|
||||
type: data.mimeType,
|
||||
});
|
||||
}
|
||||
return fetchTimeout(url, {
|
||||
method: 'POST',
|
||||
headers: commonHeaders,
|
||||
body,
|
||||
});
|
||||
};
|
||||
|
||||
export const list = (host: string, folderTree: string[]): Promise<string[]> => {
|
||||
const url = host + '/' + 'list';
|
||||
const body = new FormData();
|
||||
body.append('metadata', JSON.stringify({ folderTree }));
|
||||
|
||||
return fetchTimeout(url, {
|
||||
method: 'POST',
|
||||
headers: commonHeaders,
|
||||
body,
|
||||
}).then(res => res.json());
|
||||
};
|
||||
|
||||
export const getJson = (host: string, folderTree: string[], name: string) => {
|
||||
const url = host + '/' + 'download' + '/' + folderTree.join('/') + '/' + name;
|
||||
return fetchTimeout(url, {
|
||||
headers: commonHeaders,
|
||||
}).then(res => res.json());
|
||||
};
|
||||
|
||||
export const download = async (
|
||||
host: string,
|
||||
folderTree: string[],
|
||||
name: string,
|
||||
) => {
|
||||
const url = host + '/' + 'download' + '/' + folderTree.join('/') + '/' + name;
|
||||
const regex = new RegExp(`${PATH_SEPARATOR}`, 'g');
|
||||
const filePath = AppDownloadFolder + '/' + name.replace(regex, '/');
|
||||
const dirPath = filePath.split('/').slice(0, -1).join('/');
|
||||
await mkdir(dirPath).then(() => {
|
||||
return downloadFile({
|
||||
fromUrl: url,
|
||||
toFile: filePath,
|
||||
headers: commonHeaders,
|
||||
}).promise;
|
||||
});
|
||||
};
|
||||
|
||||
export const exists = (
|
||||
host: string,
|
||||
folderTree: string[],
|
||||
name: string,
|
||||
): Promise<boolean> => {
|
||||
const url = host + '/' + 'exists';
|
||||
const body = new FormData();
|
||||
body.append('metadata', JSON.stringify({ folderTree, name }));
|
||||
return fetchTimeout(url, {
|
||||
method: 'POST',
|
||||
headers: commonHeaders,
|
||||
body,
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => data.exists);
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useTheme } from '@hooks/useTheme';
|
||||
import { useTheme } from '@hooks/persisted';
|
||||
import React from 'react';
|
||||
import {
|
||||
Dimensions,
|
||||
|
||||
@@ -3,7 +3,7 @@ import { StyleSheet, View, Text, StatusBar } from 'react-native';
|
||||
import ErrorBoundary from 'react-native-error-boundary';
|
||||
|
||||
import { Button, List } from '@components';
|
||||
import { useTheme } from '@hooks';
|
||||
import { useTheme } from '@hooks/persisted';
|
||||
|
||||
interface ErrorFallbackProps {
|
||||
error: Error;
|
||||
|
||||
@@ -6,9 +6,10 @@ import { ThemeColors } from '../../theme/types';
|
||||
|
||||
interface AppbarProps {
|
||||
title: string;
|
||||
handleGoBack: () => void;
|
||||
handleGoBack?: () => void;
|
||||
theme: ThemeColors;
|
||||
mode?: 'small' | 'medium' | 'large' | 'center-aligned';
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
const Appbar: React.FC<AppbarProps> = ({
|
||||
|
||||
@@ -6,8 +6,6 @@ import {
|
||||
BottomSheetModalProps,
|
||||
} from '@gorhom/bottom-sheet';
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
import { useTheme } from '@hooks/useTheme';
|
||||
import { overlay } from 'react-native-paper';
|
||||
|
||||
interface BottomSheetProps extends Omit<BottomSheetModalProps, 'ref'> {
|
||||
bottomSheetRef: Ref<BottomSheetModal> | null;
|
||||
@@ -15,8 +13,6 @@ interface BottomSheetProps extends Omit<BottomSheetModalProps, 'ref'> {
|
||||
|
||||
const BottomSheet: React.FC<BottomSheetProps> = props => {
|
||||
const { bottom } = useSafeAreaInsets();
|
||||
const theme = useTheme();
|
||||
|
||||
const renderBackdrop = useCallback(
|
||||
(backdropProps: BottomSheetBackdropProps) => (
|
||||
<BottomSheetBackdrop
|
||||
@@ -27,14 +23,12 @@ const BottomSheet: React.FC<BottomSheetProps> = props => {
|
||||
),
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<BottomSheetModal
|
||||
ref={props.bottomSheetRef}
|
||||
backdropComponent={renderBackdrop}
|
||||
handleComponent={null}
|
||||
containerStyle={{ paddingBottom: bottom }}
|
||||
backgroundStyle={{ backgroundColor: overlay(2, theme.surface) }}
|
||||
{...props}
|
||||
>
|
||||
{props.children}
|
||||
|
||||
@@ -4,9 +4,9 @@ import {
|
||||
ButtonProps as PaperButtonProps,
|
||||
} from 'react-native-paper';
|
||||
|
||||
import { useTheme } from '@hooks';
|
||||
import { useTheme } from '@hooks/persisted';
|
||||
|
||||
interface ButtonProps extends Omit<PaperButtonProps, 'children' | 'theme'> {
|
||||
interface ButtonProps extends Partial<PaperButtonProps> {
|
||||
title?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import React from 'react';
|
||||
import { Pressable, StyleSheet, Text, View } from 'react-native';
|
||||
|
||||
import { ThemeType } from '../../theme/types';
|
||||
import { ThemeColors } from '../../theme/types';
|
||||
|
||||
interface ColorPreferenceItemProps {
|
||||
label: string;
|
||||
description?: string;
|
||||
onPress: () => void;
|
||||
theme: ThemeType;
|
||||
theme: ThemeColors;
|
||||
}
|
||||
|
||||
const ColorPreferenceItem: React.FC<ColorPreferenceItemProps> = ({
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
import { ThemeColors } from '@theme/types';
|
||||
import React from 'react';
|
||||
import { View, StyleSheet } from 'react-native';
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
|
||||
const ScreenContainer = ({ children, theme }) => {
|
||||
const ScreenContainer = ({
|
||||
children,
|
||||
}: {
|
||||
children?: React.ReactNode;
|
||||
theme: ThemeColors;
|
||||
}) => {
|
||||
const { bottom } = useSafeAreaInsets();
|
||||
|
||||
return (
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
backgroundColor: theme.colorPrimaryDark,
|
||||
paddingBottom: bottom,
|
||||
}}
|
||||
>
|
||||
@@ -18,9 +23,13 @@ const ScreenContainer = ({ children, theme }) => {
|
||||
);
|
||||
};
|
||||
|
||||
const Row = ({ children, style = {} }) => (
|
||||
<View style={[styles.row, style]}>{children}</View>
|
||||
);
|
||||
const Row = ({
|
||||
children,
|
||||
style = {},
|
||||
}: {
|
||||
children?: React.ReactNode;
|
||||
style?: any;
|
||||
}) => <View style={[styles.row, style]}>{children}</View>;
|
||||
|
||||
export { ScreenContainer, Row };
|
||||
|
||||
@@ -5,7 +5,7 @@ import { getString } from '@strings/translations';
|
||||
|
||||
import { Dialog, Portal } from 'react-native-paper';
|
||||
import { ThemeColors } from '../../theme/types';
|
||||
import { Button } from '@components/index';
|
||||
import Button from '../Button/Button';
|
||||
|
||||
interface ConfirmationDialogProps {
|
||||
title: string;
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
import { StyleSheet, Text, TextStyle, View, TextInput } from 'react-native';
|
||||
import React, { useEffect } from 'react';
|
||||
|
||||
import { useTheme } from '@hooks/useTheme';
|
||||
import { IconButtonV2 } from '@components/index';
|
||||
interface CounterProps {
|
||||
labelStyle?: TextStyle | TextStyle[];
|
||||
label: string;
|
||||
value: number;
|
||||
displayValue?: number | string;
|
||||
minimumValue: number;
|
||||
maximumValue: number;
|
||||
step?: number;
|
||||
onChange: (value: number) => void;
|
||||
}
|
||||
|
||||
const Counter: React.FC<CounterProps> = ({
|
||||
labelStyle,
|
||||
label,
|
||||
value,
|
||||
displayValue,
|
||||
minimumValue,
|
||||
maximumValue,
|
||||
step = 1,
|
||||
onChange,
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
const minusDisabled = value <= minimumValue;
|
||||
const plusDisabled = value >= maximumValue;
|
||||
const [text, onChangeText] = React.useState(value.toString());
|
||||
|
||||
useEffect(() => {
|
||||
onChangeText(value.toString());
|
||||
}, [value]);
|
||||
|
||||
const endEditing = () => {
|
||||
let res = isNaN(Number(text)) ? 0 : Number(text);
|
||||
if (minimumValue && res < minimumValue) {
|
||||
res = minimumValue;
|
||||
} else if (maximumValue && res > maximumValue) {
|
||||
res = maximumValue;
|
||||
}
|
||||
onChange(res);
|
||||
onChangeText(res.toString());
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text
|
||||
style={[{ color: theme.onSurfaceVariant }, labelStyle, styles.text]}
|
||||
>
|
||||
{label}
|
||||
</Text>
|
||||
<View style={styles.buttonContainer}>
|
||||
<View style={styles.buttons}>
|
||||
<IconButtonV2
|
||||
name="minus"
|
||||
color={theme.primary}
|
||||
size={26}
|
||||
disabled={minusDisabled}
|
||||
onPress={() => onChange(value - step)}
|
||||
theme={theme}
|
||||
/>
|
||||
</View>
|
||||
<TextInput
|
||||
editable={displayValue ? false : true}
|
||||
style={[styles.value, { color: theme.onSurface }]}
|
||||
onEndEditing={endEditing}
|
||||
value={displayValue ? displayValue.toString() : text}
|
||||
onChangeText={onChangeText}
|
||||
keyboardType="numeric"
|
||||
/>
|
||||
<View style={styles.buttons}>
|
||||
<IconButtonV2
|
||||
name="plus"
|
||||
color={theme.primary}
|
||||
size={26}
|
||||
disabled={plusDisabled}
|
||||
onPress={() => onChange(value + step)}
|
||||
theme={theme}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
export default Counter;
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
paddingHorizontal: 16,
|
||||
marginVertical: 6,
|
||||
},
|
||||
text: {
|
||||
flex: 6,
|
||||
},
|
||||
value: {
|
||||
textAlign: 'center',
|
||||
flex: 2,
|
||||
},
|
||||
buttons: {
|
||||
flex: 1,
|
||||
},
|
||||
buttonContainer: {
|
||||
position: 'relative',
|
||||
flex: 5,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
});
|
||||
@@ -1,8 +1,22 @@
|
||||
import { useTheme } from '@hooks/useTheme';
|
||||
import { useTheme } from '@hooks/persisted';
|
||||
import React from 'react';
|
||||
import { StyleSheet, Text, View } from 'react-native';
|
||||
|
||||
const EmptyView = ({ icon, description, style, children, iconStyle }) => {
|
||||
interface EmptyViewProps {
|
||||
icon: string;
|
||||
description: string;
|
||||
style?: any;
|
||||
children?: React.ReactNode;
|
||||
iconStyle?: any;
|
||||
}
|
||||
|
||||
const EmptyView = ({
|
||||
icon,
|
||||
description,
|
||||
style,
|
||||
children,
|
||||
iconStyle,
|
||||
}: EmptyViewProps) => {
|
||||
const theme = useTheme();
|
||||
|
||||
return (
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { StyleSheet, Text, View } from 'react-native';
|
||||
|
||||
import { useTheme } from '@hooks/useTheme';
|
||||
import { useTheme } from '@hooks/persisted';
|
||||
|
||||
interface ErrorScreenProps {
|
||||
error: string;
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
import { ThemeColors } from '@theme/types';
|
||||
import React from 'react';
|
||||
import { Pressable, StyleSheet, Text, View } from 'react-native';
|
||||
import { IconButton } from 'react-native-paper';
|
||||
|
||||
// const icons = ['(・o・;)', 'Σ(ಠ_ಠ)', 'ಥ_ಥ', '(˘・_・˘)', '(; ̄Д ̄)', '(・Д・。'];
|
||||
|
||||
export const ErrorView = ({ errorName, actions, theme }) => (
|
||||
interface ErrorAction {
|
||||
name: string;
|
||||
icon: string;
|
||||
onPress: () => void;
|
||||
}
|
||||
|
||||
interface ErrorViewProps {
|
||||
errorName: string;
|
||||
actions: ErrorAction[];
|
||||
theme: ThemeColors;
|
||||
}
|
||||
|
||||
export const ErrorView = ({ errorName, actions, theme }: ErrorViewProps) => (
|
||||
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
|
||||
<Text style={[styles.emptyViewIcon, { color: theme.outline }]}>
|
||||
{/* {icons[Math.floor(Math.random() * 5)]} */}
|
||||
@@ -36,12 +49,7 @@ export const ErrorView = ({ errorName, actions, theme }) => (
|
||||
minWidth: 100,
|
||||
}}
|
||||
>
|
||||
<IconButton
|
||||
icon={action.icon}
|
||||
color={theme.outline}
|
||||
size={24}
|
||||
style={{ margin: 0 }}
|
||||
/>
|
||||
<IconButton icon={action.icon} size={24} style={{ margin: 0 }} />
|
||||
<Text
|
||||
style={{
|
||||
fontSize: 12,
|
||||
@@ -9,9 +9,10 @@ interface ListItemProps {
|
||||
title: string;
|
||||
description?: string | null;
|
||||
icon?: string;
|
||||
right?: string;
|
||||
onPress?: () => void;
|
||||
theme: ThemeColors;
|
||||
disabled?: boolean;
|
||||
right?: string;
|
||||
}
|
||||
|
||||
const Section = ({ children }: { children: ReactNode }) => (
|
||||
@@ -36,13 +37,16 @@ const Item: React.FC<ListItemProps> = ({
|
||||
icon,
|
||||
onPress,
|
||||
theme,
|
||||
disabled,
|
||||
right,
|
||||
}) => (
|
||||
<PaperList.Item
|
||||
title={title}
|
||||
titleStyle={{ color: theme.onSurface }}
|
||||
titleStyle={{ color: disabled ? theme.onSurfaceDisabled : theme.onSurface }}
|
||||
description={description}
|
||||
descriptionStyle={{ color: theme.onSurfaceVariant }}
|
||||
descriptionStyle={{
|
||||
color: disabled ? theme.onSurfaceDisabled : theme.onSurfaceVariant,
|
||||
}}
|
||||
left={
|
||||
icon
|
||||
? () => (
|
||||
@@ -65,6 +69,7 @@ const Item: React.FC<ListItemProps> = ({
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
rippleColor={theme.rippleColor}
|
||||
style={styles.listItemCtn}
|
||||
@@ -81,7 +86,7 @@ const InfoItem = ({
|
||||
theme,
|
||||
}: {
|
||||
title: string;
|
||||
icon: string;
|
||||
icon?: string;
|
||||
theme: ThemeColors;
|
||||
}) => (
|
||||
<View style={styles.infoCtn}>
|
||||
@@ -96,7 +101,14 @@ const Icon = ({ icon, theme }: { icon: string; theme: ThemeColors }) => (
|
||||
<PaperList.Icon color={theme.primary} icon={icon} style={{ margin: 0 }} />
|
||||
);
|
||||
|
||||
const ColorItem = ({ title, description, theme, onPress }) => (
|
||||
interface ColorItemProps {
|
||||
title: string;
|
||||
description: string;
|
||||
theme: ThemeColors;
|
||||
onPress: () => void;
|
||||
}
|
||||
|
||||
const ColorItem = ({ title, description, theme, onPress }: ColorItemProps) => (
|
||||
<Pressable
|
||||
style={{
|
||||
padding: 16,
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
import React from 'react';
|
||||
import { StyleSheet, View, Text, Pressable } from 'react-native';
|
||||
|
||||
import FastImage from 'react-native-fast-image';
|
||||
import { Image } from 'react-native';
|
||||
import { coverPlaceholderColor } from '../theme/colors';
|
||||
|
||||
import { getSourceStorage } from '@hooks/useSourceStorage';
|
||||
import { defaultUserAgentString } from '@utils/fetch/fetch';
|
||||
|
||||
import color from 'color';
|
||||
import { ThemeColors } from '@theme/types';
|
||||
import { NovelInfo } from '@database/types';
|
||||
|
||||
interface ListViewProps {
|
||||
item: NovelInfo;
|
||||
downloadBadge?: React.ReactNode;
|
||||
unreadBadge?: React.ReactNode;
|
||||
inLibraryBadge?: React.ReactNode;
|
||||
theme: ThemeColors;
|
||||
onPress: () => void;
|
||||
isSelected?: boolean;
|
||||
onLongPress?: () => void;
|
||||
}
|
||||
|
||||
const ListView = ({
|
||||
item,
|
||||
@@ -18,8 +28,7 @@ const ListView = ({
|
||||
onPress,
|
||||
isSelected,
|
||||
onLongPress,
|
||||
}) => {
|
||||
const { cookies = '' } = getSourceStorage(item.sourceId);
|
||||
}: ListViewProps) => {
|
||||
return (
|
||||
<Pressable
|
||||
android_ripple={{ color: theme.rippleColor }}
|
||||
@@ -32,18 +41,17 @@ const ListView = ({
|
||||
onPress={onPress}
|
||||
onLongPress={onLongPress}
|
||||
>
|
||||
<FastImage
|
||||
<Image
|
||||
source={{
|
||||
uri: item.novelCover,
|
||||
headers: { Cookie: cookies, 'User-Agent': defaultUserAgentString },
|
||||
uri: item.cover,
|
||||
}}
|
||||
style={[styles.extensionIcon, inLibraryBadge && { opacity: 0.5 }]}
|
||||
style={[styles.extensionIcon, inLibraryBadge ? { opacity: 0.5 } : {}]}
|
||||
/>
|
||||
<Text
|
||||
style={[{ color: theme.onSurface }, styles.novelName]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{item.novelName}
|
||||
{item.name}
|
||||
</Text>
|
||||
<View style={styles.badgeContainer}>
|
||||
{downloadBadge}
|
||||
@@ -6,7 +6,7 @@ import { ScrollView } from 'react-native-gesture-handler';
|
||||
import Button from './Button/Button';
|
||||
import { getString } from '@strings/translations';
|
||||
|
||||
import { useTheme } from '@hooks/useTheme';
|
||||
import { useTheme } from '@hooks/persisted';
|
||||
|
||||
interface NewUpdateDialogProps {
|
||||
newVersion: {
|
||||
@@ -37,7 +37,9 @@ const NewUpdateDialog: React.FC<NewUpdateDialogProps> = ({ newVersion }) => {
|
||||
{`${getString('common.newUpdateAvailable')} ${newVersion.tag_name}`}
|
||||
</Text>
|
||||
<ScrollView style={{ height: modalHeight }}>
|
||||
{newVersion.body}
|
||||
<Text style={[styles.body, { color: theme.onSurfaceVariant }]}>
|
||||
{newVersion.body.split('\n').join('\n\n')}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
<View style={styles.buttonCtn}>
|
||||
<Button
|
||||
@@ -67,7 +69,10 @@ const styles = StyleSheet.create({
|
||||
fontSize: 20,
|
||||
marginBottom: 16,
|
||||
},
|
||||
body: {},
|
||||
body: {
|
||||
fontSize: 15,
|
||||
fontWeight: '500',
|
||||
},
|
||||
buttonCtn: {
|
||||
flexDirection: 'row',
|
||||
marginTop: 16,
|
||||
|
||||
@@ -8,40 +8,49 @@ import {
|
||||
} from 'react-native';
|
||||
|
||||
import { LinearGradient } from 'expo-linear-gradient';
|
||||
import FastImage from 'react-native-fast-image';
|
||||
import { Image } from 'react-native';
|
||||
import ListView from './ListView';
|
||||
|
||||
import { useDeviceOrientation } from '@hooks/useDeviceOrientation';
|
||||
import { useDeviceOrientation } from '@hooks';
|
||||
import { coverPlaceholderColor } from '../theme/colors';
|
||||
import { useLibrarySettings } from '@hooks/useSettings';
|
||||
import { DisplayModes } from '@screens/library/constants/constants';
|
||||
import { LibraryNovelInfo } from '@database/types';
|
||||
import { SourceNovelItem } from 'src/sources/types';
|
||||
import { LibraryNovelInfo, NovelInfo } from '@database/types';
|
||||
import { NovelItem } from '@plugins/types';
|
||||
import { ThemeColors } from '@theme/types';
|
||||
import SourceScreenSkeletonLoading from '@screens/browse/loadingAnimation/SourceScreenSkeletonLoading';
|
||||
import { useLibrarySettings } from '@hooks/persisted';
|
||||
import { getUserAgent } from '@hooks/persisted/useUserAgent';
|
||||
|
||||
import { getSourceStorage } from '@hooks/useSourceStorage';
|
||||
import { defaultUserAgentString } from '@utils/fetch/fetch';
|
||||
|
||||
interface NovelCoverProps {
|
||||
item: LibraryNovelInfo;
|
||||
onPress: () => void;
|
||||
libraryStatus?: boolean;
|
||||
interface UnreadBadgeProps {
|
||||
chaptersDownloaded: number;
|
||||
chaptersUnread: number;
|
||||
showDownloadBadges: boolean;
|
||||
theme: ThemeColors;
|
||||
isSelected?: boolean;
|
||||
onLongPress: (novelId: number) => void;
|
||||
selectedNovels?: Array<SourceNovelItem>;
|
||||
}
|
||||
|
||||
const NovelCover: React.FC<NovelCoverProps> = ({
|
||||
interface DownloadBadgeProps {
|
||||
chaptersDownloaded: number;
|
||||
chaptersUnread: number;
|
||||
showUnreadBadges: boolean;
|
||||
theme: ThemeColors;
|
||||
}
|
||||
|
||||
function NovelCover<TNovel extends NovelItem | NovelInfo | LibraryNovelInfo>({
|
||||
item,
|
||||
onPress,
|
||||
libraryStatus,
|
||||
theme,
|
||||
isSelected,
|
||||
onLongPress,
|
||||
selectedNovels,
|
||||
}) => {
|
||||
selectedNovelIds,
|
||||
}: {
|
||||
item: TNovel;
|
||||
onPress: () => void;
|
||||
libraryStatus: boolean;
|
||||
theme: ThemeColors;
|
||||
isSelected: boolean;
|
||||
onLongPress: (item: TNovel) => void;
|
||||
selectedNovelIds: number[];
|
||||
}) {
|
||||
const {
|
||||
displayMode = DisplayModes.Comfortable,
|
||||
showDownloadBadges = true,
|
||||
@@ -60,25 +69,21 @@ const NovelCover: React.FC<NovelCoverProps> = ({
|
||||
|
||||
const coverHeight = useMemo(
|
||||
() => (window.width / numColumns) * (4 / 3),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[numColumns],
|
||||
);
|
||||
|
||||
const selectNovel = () => onLongPress && onLongPress(item.novelId);
|
||||
const selectNovel = () => onLongPress(item);
|
||||
|
||||
const uri = item.novelCover;
|
||||
|
||||
const { cookies = '' } = getSourceStorage(item.sourceId);
|
||||
|
||||
return item.sourceId < 0 ? (
|
||||
<SourceScreenSkeletonLoading theme={theme} completeRow={item.sourceId} />
|
||||
) : displayMode !== DisplayModes.List ? (
|
||||
const uri = item.cover;
|
||||
return displayMode !== DisplayModes.List ? (
|
||||
<View
|
||||
style={[
|
||||
{
|
||||
flex: 1 / numColumns,
|
||||
borderRadius: 6,
|
||||
overflow: 'hidden',
|
||||
margin: 2,
|
||||
},
|
||||
styles.standardNovelCover,
|
||||
isSelected && {
|
||||
backgroundColor: theme.primary,
|
||||
opacity: 0.8,
|
||||
@@ -89,13 +94,15 @@ const NovelCover: React.FC<NovelCoverProps> = ({
|
||||
android_ripple={{ color: theme.rippleColor }}
|
||||
style={styles.opac}
|
||||
onPress={
|
||||
selectedNovels && selectedNovels.length > 0 ? selectNovel : onPress
|
||||
selectedNovelIds && selectedNovelIds.length > 0
|
||||
? selectNovel
|
||||
: onPress
|
||||
}
|
||||
onLongPress={selectNovel}
|
||||
>
|
||||
<View style={styles.badgeContainer}>
|
||||
{libraryStatus && <InLibraryBadge theme={theme} />}
|
||||
{showDownloadBadges && item.chaptersDownloaded && (
|
||||
{showDownloadBadges && item.chaptersDownloaded > 0 && (
|
||||
<DownloadBadge
|
||||
showUnreadBadges={showUnreadBadges}
|
||||
chaptersDownloaded={item.chaptersDownloaded}
|
||||
@@ -103,7 +110,7 @@ const NovelCover: React.FC<NovelCoverProps> = ({
|
||||
theme={theme}
|
||||
/>
|
||||
)}
|
||||
{showUnreadBadges && item.chaptersUnread && (
|
||||
{showUnreadBadges && item.chaptersUnread > 0 && (
|
||||
<UnreadBadge
|
||||
theme={theme}
|
||||
chaptersDownloaded={item.chaptersDownloaded}
|
||||
@@ -112,27 +119,24 @@ const NovelCover: React.FC<NovelCoverProps> = ({
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
<FastImage
|
||||
source={{
|
||||
uri,
|
||||
headers: { Cookie: cookies, 'User-Agent': defaultUserAgentString },
|
||||
}}
|
||||
<Image
|
||||
source={{ uri, headers: { 'User-Agent': getUserAgent() } }}
|
||||
style={[
|
||||
{
|
||||
height: coverHeight,
|
||||
borderRadius: 4,
|
||||
backgroundColor: coverPlaceholderColor,
|
||||
},
|
||||
styles.standardBorderRadius,
|
||||
libraryStatus && styles.opacityPoint5,
|
||||
libraryStatus && { opacity: 0.5 },
|
||||
]}
|
||||
/>
|
||||
<View style={styles.compactTitleContainer}>
|
||||
{displayMode === DisplayModes.Compact && (
|
||||
<CompactTitle novelName={item.novelName} />
|
||||
<CompactTitle novelName={item.name} />
|
||||
)}
|
||||
</View>
|
||||
{displayMode === DisplayModes.Comfortable && (
|
||||
<ComfortableTitle novelName={item.novelName} theme={theme} />
|
||||
<ComfortableTitle novelName={item.name} theme={theme} />
|
||||
)}
|
||||
</Pressable>
|
||||
</View>
|
||||
@@ -164,27 +168,30 @@ const NovelCover: React.FC<NovelCoverProps> = ({
|
||||
inLibraryBadge={libraryStatus && <InLibraryBadge theme={theme} />}
|
||||
theme={theme}
|
||||
onPress={
|
||||
selectedNovels && selectedNovels.length > 0 ? selectNovel : onPress
|
||||
selectedNovelIds && selectedNovelIds.length > 0 ? selectNovel : onPress
|
||||
}
|
||||
onLongPress={selectNovel}
|
||||
isSelected={isSelected}
|
||||
/>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export default memo(NovelCover);
|
||||
|
||||
const ComfortableTitle: React.FC<{ theme: ThemeColors; novelName: string }> = ({
|
||||
const ComfortableTitle = ({
|
||||
theme,
|
||||
novelName,
|
||||
}: {
|
||||
theme: ThemeColors;
|
||||
novelName: string;
|
||||
}) => (
|
||||
<Text
|
||||
numberOfLines={2}
|
||||
style={[
|
||||
styles.title,
|
||||
styles.padding4,
|
||||
{
|
||||
color: theme.onSurface,
|
||||
padding: 4,
|
||||
},
|
||||
]}
|
||||
>
|
||||
@@ -192,57 +199,61 @@ const ComfortableTitle: React.FC<{ theme: ThemeColors; novelName: string }> = ({
|
||||
</Text>
|
||||
);
|
||||
|
||||
const CompactTitle: React.FC<{ novelName: string }> = ({ novelName }) => (
|
||||
const CompactTitle = ({ novelName }: { novelName: string }) => (
|
||||
<View style={styles.titleContainer}>
|
||||
<LinearGradient
|
||||
colors={['transparent', 'rgba(0,0,0,0.7)']}
|
||||
style={styles.linearGradient}
|
||||
>
|
||||
<Text numberOfLines={2} style={[styles.title, styles.compactTitle]}>
|
||||
<Text
|
||||
numberOfLines={2}
|
||||
style={[
|
||||
styles.title,
|
||||
{
|
||||
color: 'rgba(255,255,255,1)',
|
||||
textShadowColor: 'rgba(0, 0, 0, 0.75)',
|
||||
textShadowOffset: { width: -1, height: 1 },
|
||||
textShadowRadius: 10,
|
||||
},
|
||||
]}
|
||||
>
|
||||
{novelName}
|
||||
</Text>
|
||||
</LinearGradient>
|
||||
</View>
|
||||
);
|
||||
|
||||
const InLibraryBadge: React.FC<{ theme: ThemeColors }> = ({ theme }) => (
|
||||
const InLibraryBadge = ({ theme }: { theme: ThemeColors }) => (
|
||||
<Text
|
||||
style={[
|
||||
styles.inLibraryBadge,
|
||||
{
|
||||
backgroundColor: theme.primary,
|
||||
color: theme.onPrimary,
|
||||
borderRadius: 4,
|
||||
},
|
||||
styles.standardBorderRadius,
|
||||
]}
|
||||
>
|
||||
In library
|
||||
</Text>
|
||||
);
|
||||
|
||||
interface BadgeProps {
|
||||
chaptersDownloaded: number;
|
||||
chaptersUnread: number;
|
||||
theme: ThemeColors;
|
||||
}
|
||||
interface UnreadBadgeProps extends BadgeProps {
|
||||
showDownloadBadges: boolean;
|
||||
}
|
||||
interface DownloadBadgeProps extends BadgeProps {
|
||||
showUnreadBadges: boolean;
|
||||
}
|
||||
|
||||
const UnreadBadge: React.FC<UnreadBadgeProps> = ({
|
||||
const UnreadBadge = ({
|
||||
chaptersDownloaded,
|
||||
chaptersUnread,
|
||||
showDownloadBadges,
|
||||
theme,
|
||||
}) => (
|
||||
}: UnreadBadgeProps) => (
|
||||
<Text
|
||||
style={[
|
||||
styles.unreadBadge,
|
||||
!chaptersDownloaded && styles.LeftBorderRadius,
|
||||
!showDownloadBadges && styles.standardBorderRadius,
|
||||
!chaptersDownloaded && {
|
||||
borderTopLeftRadius: 4,
|
||||
borderBottomLeftRadius: 4,
|
||||
},
|
||||
!showDownloadBadges && {
|
||||
borderRadius: 4,
|
||||
},
|
||||
{
|
||||
backgroundColor: theme.primary,
|
||||
color: theme.onPrimary,
|
||||
@@ -253,17 +264,22 @@ const UnreadBadge: React.FC<UnreadBadgeProps> = ({
|
||||
</Text>
|
||||
);
|
||||
|
||||
const DownloadBadge: React.FC<DownloadBadgeProps> = ({
|
||||
const DownloadBadge = ({
|
||||
chaptersDownloaded,
|
||||
showUnreadBadges,
|
||||
chaptersUnread,
|
||||
theme,
|
||||
}) => (
|
||||
}: DownloadBadgeProps) => (
|
||||
<Text
|
||||
style={[
|
||||
styles.downloadBadge,
|
||||
!chaptersUnread && styles.RightBorderRadius,
|
||||
!showUnreadBadges && styles.standardBorderRadius,
|
||||
!chaptersUnread && {
|
||||
borderTopRightRadius: 4,
|
||||
borderBottomRightRadius: 4,
|
||||
},
|
||||
!showUnreadBadges && {
|
||||
borderRadius: 4,
|
||||
},
|
||||
{
|
||||
backgroundColor: theme.tertiary,
|
||||
color: theme.onTertiary,
|
||||
@@ -275,19 +291,6 @@ const DownloadBadge: React.FC<DownloadBadgeProps> = ({
|
||||
);
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
LeftBorderRadius: {
|
||||
borderTopLeftRadius: 4,
|
||||
borderBottomLeftRadius: 4,
|
||||
},
|
||||
RightBorderRadius: {
|
||||
borderTopRightRadius: 4,
|
||||
borderBottomRightRadius: 4,
|
||||
},
|
||||
standardBorderRadius: {
|
||||
borderRadius: 4,
|
||||
},
|
||||
opacityPoint5: { opacity: 0.5 },
|
||||
padding4: { padding: 4 },
|
||||
titleContainer: {
|
||||
flex: 1,
|
||||
borderRadius: 4,
|
||||
@@ -351,15 +354,4 @@ const styles = StyleSheet.create({
|
||||
left: 10,
|
||||
flexDirection: 'row',
|
||||
},
|
||||
standardNovelCover: {
|
||||
borderRadius: 6,
|
||||
overflow: 'hidden',
|
||||
margin: 2,
|
||||
},
|
||||
compactTitle: {
|
||||
color: 'rgba(255,255,255,1)',
|
||||
textShadowColor: 'rgba(0, 0, 0, 0.75)',
|
||||
textShadowOffset: { width: -1, height: 1 },
|
||||
textShadowRadius: 10,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,27 +1,23 @@
|
||||
import { useLibrarySettings } from '@hooks/useSettings';
|
||||
import { useLibrarySettings } from '@hooks/persisted';
|
||||
import { DisplayModes } from '@screens/library/constants/constants';
|
||||
import React, { useCallback, useMemo } from 'react';
|
||||
import React, { useMemo } from 'react';
|
||||
import {
|
||||
StyleSheet,
|
||||
FlatList,
|
||||
FlatListProps,
|
||||
ListRenderItem,
|
||||
} from 'react-native';
|
||||
import { SourceNovelItem } from '../sources/types';
|
||||
import { NovelItem } from '@plugins/types';
|
||||
import { LibraryNovelInfo, NovelInfo } from '../database/types';
|
||||
import { useDeviceOrientation } from '@hooks/useDeviceOrientation';
|
||||
import { useDeviceOrientation } from '@hooks';
|
||||
|
||||
export type NovelListRenderItem = ListRenderItem<
|
||||
LibraryNovelInfo | NovelInfo | SourceNovelItem
|
||||
LibraryNovelInfo | NovelInfo | NovelItem
|
||||
>;
|
||||
|
||||
interface NovelListProps
|
||||
extends FlatListProps<LibraryNovelInfo | NovelInfo | SourceNovelItem> {
|
||||
isFetchingNextPage?: boolean;
|
||||
inSource?: boolean;
|
||||
}
|
||||
|
||||
const NovelList: React.FC<NovelListProps> = props => {
|
||||
const NovelList: React.FC<
|
||||
FlatListProps<LibraryNovelInfo | NovelInfo | NovelItem>
|
||||
> = props => {
|
||||
const { displayMode = DisplayModes.Comfortable, novelsPerRow = 3 } =
|
||||
useLibrarySettings();
|
||||
|
||||
@@ -41,21 +37,6 @@ const NovelList: React.FC<NovelListProps> = props => {
|
||||
}
|
||||
}, [isListView, orientation, novelsPerRow]);
|
||||
|
||||
const keyExtractor = useCallback(
|
||||
(item: SourceNovelItem) => item.sourceId + item.novelUrl,
|
||||
[],
|
||||
);
|
||||
var extendedNovelList: Array<SourceNovelItem | LibraryNovelInfo> =
|
||||
props?.data as Array<LibraryNovelInfo>;
|
||||
if (props.data?.length && props.inSource && props.isFetchingNextPage) {
|
||||
let remainder = numColumns - (props.data?.length % numColumns);
|
||||
let extension = [];
|
||||
if (remainder !== 0 && remainder !== numColumns) {
|
||||
extension.push({ sourceId: -remainder, novelName: '', novelUrl: '' });
|
||||
}
|
||||
extendedNovelList = [...props.data, ...extension];
|
||||
}
|
||||
|
||||
return (
|
||||
<FlatList
|
||||
contentContainerStyle={[
|
||||
@@ -64,9 +45,8 @@ const NovelList: React.FC<NovelListProps> = props => {
|
||||
]}
|
||||
numColumns={numColumns}
|
||||
key={numColumns}
|
||||
keyExtractor={keyExtractor}
|
||||
keyExtractor={item => item.url}
|
||||
{...props}
|
||||
data={extendedNovelList}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,14 +1,37 @@
|
||||
import { ThemeColors } from '@theme/types';
|
||||
import React from 'react';
|
||||
import { StyleSheet, View, Text } from 'react-native';
|
||||
import { RadioButton as MaterialRadioButton } from 'react-native-paper';
|
||||
|
||||
export const RadioButtonGroup = ({ children, value, onValueChange }) => (
|
||||
interface RadioButtonGroupProps {
|
||||
children?: React.ReactNode;
|
||||
value: string;
|
||||
onValueChange: () => void;
|
||||
}
|
||||
|
||||
interface RadioButtonProps {
|
||||
value: string;
|
||||
label: string;
|
||||
theme: ThemeColors;
|
||||
labelStyle: StyleSheet.AbsoluteFillStyle;
|
||||
}
|
||||
|
||||
export const RadioButtonGroup = ({
|
||||
children,
|
||||
value,
|
||||
onValueChange,
|
||||
}: RadioButtonGroupProps) => (
|
||||
<MaterialRadioButton.Group onValueChange={onValueChange} value={value}>
|
||||
{children}
|
||||
</MaterialRadioButton.Group>
|
||||
);
|
||||
|
||||
export const RadioButton = ({ value, label, theme, labelStyle }) => (
|
||||
export const RadioButton = ({
|
||||
value,
|
||||
label,
|
||||
theme,
|
||||
labelStyle,
|
||||
}: RadioButtonProps) => (
|
||||
<View style={styles.radioButtonContainer}>
|
||||
<MaterialRadioButton
|
||||
value={value}
|
||||
@@ -3,8 +3,19 @@ import { View, Text, /* StyleSheet, */ Pressable } from 'react-native';
|
||||
import { overlay } from 'react-native-paper';
|
||||
import color from 'color';
|
||||
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
|
||||
import { ThemeColors } from '@theme/types';
|
||||
|
||||
export const ThemePicker = ({ theme, currentTheme, onPress }) => (
|
||||
interface ThemePickerProps {
|
||||
theme: ThemeColors;
|
||||
currentTheme: ThemeColors;
|
||||
onPress: () => void;
|
||||
}
|
||||
|
||||
export const ThemePicker = ({
|
||||
theme,
|
||||
currentTheme,
|
||||
onPress,
|
||||
}: ThemePickerProps) => (
|
||||
<View
|
||||
style={{
|
||||
justifyContent: 'center',
|
||||
@@ -13,3 +13,4 @@ export { default as ColorPreferenceItem } from './ColorPreferenceItem/ColorPrefe
|
||||
export { default as LoadingMoreIndicator } from './LoadingMoreIndicator/LoadingMoreIndicator';
|
||||
export { Checkbox } from './Checkbox/Checkbox';
|
||||
export { RadioButton } from './RadioButton/RadioButton';
|
||||
export { default as ConfirmationDialog } from './ConfirmationDialog/ConfirmationDialog';
|
||||
|
||||
@@ -1,100 +1,50 @@
|
||||
import * as SQLite from 'expo-sqlite';
|
||||
import {
|
||||
createNovelTableQuery,
|
||||
createUrlIndexQuery,
|
||||
createLibraryIndexQuery,
|
||||
addCategoryColumnQuery,
|
||||
} from './tables/NovelTable';
|
||||
createCategoriesTableQuery,
|
||||
createCategoryDefaultQuery,
|
||||
createCategoryLocalQuery,
|
||||
createCategoryTriggerQuery,
|
||||
} from './tables/CategoryTable';
|
||||
import { createNovelTableQuery } from './tables/NovelTable';
|
||||
import { createNovelCategoryTableQuery } from './tables/NovelCategoryTable';
|
||||
import {
|
||||
createChapterTableQuery,
|
||||
createNovelIdIndexQuery,
|
||||
createUnreadChaptersIndexQuery,
|
||||
createChapterNovelIdIndexQuery,
|
||||
} from './tables/ChapterTable';
|
||||
import {
|
||||
createHistoryTableQuery,
|
||||
createChapterIdIndexQuery,
|
||||
} from './tables/HistoryTable';
|
||||
import {
|
||||
createDownloadIdIndex,
|
||||
createDownloadTableQuery,
|
||||
} from './tables/DownloadTable';
|
||||
import { createUpdatesTableQuery } from './tables/UpdateTable';
|
||||
import {
|
||||
addCategorySortColumnQuery,
|
||||
createCategoriesTableQuery,
|
||||
createCategorydIndexQuery,
|
||||
createDefaultCategoryQuery,
|
||||
} from './tables/CategoryTable';
|
||||
import {
|
||||
dbTxnErrorCallback,
|
||||
txnErrorCallbackWithoutToast,
|
||||
} from './utils/helpers';
|
||||
import { dbTxnErrorCallback } from './utils/helpers';
|
||||
import { noop } from 'lodash-es';
|
||||
|
||||
const dbName = 'lnreader.db';
|
||||
|
||||
const db = SQLite.openDatabase(dbName);
|
||||
|
||||
const createTables = () => {
|
||||
export const createTables = () => {
|
||||
db.exec([{ sql: 'PRAGMA foreign_keys = ON', args: [] }], false, () => {});
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(createNovelTableQuery);
|
||||
tx.executeSql(createCategoriesTableQuery, [], () => {
|
||||
tx.executeSql(
|
||||
addCategorySortColumnQuery,
|
||||
undefined,
|
||||
noop,
|
||||
txnErrorCallbackWithoutToast,
|
||||
);
|
||||
tx.executeSql(
|
||||
createDefaultCategoryQuery,
|
||||
undefined,
|
||||
noop,
|
||||
txnErrorCallbackWithoutToast,
|
||||
);
|
||||
tx.executeSql(createCategoryDefaultQuery);
|
||||
tx.executeSql(createCategoryLocalQuery);
|
||||
tx.executeSql(createCategoryTriggerQuery);
|
||||
});
|
||||
tx.executeSql(createNovelTableQuery, [], () => {
|
||||
tx.executeSql(
|
||||
addCategoryColumnQuery,
|
||||
undefined,
|
||||
noop,
|
||||
txnErrorCallbackWithoutToast,
|
||||
);
|
||||
tx.executeSql(createNovelCategoryTableQuery);
|
||||
tx.executeSql(createChapterTableQuery, [], () => {
|
||||
tx.executeSql(createChapterNovelIdIndexQuery);
|
||||
});
|
||||
tx.executeSql(createChapterTableQuery);
|
||||
tx.executeSql(createHistoryTableQuery);
|
||||
tx.executeSql(createDownloadTableQuery);
|
||||
tx.executeSql(createUpdatesTableQuery);
|
||||
});
|
||||
};
|
||||
|
||||
const createIndexes = () => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(createUrlIndexQuery);
|
||||
tx.executeSql(createLibraryIndexQuery);
|
||||
tx.executeSql(createNovelIdIndexQuery);
|
||||
tx.executeSql(createUnreadChaptersIndexQuery);
|
||||
tx.executeSql(createChapterIdIndexQuery);
|
||||
tx.executeSql(createCategorydIndexQuery);
|
||||
tx.executeSql(createDownloadIdIndex);
|
||||
});
|
||||
};
|
||||
|
||||
export const createDatabase = async () => {
|
||||
createTables();
|
||||
createIndexes();
|
||||
};
|
||||
|
||||
/**
|
||||
* For Testing
|
||||
*/
|
||||
export const deleteDatabase = () => {
|
||||
export const deleteDatabase = async () => {
|
||||
db.transaction(
|
||||
tx => {
|
||||
tx.executeSql('DROP TABLE novels');
|
||||
tx.executeSql('DROP TABLE chapters');
|
||||
tx.executeSql('DROP TABLE history');
|
||||
tx.executeSql('DROP TABLE downloads');
|
||||
tx.executeSql('DROP TABLE updates');
|
||||
tx.executeSql('DROP TABLE categories');
|
||||
tx.executeSql('DROP TABLE Category');
|
||||
tx.executeSql('DROP TABLE Novel');
|
||||
tx.executeSql('DROP TABLE NovelCategory');
|
||||
tx.executeSql('DROP TABLE Chapter');
|
||||
tx.executeSql('DROP TABLE Download');
|
||||
},
|
||||
dbTxnErrorCallback,
|
||||
noop,
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import * as SQLite from 'expo-sqlite';
|
||||
import { noop } from 'lodash-es';
|
||||
import { Category } from '../types';
|
||||
import { BackupCategory, Category, NovelCategory, CCategory } from '../types';
|
||||
import { showToast } from '@utils/showToast';
|
||||
import { txnErrorCallback } from '../utils/helpers';
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
const getCategoriesQuery = `
|
||||
SELECT * FROM categories ORDER BY CASE WHEN id > 1 THEN 1 ELSE 0 END, IFNULL(sort, 9999)
|
||||
SELECT * FROM Category ORDER BY sort
|
||||
`;
|
||||
|
||||
export const getCategoriesFromDb = (): Promise<Category[]> => {
|
||||
export const getCategoriesFromDb = async (): Promise<Category[]> => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
@@ -21,31 +22,67 @@ export const getCategoriesFromDb = (): Promise<Category[]> => {
|
||||
);
|
||||
};
|
||||
|
||||
const createCategoryQuery = `
|
||||
INSERT INTO categories (name)
|
||||
VALUES
|
||||
(?)
|
||||
export const getCategoriesWithCount = async (
|
||||
novelIds: number[],
|
||||
): Promise<CCategory[]> => {
|
||||
const getCategoriesWithCountQuery = `
|
||||
SELECT *, novelsCount
|
||||
FROM Category LEFT JOIN
|
||||
(
|
||||
SELECT categoryId, COUNT(novelId) as novelsCount
|
||||
FROM NovelCategory WHERE novelId in (${novelIds.join(
|
||||
',',
|
||||
)}) GROUP BY categoryId
|
||||
) as NC ON Category.id = NC.categoryId
|
||||
ORDER BY sort
|
||||
`;
|
||||
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getCategoriesWithCountQuery,
|
||||
[],
|
||||
(txObj, { rows }) => resolve((rows as any)._array),
|
||||
txnErrorCallback,
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const createCategoryQuery = 'INSERT INTO Category (name) VALUES (?)';
|
||||
|
||||
export const createCategory = (categoryName: string): void =>
|
||||
db.transaction(tx =>
|
||||
tx.executeSql(createCategoryQuery, [categoryName], noop, txnErrorCallback),
|
||||
);
|
||||
|
||||
const deleteCategoryQuery = `
|
||||
DELETE FROM categories
|
||||
WHERE
|
||||
id = ?
|
||||
`;
|
||||
const beforeDeleteCategoryQuery = `
|
||||
UPDATE NovelCategory SET categoryId = (SELECT id FROM Category WHERE sort = 1)
|
||||
WHERE novelId IN (
|
||||
SELECT novelId FROM NovelCategory
|
||||
GROUP BY novelId
|
||||
HAVING COUNT(categoryId) = 1
|
||||
)
|
||||
AND categoryId = ?;
|
||||
`;
|
||||
const deleteCategoryQuery = 'DELETE FROM Category WHERE id = ?';
|
||||
|
||||
export const deleteCategoryById = (categoryId: number): void =>
|
||||
db.transaction(tx =>
|
||||
tx.executeSql(deleteCategoryQuery, [categoryId], noop, txnErrorCallback),
|
||||
);
|
||||
export const deleteCategoryById = (category: Category): void => {
|
||||
if (category.sort <= 2) {
|
||||
return showToast('You cant delete default category');
|
||||
}
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
beforeDeleteCategoryQuery,
|
||||
[category.id],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
tx.executeSql(deleteCategoryQuery, [category.id], noop, txnErrorCallback);
|
||||
});
|
||||
};
|
||||
|
||||
const updateCategoryQuery = `
|
||||
UPDATE categories SET name = ? WHERE id = ?
|
||||
`;
|
||||
const updateCategoryQuery = 'UPDATE Category SET name = ? WHERE id = ?';
|
||||
|
||||
export const updateCategory = (
|
||||
categoryId: number,
|
||||
@@ -61,7 +98,7 @@ export const updateCategory = (
|
||||
);
|
||||
|
||||
const isCategoryNameDuplicateQuery = `
|
||||
SELECT COUNT(*) as isDuplicate FROM categories WHERE name = ?
|
||||
SELECT COUNT(*) as isDuplicate FROM Category WHERE name = ?
|
||||
`;
|
||||
|
||||
export const isCategoryNameDuplicate = (
|
||||
@@ -82,11 +119,13 @@ export const isCategoryNameDuplicate = (
|
||||
);
|
||||
};
|
||||
|
||||
const updateCategoryOrderQuery = `
|
||||
UPDATE categories SET sort = ? WHERE id = ?
|
||||
`;
|
||||
const updateCategoryOrderQuery = 'UPDATE Category SET sort = ? WHERE id = ?';
|
||||
|
||||
export const updateCategoryOrderInDb = (categories: Category[]): void =>
|
||||
export const updateCategoryOrderInDb = (categories: Category[]): void => {
|
||||
// Do not set local as default one
|
||||
if (categories.length && categories[0].id == 2) {
|
||||
return;
|
||||
}
|
||||
db.transaction(tx => {
|
||||
categories.map(category => {
|
||||
tx.executeSql(
|
||||
@@ -97,3 +136,34 @@ export const updateCategoryOrderInDb = (categories: Category[]): void =>
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const getAllNovelCategories = (): Promise<NovelCategory[]> => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'SELECT * FROM NovelCategory',
|
||||
[],
|
||||
(txObj, { rows }) => resolve((rows as any)._array),
|
||||
txnErrorCallback,
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const _restoreCategory = (category: BackupCategory) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql('DELETE FROM Category WHERE id = ?', [category.id]);
|
||||
tx.executeSql('INSERT INTO Category (id, name, sort) VALUES (?, ?, ?)', [
|
||||
category.id,
|
||||
category.name,
|
||||
category.sort,
|
||||
]);
|
||||
for (const novelId of category.novelIds) {
|
||||
tx.executeSql(
|
||||
'INSERT INTO NovelCategory (categoryId, novelId) VALUES (?, ?)',
|
||||
[category.id, novelId],
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
import RNFS from 'react-native-fs';
|
||||
import * as SQLite from 'expo-sqlite';
|
||||
import { showToast } from '../../hooks/showToast';
|
||||
import { sourceManager } from '../../sources/sourceManager';
|
||||
import { ChapterItem } from '../types';
|
||||
import { showToast } from '@utils/showToast';
|
||||
import { getPlugin } from '@plugins/pluginManager';
|
||||
import { ChapterInfo, DownloadedChapter } from '../types';
|
||||
import { ChapterItem } from '@plugins/types';
|
||||
|
||||
import * as cheerio from 'cheerio';
|
||||
import RNFetchBlob from 'rn-fetch-blob';
|
||||
import { NovelDownloadFolder } from '@utils/constants/download';
|
||||
import { txnErrorCallback } from '@database/utils/helpers';
|
||||
import { Plugin } from '@plugins/types';
|
||||
import { Update } from '../types';
|
||||
import { noop } from 'lodash-es';
|
||||
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
const insertChaptersQuery = `
|
||||
INSERT INTO chapters (
|
||||
chapterUrl, chapterName, releaseDate,
|
||||
novelId
|
||||
const insertChapterQuery = `
|
||||
INSERT INTO Chapter (
|
||||
url, name, releaseTime, novelId, chapterNumber
|
||||
)
|
||||
values
|
||||
(?, ?, ?, ?)
|
||||
Values
|
||||
(?, ?, ?, ?, ?)
|
||||
`;
|
||||
|
||||
export const insertChapters = async (
|
||||
@@ -25,53 +29,56 @@ export const insertChapters = async (
|
||||
if (!chapters?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
db.transaction(tx => {
|
||||
chapters.map(chapter =>
|
||||
tx.executeSql(insertChaptersQuery, [
|
||||
chapter.chapterUrl,
|
||||
chapter.chapterName,
|
||||
chapter.releaseDate,
|
||||
novelId,
|
||||
]),
|
||||
);
|
||||
chapters.forEach(chapter => {
|
||||
tx.executeSql(
|
||||
insertChapterQuery,
|
||||
[
|
||||
chapter.url,
|
||||
chapter.name,
|
||||
chapter.releaseTime || '',
|
||||
novelId,
|
||||
chapter.chapterNumber || null,
|
||||
],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const getChaptersQuery = (sort = 'ORDER BY chapterId ASC', filter = '') =>
|
||||
`SELECT * FROM chapters WHERE novelId = ? ${filter} ${sort}`;
|
||||
const getChaptersQuery = (sort = 'ORDER BY id ASC', filter = '') =>
|
||||
`SELECT * FROM Chapter WHERE novelId = ? ${filter} ${sort}`;
|
||||
|
||||
export const getChapters = (novelId: number, sort: string, filter: string) => {
|
||||
export const getChapters = (
|
||||
novelId: number,
|
||||
sort?: string,
|
||||
filter?: string,
|
||||
): Promise<ChapterInfo[]> => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getChaptersQuery(sort, filter),
|
||||
[novelId],
|
||||
(txObj, { rows }) => {
|
||||
const _array = (rows as any)._array;
|
||||
resolve(_array);
|
||||
},
|
||||
(txObj, { rows }) => resolve((rows as any)._array),
|
||||
txnErrorCallback,
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const getChapterQuery = 'SELECT * FROM downloads WHERE downloadChapterId = ?';
|
||||
// downloaded chapter
|
||||
const getChapterQuery =
|
||||
'SELECT chapterText FROM Download WHERE Download.chapterId = ?';
|
||||
|
||||
export const getChapterFromDB = async (chapterId: number) => {
|
||||
export const getChapterFromDB = (chapterId: number): Promise<string> => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getChapterQuery,
|
||||
[chapterId],
|
||||
(txObj, results) => {
|
||||
resolve(results.rows.item(0));
|
||||
},
|
||||
(_txObj, _error) => {
|
||||
// console.log('Error ', error)
|
||||
return false;
|
||||
},
|
||||
(txObj, { rows }) => resolve(rows.item(0)?.chapterText),
|
||||
txnErrorCallback,
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -79,19 +86,19 @@ export const getChapterFromDB = async (chapterId: number) => {
|
||||
|
||||
const getPrevChapterQuery = `
|
||||
SELECT
|
||||
*
|
||||
id, *
|
||||
FROM
|
||||
chapters
|
||||
Chapter
|
||||
WHERE
|
||||
novelId = ?
|
||||
AND
|
||||
chapterId < ?
|
||||
id < ?
|
||||
`;
|
||||
|
||||
export const getPrevChapter = (
|
||||
novelId: number,
|
||||
chapterId: number,
|
||||
): Promise<ChapterItem> => {
|
||||
): Promise<ChapterInfo> => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
@@ -99,8 +106,8 @@ export const getPrevChapter = (
|
||||
[novelId, chapterId],
|
||||
(_txObj, results) =>
|
||||
resolve(results.rows.item(results.rows.length - 1)),
|
||||
(_txObj, error) => {
|
||||
showToast(error.message);
|
||||
() => {
|
||||
showToast("There's no previous chapter");
|
||||
return false;
|
||||
},
|
||||
);
|
||||
@@ -110,27 +117,27 @@ export const getPrevChapter = (
|
||||
|
||||
const getNextChapterQuery = `
|
||||
SELECT
|
||||
*
|
||||
id, *
|
||||
FROM
|
||||
chapters
|
||||
Chapter
|
||||
WHERE
|
||||
novelId = ?
|
||||
AND
|
||||
chapterId > ?
|
||||
id > ?
|
||||
`;
|
||||
|
||||
export const getNextChapter = (
|
||||
novelId: number,
|
||||
chapterId: number,
|
||||
): Promise<ChapterItem> => {
|
||||
): Promise<ChapterInfo> => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getNextChapterQuery,
|
||||
[novelId, chapterId],
|
||||
(_txObj, results) => resolve(results.rows.item(0)),
|
||||
(_txObj, error) => {
|
||||
showToast(error.message);
|
||||
() => {
|
||||
showToast("There's no next Chapter");
|
||||
return false;
|
||||
},
|
||||
);
|
||||
@@ -138,227 +145,126 @@ export const getNextChapter = (
|
||||
);
|
||||
};
|
||||
|
||||
const markChapterReadQuery =
|
||||
'UPDATE chapters SET `read` = 1 WHERE chapterId = ?';
|
||||
const markChapterReadQuery = 'UPDATE Chapter SET `unread` = 0 WHERE id = ?';
|
||||
|
||||
export const markChapterRead = async (chapterId: number) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
markChapterReadQuery,
|
||||
[chapterId],
|
||||
(_txObj, _res) => {},
|
||||
(_txObj, _error) => {
|
||||
// console.log(error)
|
||||
return false;
|
||||
},
|
||||
);
|
||||
tx.executeSql(markChapterReadQuery, [chapterId], noop, (_txObj, _error) => {
|
||||
// console.log(error)
|
||||
return false;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const markChapterUnreadQuery =
|
||||
'UPDATE chapters SET `read` = 0 WHERE chapterId = ?';
|
||||
const markChapterUnreadQuery = 'UPDATE Chapter SET `unread` = 1 WHERE id = ?';
|
||||
|
||||
export const markChapterUnread = async (chapterId: number) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
markChapterUnreadQuery,
|
||||
[chapterId],
|
||||
(_txObj, _res) => {},
|
||||
(_txObj, _error) => {
|
||||
// console.log(error)
|
||||
return false;
|
||||
},
|
||||
);
|
||||
tx.executeSql(markChapterUnreadQuery, [chapterId], noop, txnErrorCallback);
|
||||
});
|
||||
};
|
||||
|
||||
const markAllChaptersReadQuery =
|
||||
'UPDATE chapters SET `read` = 1 WHERE novelId = ?';
|
||||
'UPDATE Chapter SET `unread` = 0 WHERE novelId = ?';
|
||||
|
||||
export const markAllChaptersRead = async (novelId: number) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
markAllChaptersReadQuery,
|
||||
[novelId],
|
||||
(_txObj, _res) => {},
|
||||
(_txObj, _error) => {
|
||||
// console.log(error)
|
||||
return false;
|
||||
},
|
||||
);
|
||||
tx.executeSql(markAllChaptersReadQuery, [novelId], noop, txnErrorCallback);
|
||||
});
|
||||
};
|
||||
|
||||
const markAllChaptersUnreadQuery =
|
||||
'UPDATE chapters SET `read` = 0 WHERE novelId = ?';
|
||||
'UPDATE Chapter SET `unread` = 1 WHERE novelId = ?';
|
||||
|
||||
export const markAllChaptersUnread = async (novelId: number) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
markAllChaptersUnreadQuery,
|
||||
[novelId],
|
||||
(_txObj, _res) => {},
|
||||
(_txObj, _error) => {
|
||||
// console.log(error)
|
||||
return false;
|
||||
},
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const isChapterDownloadedQuery =
|
||||
'SELECT * FROM downloads WHERE downloadChapterId=?';
|
||||
|
||||
export const isChapterDownloaded = async (chapterId: number) => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
isChapterDownloadedQuery,
|
||||
[chapterId],
|
||||
(txObj, res) => {
|
||||
if (res.rows.length !== 0) {
|
||||
resolve(true);
|
||||
} else {
|
||||
resolve(false);
|
||||
}
|
||||
},
|
||||
(_txObj, _error) => {
|
||||
// console.log('Error ', error)
|
||||
return false;
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const downloadChapterQuery =
|
||||
'INSERT INTO downloads (downloadChapterId, chapterName, chapterText) VALUES (?, ?, ?)';
|
||||
|
||||
const createImageFolder = async (
|
||||
const createChapterFolder = async (
|
||||
path: string,
|
||||
data?: {
|
||||
sourceId: number;
|
||||
data: {
|
||||
pluginId: string;
|
||||
novelId: number;
|
||||
chapterId: number;
|
||||
},
|
||||
): Promise<string> => {
|
||||
const mkdirIfNot = async (p: string) => {
|
||||
const mkdirIfNot = async (p: string, nomedia: boolean) => {
|
||||
const nomediaPath =
|
||||
p + (p.charAt(p.length - 1) === '/' ? '' : '/') + '.nomedia';
|
||||
if (!(await RNFetchBlob.fs.exists(p))) {
|
||||
await RNFetchBlob.fs.mkdir(p);
|
||||
await RNFetchBlob.fs.createFile(nomediaPath, ',', 'utf8');
|
||||
if (!(await RNFS.exists(p))) {
|
||||
await RNFS.mkdir(p);
|
||||
if (nomedia) {
|
||||
await RNFS.writeFile(nomediaPath, ',', 'utf8');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await mkdirIfNot(path);
|
||||
await mkdirIfNot(path, false);
|
||||
|
||||
if (data) {
|
||||
const { sourceId, novelId, chapterId } = data;
|
||||
await mkdirIfNot(`${path}/${sourceId}/`);
|
||||
await mkdirIfNot(`${path}/${sourceId}/${novelId}/`);
|
||||
await mkdirIfNot(`${path}/${sourceId}/${novelId}/${chapterId}/`);
|
||||
return `${path}/${sourceId}/${novelId}/${chapterId}/`;
|
||||
} else {
|
||||
return path;
|
||||
}
|
||||
const { pluginId, novelId, chapterId } = data;
|
||||
await mkdirIfNot(`${path}/${pluginId}/${novelId}/${chapterId}/`, true);
|
||||
return `${path}/${pluginId}/${novelId}/${chapterId}/`;
|
||||
};
|
||||
|
||||
const downloadImages = async (
|
||||
const downloadFiles = async (
|
||||
html: string,
|
||||
sourceId: number,
|
||||
plugin: Plugin,
|
||||
novelId: number,
|
||||
chapterId: number,
|
||||
): Promise<string> => {
|
||||
): Promise<void> => {
|
||||
try {
|
||||
const headers = sourceManager(sourceId)?.headers || {};
|
||||
const folder = await createChapterFolder(NovelDownloadFolder, {
|
||||
pluginId: plugin.id,
|
||||
novelId,
|
||||
chapterId,
|
||||
}).catch(error => {
|
||||
throw error;
|
||||
});
|
||||
const loadedCheerio = cheerio.load(html);
|
||||
const imgs = loadedCheerio('img').toArray();
|
||||
for (let i = 0; i < imgs.length; i++) {
|
||||
const elem = loadedCheerio(imgs[i]);
|
||||
const url = elem.attr('src');
|
||||
if (url) {
|
||||
const imageb64 = (
|
||||
await RNFetchBlob.fetch('GET', url, headers)
|
||||
).base64();
|
||||
const fileurl =
|
||||
(await createImageFolder(
|
||||
`${RNFetchBlob.fs.dirs.DownloadDir}/LNReader`,
|
||||
{ sourceId, novelId, chapterId },
|
||||
).catch(() => {
|
||||
showToast(
|
||||
`Unexpected storage error!\nRemove ${fileurl} and try downloading again`,
|
||||
);
|
||||
return '--';
|
||||
})) +
|
||||
i +
|
||||
'.b64.png';
|
||||
if (fileurl.charAt(0) === '-') {
|
||||
return loadedCheerio.html();
|
||||
}
|
||||
const imageb64 = await plugin.fetchImage(url);
|
||||
const fileurl = folder + i + '.b64.png';
|
||||
elem.attr('src', `file://${fileurl}`);
|
||||
const exists = await RNFetchBlob.fs.exists(fileurl).catch(() => {
|
||||
showToast(
|
||||
`Unexpected storage error!\nRemove ${fileurl} and try downloading again`,
|
||||
);
|
||||
});
|
||||
if (!exists) {
|
||||
RNFetchBlob.fs.createFile(fileurl, imageb64, 'base64').catch(() => {
|
||||
showToast(
|
||||
`Unexpected storage error!\nRemove ${fileurl} and try downloading again`,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
RNFetchBlob.fs.writeFile(fileurl, imageb64, 'base64').catch(() => {
|
||||
showToast(
|
||||
`Unexpected storage error!\nRemove ${fileurl} and try downloading again`,
|
||||
);
|
||||
});
|
||||
}
|
||||
RNFS.writeFile(fileurl, imageb64, 'base64');
|
||||
}
|
||||
}
|
||||
loadedCheerio('body').prepend("<input type='hidden' offline />");
|
||||
return loadedCheerio.html();
|
||||
} catch (e) {
|
||||
return html;
|
||||
RNFS.writeFile(folder + 'index.html', loadedCheerio.html());
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// novelId for determine folder %LNReaderDownloadDir%/novelId/ChapterId/
|
||||
export const downloadChapter = async (
|
||||
sourceId: number,
|
||||
novelUrl: string,
|
||||
pluginId: string,
|
||||
novelId: number,
|
||||
chapterUrl: string,
|
||||
chapterId: number,
|
||||
chapterUrl: string,
|
||||
) => {
|
||||
try {
|
||||
const source = sourceManager(sourceId);
|
||||
|
||||
const chapter = await source.parseChapter(novelUrl, chapterUrl);
|
||||
|
||||
if (chapter.chapterText?.length) {
|
||||
const imagedChapterText =
|
||||
chapter.chapterText &&
|
||||
(await downloadImages(
|
||||
chapter.chapterText,
|
||||
sourceId,
|
||||
novelId,
|
||||
chapterId,
|
||||
));
|
||||
|
||||
const plugin = getPlugin(pluginId);
|
||||
if (!plugin) {
|
||||
throw new Error('Plugin not found!');
|
||||
}
|
||||
const chapterText = await plugin.parseChapter(chapterUrl);
|
||||
if (chapterText && chapterText.length) {
|
||||
await downloadFiles(chapterText, plugin, novelId, chapterId);
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE chapters SET downloaded = 1 WHERE chapterId = ?',
|
||||
"UPDATE Chapter SET isDownloaded = 1, updatedTime = datetime('now','localtime') WHERE id = ?",
|
||||
[chapterId],
|
||||
);
|
||||
tx.executeSql(
|
||||
downloadChapterQuery,
|
||||
[chapterId, chapter.chapterName, imagedChapterText],
|
||||
(_txObj, _res) => {
|
||||
return true;
|
||||
},
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
throw new Error("Either chapter is empty or the app couldn't scrape it");
|
||||
@@ -368,81 +274,59 @@ export const downloadChapter = async (
|
||||
}
|
||||
};
|
||||
|
||||
const deleteDownloadedImages = async (
|
||||
sourceId: number,
|
||||
const deleteDownloadedFiles = async (
|
||||
pluginId: string,
|
||||
novelId: number,
|
||||
chapterId: number,
|
||||
) => {
|
||||
try {
|
||||
const path = await createImageFolder(
|
||||
`${RNFetchBlob.fs.dirs.DownloadDir}/LNReader`,
|
||||
{ sourceId, novelId, chapterId },
|
||||
);
|
||||
const files = await RNFetchBlob.fs.ls(path);
|
||||
const path = await createChapterFolder(NovelDownloadFolder, {
|
||||
pluginId,
|
||||
novelId,
|
||||
chapterId,
|
||||
});
|
||||
const files = await RNFS.readDir(path);
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const ex = /\.b64\.png/.exec(files[i]);
|
||||
if (ex) {
|
||||
if (await RNFetchBlob.fs.exists(`${path}${files[i]}`)) {
|
||||
RNFetchBlob.fs.unlink(`${path}${files[i]}`);
|
||||
}
|
||||
}
|
||||
await RNFS.unlink(files[i].path);
|
||||
}
|
||||
} catch (error) {}
|
||||
await RNFS.unlink(path);
|
||||
} catch (error) {
|
||||
throw new Error('Cant delete chapter chapter folder');
|
||||
}
|
||||
};
|
||||
|
||||
// delete downloaded chapter
|
||||
export const deleteChapter = async (
|
||||
sourceId: number,
|
||||
pluginId: string,
|
||||
novelId: number,
|
||||
chapterId: number,
|
||||
) => {
|
||||
const updateIsDownloadedQuery =
|
||||
'UPDATE chapters SET downloaded = 0 WHERE chapterId=?';
|
||||
const deleteChapterQuery = 'DELETE FROM downloads WHERE downloadChapterId=?';
|
||||
'UPDATE Chapter SET isDownloaded = 0 WHERE id = ?';
|
||||
|
||||
await deleteDownloadedImages(sourceId, novelId, chapterId);
|
||||
await deleteDownloadedFiles(pluginId, novelId, chapterId);
|
||||
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
updateIsDownloadedQuery,
|
||||
[chapterId],
|
||||
(_txObj, _res) => {},
|
||||
(_txObj, _error) => {
|
||||
// console.log('Error ', error)
|
||||
return false;
|
||||
},
|
||||
);
|
||||
tx.executeSql(
|
||||
deleteChapterQuery,
|
||||
[chapterId],
|
||||
(_txObj, _res) => {
|
||||
// console.log('Chapter deleted');
|
||||
},
|
||||
(_txObj, _error) => {
|
||||
// console.log('Error ', error)
|
||||
return false;
|
||||
},
|
||||
);
|
||||
tx.executeSql(updateIsDownloadedQuery, [chapterId], noop, txnErrorCallback);
|
||||
});
|
||||
};
|
||||
|
||||
export const deleteChapters = async (
|
||||
sourceId: number,
|
||||
chapters?: ChapterItem[],
|
||||
pluginId: string,
|
||||
novelId: number,
|
||||
chapters?: ChapterInfo[],
|
||||
) => {
|
||||
if (!chapters?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const chapterIdsString = chapters
|
||||
?.map(chapter => chapter.chapterId)
|
||||
.toString();
|
||||
const chapterIdsString = chapters?.map(chapter => chapter.id).toString();
|
||||
|
||||
const updateIsDownloadedQuery = `UPDATE chapters SET downloaded = 0 WHERE chapterId IN (${chapterIdsString})`;
|
||||
const deleteChapterQuery = `DELETE FROM downloads WHERE downloadChapterId IN (${chapterIdsString})`;
|
||||
const updateIsDownloadedQuery = `UPDATE Chapter SET isDownloaded = 0 WHERE id IN (${chapterIdsString})`;
|
||||
|
||||
await Promise.all(
|
||||
chapters?.map(chapter =>
|
||||
deleteDownloadedImages(sourceId, chapter.novelId, chapter.chapterId),
|
||||
deleteDownloadedFiles(pluginId, novelId, chapter.id),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -453,42 +337,62 @@ export const deleteChapters = async (
|
||||
undefined,
|
||||
txnErrorCallback,
|
||||
);
|
||||
tx.executeSql(deleteChapterQuery, undefined, undefined, txnErrorCallback);
|
||||
});
|
||||
};
|
||||
|
||||
const getLastReadChapterQuery = `
|
||||
SELECT chapters.*
|
||||
FROM history
|
||||
JOIN chapters
|
||||
ON history.historyChapterId = chapters.chapterId
|
||||
WHERE history.historyNovelId = ?
|
||||
`;
|
||||
export const deleteDownloads = async (chapters: DownloadedChapter[]) => {
|
||||
await Promise.all(
|
||||
chapters?.map(chapter => {
|
||||
deleteDownloadedFiles(chapter.pluginId, chapter.novelId, chapter.id);
|
||||
}),
|
||||
);
|
||||
db.transaction(tx => {
|
||||
tx.executeSql('UPDATE Chapter SET isDownloaded = 0', [], () =>
|
||||
showToast('Deleted all Downloads'),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const getLastReadChapter = async (novelId: number) => {
|
||||
const getReadDownloadedChapters = async (): Promise<DownloadedChapter[]> => {
|
||||
return new Promise(resolve => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getLastReadChapterQuery,
|
||||
[novelId],
|
||||
(txObj, { rows }) => resolve(rows.item(0)),
|
||||
(_txObj, _error) => {
|
||||
// console.log('Error ', error)
|
||||
return false;
|
||||
},
|
||||
`
|
||||
SELECT Chapter.id, Chapter.novelId, pluginId
|
||||
FROM Chapter
|
||||
JOIN Novel
|
||||
ON Novel.id = Chapter.novelId AND unread = 0 AND isDownloaded = 1`,
|
||||
[],
|
||||
(txObj, { rows }) => resolve((rows as any)._array),
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const bookmarkChapterQuery =
|
||||
'UPDATE chapters SET bookmark = ? WHERE chapterId = ?';
|
||||
export const deleteReadChaptersFromDb = async () => {
|
||||
const chapters = await getReadDownloadedChapters();
|
||||
await Promise.all(
|
||||
chapters?.map(chapter => {
|
||||
deleteDownloadedFiles(chapter.pluginId, chapter.novelId, chapter.novelId);
|
||||
}),
|
||||
);
|
||||
const chapterIdsString = chapters?.map(chapter => chapter.id).toString();
|
||||
|
||||
const updateIsDownloadedQuery = `UPDATE Chapter SET isDownloaded = 0 WHERE id IN (${chapterIdsString})`;
|
||||
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(updateIsDownloadedQuery, [], noop, txnErrorCallback);
|
||||
});
|
||||
showToast('Read chapters deleted');
|
||||
};
|
||||
|
||||
const bookmarkChapterQuery = 'UPDATE Chapter SET bookmark = ? WHERE id = ?';
|
||||
|
||||
export const bookmarkChapter = async (bookmark: boolean, chapterId: number) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
bookmarkChapterQuery,
|
||||
[!bookmark, chapterId],
|
||||
[1 - Number(bookmark), chapterId],
|
||||
(_txObj, _res) => {},
|
||||
(_txObj, _error) => {
|
||||
// console.log('Error ', error)
|
||||
@@ -499,7 +403,7 @@ export const bookmarkChapter = async (bookmark: boolean, chapterId: number) => {
|
||||
};
|
||||
|
||||
const markPreviuschaptersReadQuery =
|
||||
'UPDATE chapters SET `read` = 1 WHERE chapterId < ? AND novelId = ?';
|
||||
'UPDATE Chapter SET `unread` = 0 WHERE id <= ? AND novelId = ?';
|
||||
|
||||
export const markPreviuschaptersRead = async (
|
||||
chapterId: number,
|
||||
@@ -519,7 +423,7 @@ export const markPreviuschaptersRead = async (
|
||||
};
|
||||
|
||||
const markPreviousChaptersUnreadQuery =
|
||||
'UPDATE chapters SET `read` = 0 WHERE chapterId < ? AND novelId = ?';
|
||||
'UPDATE Chapter SET `unread` = 1 WHERE id <= ? AND novelId = ?';
|
||||
|
||||
export const markPreviousChaptersUnread = async (
|
||||
chapterId: number,
|
||||
@@ -539,21 +443,23 @@ export const markPreviousChaptersUnread = async (
|
||||
};
|
||||
|
||||
const getDownloadedChaptersQuery = `
|
||||
SELECT chapters.*, novels.sourceId, novels.novelName, novels.novelCover, novels.novelUrl
|
||||
FROM chapters
|
||||
JOIN novels
|
||||
ON chapters.novelId = novels.novelId
|
||||
WHERE chapters.downloaded = 1`;
|
||||
SELECT
|
||||
Chapter.*,
|
||||
Novel.pluginId, Novel.name as novelName, Novel.cover as novelCover, Novel.url as novelUrl
|
||||
FROM Chapter
|
||||
JOIN Novel
|
||||
ON Chapter.novelId = Novel.id
|
||||
WHERE Chapter.isDownloaded = 1
|
||||
`;
|
||||
|
||||
export const getDownloadedChapters = () => {
|
||||
export const getDownloadedChapters = (): Promise<DownloadedChapter[]> => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getDownloadedChaptersQuery,
|
||||
undefined,
|
||||
(txObj, { rows }) => {
|
||||
const _array = (rows as any)._array;
|
||||
resolve(_array);
|
||||
resolve(rows._array);
|
||||
},
|
||||
(_txObj, _error) => {
|
||||
// console.log('Error ', error)
|
||||
@@ -564,25 +470,38 @@ export const getDownloadedChapters = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export const deleteDownloads = async () => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql('UPDATE chapters SET downloaded = 0');
|
||||
tx.executeSql('DELETE FROM downloads; VACCUM;');
|
||||
});
|
||||
const getUpdatesQuery = `
|
||||
SELECT
|
||||
Chapter.*,
|
||||
pluginId, Novel.id as novelId, Novel.name as novelName, Novel.url as novelUrl, cover as novelCover
|
||||
FROM
|
||||
Chapter
|
||||
JOIN
|
||||
Novel
|
||||
ON Chapter.novelId = Novel.id AND Chapter.updatedTime IS NOT NULL
|
||||
ORDER BY Chapter.updatedTime DESC
|
||||
`;
|
||||
|
||||
export const getUpdatesFromDb = (): Promise<Update[]> => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getUpdatesQuery,
|
||||
[],
|
||||
(txObj, { rows }) => resolve((rows as any)._array),
|
||||
txnErrorCallback,
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const updateChapterDownloadedQuery = `
|
||||
UPDATE
|
||||
chapters
|
||||
SET
|
||||
downloaded = 1
|
||||
WHERE
|
||||
chapterId = ?`;
|
||||
|
||||
export const updateChapterDeletedQuery = `
|
||||
UPDATE
|
||||
chapters
|
||||
SET
|
||||
downloaded = 0
|
||||
WHERE
|
||||
chapterId = ?`;
|
||||
export const clearUpdates = () => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE Chapter SET updatedTime = NULL',
|
||||
[],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
|
||||
import { txnErrorCallback } from '@database/utils/helpers';
|
||||
import * as SQLite from 'expo-sqlite';
|
||||
import { showToast } from '../../hooks/showToast';
|
||||
import { sourceManager } from '../../sources/sourceManager';
|
||||
import { DownloadedChapter } from '../types';
|
||||
|
||||
import {
|
||||
updateChapterDeletedQuery,
|
||||
updateChapterDownloadedQuery,
|
||||
} from './ChapterQueries';
|
||||
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
const downloadChapterQuery = `
|
||||
INSERT INTO
|
||||
downloads (downloadChapterId, chapterName, chapterText)
|
||||
VALUES
|
||||
(?, ?, ?)
|
||||
`;
|
||||
|
||||
export const fetchAndInsertChapterInDb = async (
|
||||
sourceId: number,
|
||||
novelUrl: string,
|
||||
chapterId: number,
|
||||
chapterUrl: string,
|
||||
) => {
|
||||
const chapter = await sourceManager(sourceId).parseChapter(
|
||||
novelUrl,
|
||||
chapterUrl,
|
||||
);
|
||||
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(updateChapterDownloadedQuery, [chapterId]);
|
||||
tx.executeSql(
|
||||
downloadChapterQuery,
|
||||
[chapterId, chapter.chapterName, chapter.chapterText],
|
||||
(txObj, res) => {},
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const deleteChapterFromDbQuery = `
|
||||
DELETE FROM
|
||||
downloads
|
||||
WHERE
|
||||
downloadChapterId = ?
|
||||
`;
|
||||
|
||||
export const deleteChapterFromDb = (chapterId: number) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(updateChapterDeletedQuery, [chapterId]);
|
||||
tx.executeSql(
|
||||
deleteChapterFromDbQuery,
|
||||
[chapterId],
|
||||
(txObj, res) => {},
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const getChapterFromDbQuery = `
|
||||
SELECT
|
||||
*
|
||||
FROM
|
||||
downloads
|
||||
WHERE
|
||||
downloadChapterId = ?
|
||||
`;
|
||||
|
||||
export const getChapterFromDb = async (
|
||||
chapterId: number,
|
||||
): Promise<DownloadedChapter> => {
|
||||
return new Promise((resolve, reject) =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getChapterFromDbQuery,
|
||||
[chapterId],
|
||||
(txObj, results) => resolve(results.rows.item(0)),
|
||||
(_, error) => {
|
||||
reject(error);
|
||||
return false;
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const deleteReadChaptersFromDbQuery = `
|
||||
DELETE FROM
|
||||
downloads
|
||||
WHERE
|
||||
downloads.downloadChapterId IN (
|
||||
SELECT
|
||||
chapters.chapterId
|
||||
FROM
|
||||
downloads
|
||||
INNER JOIN chapters ON chapters.chapterId = downloads.downloadChapterId
|
||||
WHERE
|
||||
chapters.read = 1
|
||||
);
|
||||
`;
|
||||
|
||||
let updateChaptersDeletedQuery = `
|
||||
UPDATE
|
||||
chapters
|
||||
SET
|
||||
downloaded = 0
|
||||
WHERE
|
||||
chapters.chapterId IN (
|
||||
SELECT
|
||||
downloads.downloadChapterId
|
||||
FROM
|
||||
downloads
|
||||
INNER JOIN chapters ON chapters.chapterId = downloads.downloadChapterId
|
||||
WHERE
|
||||
chapters.read = 1
|
||||
);
|
||||
`;
|
||||
|
||||
export const deleteReadChaptersFromDb = (chapterId: number) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
updateChaptersDeletedQuery,
|
||||
[],
|
||||
(txObj, res) => {},
|
||||
txnErrorCallback,
|
||||
);
|
||||
tx.executeSql(
|
||||
deleteReadChaptersFromDbQuery,
|
||||
[],
|
||||
(txObj, res) => showToast('Deleted read chapters.'),
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
};
|
||||
@@ -1,69 +0,0 @@
|
||||
import * as SQLite from 'expo-sqlite';
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
import { showToast } from '../../hooks/showToast';
|
||||
|
||||
const getHistoryQuery = `
|
||||
SELECT history.*, chapters.*, novels.*
|
||||
FROM history
|
||||
JOIN chapters
|
||||
ON history.historyChapterId = chapters.chapterId
|
||||
JOIN novels
|
||||
ON history.historyNovelId = novels.novelId
|
||||
GROUP BY novels.novelId
|
||||
HAVING history.historyTimeRead = MAX(history.historyTimeRead)
|
||||
ORDER BY history.historyTimeRead DESC
|
||||
`;
|
||||
|
||||
export const getHistoryFromDb = async () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getHistoryQuery,
|
||||
null,
|
||||
(txObj, { rows: { _array } }) => {
|
||||
resolve(_array);
|
||||
},
|
||||
(txObj, error) => {
|
||||
// console.log('Error ', error)
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// const insertHistoryQuery =
|
||||
|
||||
export const insertHistory = async (novelId, chapterId) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
"INSERT OR REPLACE INTO history (historyNovelId, historyChapterId, historyTimeRead) VALUES (?, ?, (datetime('now','localtime')))",
|
||||
[novelId, chapterId],
|
||||
(txObj, res) => {},
|
||||
(txObj, error) => {
|
||||
// console.log('Error ', error)
|
||||
},
|
||||
);
|
||||
tx.executeSql('UPDATE novels SET unread = 0 WHERE novelId = ?', [novelId]);
|
||||
});
|
||||
};
|
||||
|
||||
export const deleteChapterHistory = async historyId => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'DELETE FROM history WHERE historyId = ?',
|
||||
[historyId],
|
||||
(txObj, res) => {},
|
||||
(txObj, error) => {
|
||||
// console.log('Error ', error)
|
||||
},
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const deleteAllHistory = async () => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql('DELETE FROM history; VACCUM;');
|
||||
});
|
||||
showToast('History deleted.');
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import { History } from '@database/types';
|
||||
import { txnErrorCallback } from '@database/utils/helpers';
|
||||
import * as SQLite from 'expo-sqlite';
|
||||
import { noop } from 'lodash-es';
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
import { showToast } from '../../utils/showToast';
|
||||
|
||||
const getHistoryQuery = `
|
||||
SELECT
|
||||
Chapter.novelId, Novel.pluginId, Novel.name as novelName, Novel.url as novelUrl, Novel.cover as novelCover,
|
||||
Chapter.id, Chapter.name as chapterName, Chapter.url as chapterUrl, Chapter.bookmark, Chapter.readTime
|
||||
FROM Chapter
|
||||
JOIN Novel
|
||||
ON Chapter.novelId = Novel.id AND Chapter.readTime IS NOT NULL
|
||||
ORDER BY readTime DESC
|
||||
`;
|
||||
|
||||
export const getHistoryFromDb = async (): Promise<History[]> => {
|
||||
return new Promise(resolve => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getHistoryQuery,
|
||||
[],
|
||||
(txObj, { rows }) => {
|
||||
resolve((rows as any)._array);
|
||||
},
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const insertHistory = async (chapterId: number) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
"UPDATE Chapter SET readTime = datetime('now','localtime') WHERE id = ?",
|
||||
[chapterId],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const deleteChapterHistory = async (chapterId: number) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE Chapter SET readTime = NULL WHERE id = ?',
|
||||
[chapterId],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const deleteAllHistory = async () => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql('UPDATE CHAPTER SET readTime = NULL');
|
||||
});
|
||||
showToast('History deleted.');
|
||||
};
|
||||
@@ -5,77 +5,30 @@ import { txnErrorCallback } from '../utils/helpers';
|
||||
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
const getLibraryQuery = `
|
||||
SELECT novels.*, C.chaptersUnread, D.chaptersDownloaded, H.lastReadAt, U.lastUpdatedAt
|
||||
FROM novels
|
||||
LEFT JOIN (
|
||||
SELECT chapters.novelId, COUNT(*) AS chaptersUnread
|
||||
FROM chapters
|
||||
WHERE chapters.read = 0
|
||||
GROUP BY chapters.novelId
|
||||
) AS C
|
||||
ON novels.novelId = C.novelId
|
||||
LEFT JOIN (
|
||||
SELECT chapters.novelId, COUNT(*) AS chaptersDownloaded
|
||||
FROM chapters
|
||||
WHERE chapters.downloaded = 1
|
||||
GROUP BY chapters.novelId
|
||||
) AS D
|
||||
ON novels.novelId = D.novelId
|
||||
LEFT JOIN (
|
||||
SELECT history.historyNovelId as novelId, historyTimeRead AS lastReadAt
|
||||
FROM history
|
||||
GROUP BY history.historyNovelId
|
||||
HAVING history.historyTimeRead = MAX(history.historyTimeRead)
|
||||
ORDER BY history.historyTimeRead DESC
|
||||
) AS H
|
||||
ON novels.novelId = H.novelId
|
||||
LEFT JOIN (
|
||||
SELECT updates.novelId, updateTime AS lastUpdatedAt
|
||||
FROM updates
|
||||
GROUP BY updates.novelId
|
||||
HAVING updates.updateTime = MAX(updates.updateTime)
|
||||
ORDER BY updates.updateTime DESC
|
||||
) AS U
|
||||
ON novels.novelId = U.novelId
|
||||
WHERE novels.followed = 1
|
||||
`;
|
||||
|
||||
export const getLibrary = ({
|
||||
filter,
|
||||
searchText,
|
||||
sortOrder,
|
||||
downloadedOnlyMode,
|
||||
}: {
|
||||
sortOrder?: string;
|
||||
filter?: string;
|
||||
searchText?: string;
|
||||
downloadedOnlyMode?: boolean;
|
||||
}): Promise<LibraryNovelInfo[]> => {
|
||||
let query = getLibraryQuery;
|
||||
|
||||
if (filter) {
|
||||
query += ` AND ${filter}`;
|
||||
}
|
||||
|
||||
if (downloadedOnlyMode) {
|
||||
query += ' ' + LibraryFilter.DownloadedOnly;
|
||||
}
|
||||
|
||||
if (searchText) {
|
||||
query += ` AND novelName LIKE '%${searchText}%'`;
|
||||
}
|
||||
|
||||
if (sortOrder) {
|
||||
query += ` ORDER BY ${sortOrder}`;
|
||||
export const getNovelsWithCategory = (
|
||||
categoryId: number,
|
||||
onlyOngoingNovels?: boolean,
|
||||
): Promise<NovelInfo[]> => {
|
||||
let query = `
|
||||
SELECT
|
||||
*
|
||||
FROM Novel
|
||||
JOIN (
|
||||
SELECT novelId
|
||||
FROM NovelCategory WHERE categoryId = ?
|
||||
) as NC
|
||||
ON Novel.id = NC.novelId
|
||||
`;
|
||||
if (onlyOngoingNovels) {
|
||||
query += " AND status NOT LIKE 'Completed'";
|
||||
}
|
||||
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
query,
|
||||
undefined,
|
||||
(txObj, { rows: { _array } }) => resolve(_array),
|
||||
[categoryId],
|
||||
(txObj, { rows }) => resolve((rows as any)._array),
|
||||
txnErrorCallback,
|
||||
);
|
||||
}),
|
||||
@@ -85,7 +38,7 @@ export const getLibrary = ({
|
||||
export const getLibraryNovelsFromDb = (
|
||||
onlyOngoingNovels?: boolean,
|
||||
): Promise<NovelInfo[]> => {
|
||||
let getLibraryNovelsQuery = 'SELECT * FROM novels WHERE followed = 1';
|
||||
let getLibraryNovelsQuery = 'SELECT * FROM Novel WHERE inLibrary = 1';
|
||||
|
||||
if (onlyOngoingNovels) {
|
||||
getLibraryNovelsQuery += " AND status NOT LIKE 'Completed'";
|
||||
@@ -96,7 +49,71 @@ export const getLibraryNovelsFromDb = (
|
||||
tx.executeSql(
|
||||
getLibraryNovelsQuery,
|
||||
undefined,
|
||||
(txObj, { rows: { _array } }) => resolve(_array),
|
||||
(txObj, { rows }) => resolve((rows as any)._array),
|
||||
txnErrorCallback,
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const getLibraryWithCategoryQuery = `
|
||||
SELECT
|
||||
NIL.*, chaptersUnread, chaptersDownloaded, lastReadAt, lastUpdatedAt
|
||||
FROM
|
||||
(
|
||||
SELECT
|
||||
Novel.*,
|
||||
category,
|
||||
categoryId
|
||||
FROM
|
||||
Novel LEFT JOIN (
|
||||
SELECT NovelId, name as category, categoryId FROM (NovelCategory JOIN Category ON NovelCategory.categoryId = Category.id)
|
||||
) as NC ON Novel.id = NC.novelId
|
||||
WHERE inLibrary = 1
|
||||
) as NIL
|
||||
JOIN
|
||||
(
|
||||
SELECT
|
||||
SUM(unread) as chaptersUnread, SUM(isDownloaded) as chaptersDownloaded,
|
||||
novelId, MAX(readTime) as lastReadAt, MAX(updatedTime) as lastUpdatedAt
|
||||
FROM Chapter
|
||||
GROUP BY novelId
|
||||
) as C ON NIL.id = C.novelId
|
||||
`;
|
||||
|
||||
export const getLibraryWithCategory = ({
|
||||
filter,
|
||||
searchText,
|
||||
sortOrder,
|
||||
downloadedOnlyMode,
|
||||
}: {
|
||||
sortOrder?: string;
|
||||
filter?: string;
|
||||
searchText?: string;
|
||||
downloadedOnlyMode?: boolean;
|
||||
}): Promise<LibraryNovelInfo[]> => {
|
||||
let query = getLibraryWithCategoryQuery;
|
||||
if (filter) {
|
||||
query += ` AND ${filter} `;
|
||||
}
|
||||
if (downloadedOnlyMode) {
|
||||
query += ' ' + LibraryFilter.DownloadedOnly;
|
||||
}
|
||||
|
||||
if (searchText) {
|
||||
query += ` AND name LIKE '%${searchText}%' `;
|
||||
}
|
||||
|
||||
if (sortOrder) {
|
||||
query += ` ORDER BY ${sortOrder} `;
|
||||
}
|
||||
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
query,
|
||||
[],
|
||||
(txObj, { rows }) => resolve((rows as any)._array),
|
||||
txnErrorCallback,
|
||||
);
|
||||
}),
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
import * as SQLite from 'expo-sqlite';
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
import BackgroundService from 'react-native-background-actions';
|
||||
import * as DocumentPicker from 'expo-document-picker';
|
||||
|
||||
import { fetchChapters, fetchNovel } from '../../services/Source/source';
|
||||
import { insertChapters } from './ChapterQueries';
|
||||
|
||||
import { showToast } from '../../hooks/showToast';
|
||||
import { txnErrorCallback } from '../utils/helpers';
|
||||
import { noop } from 'lodash-es';
|
||||
|
||||
const insertNovelQuery =
|
||||
'INSERT INTO novels (novelUrl, sourceUrl, sourceId, source, novelName, novelCover, novelSummary, author, artist, status, genre, categoryIds) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
|
||||
|
||||
export const insertNovel = async novel => {
|
||||
return new Promise((resolve, reject) =>
|
||||
db.transaction(tx =>
|
||||
tx.executeSql(
|
||||
insertNovelQuery,
|
||||
[
|
||||
novel.novelUrl,
|
||||
novel.sourceUrl,
|
||||
novel.sourceId,
|
||||
novel.source,
|
||||
novel.novelName,
|
||||
novel.novelCover || '',
|
||||
novel.novelSummary,
|
||||
novel.author,
|
||||
novel.artist,
|
||||
novel.status,
|
||||
novel.genre,
|
||||
JSON.stringify(novel.categoryIds),
|
||||
],
|
||||
(txObj, { insertId }) => resolve(insertId),
|
||||
txnErrorCallback,
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
export const followNovel = async (followed, novelId) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE novels SET followed = ? WHERE novelId = ?',
|
||||
[!followed, novelId],
|
||||
(txo, res) => {},
|
||||
(txObj, error) => {
|
||||
// console.log('Error ', error)
|
||||
},
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const checkNovelInCacheQuery = 'SELECT * FROM novels WHERE novelUrl=? LIMIT 1';
|
||||
|
||||
export const checkNovelInCache = novelUrl => {
|
||||
return new Promise((resolve, reject) =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
checkNovelInCacheQuery,
|
||||
[novelUrl],
|
||||
(txObj, res) => {
|
||||
if (res.rows.length !== 0) {
|
||||
resolve(true);
|
||||
} else {
|
||||
resolve(false);
|
||||
}
|
||||
},
|
||||
(txObj, error) => {
|
||||
// console.log('Error ', error)
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const getNovel = async (sourceId, novelUrl) => {
|
||||
return new Promise((resolve, reject) =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'SELECT * FROM novels WHERE novelUrl = ? AND sourceId = ?',
|
||||
[novelUrl, sourceId],
|
||||
(txObj, { rows }) => resolve(rows.item(0)),
|
||||
(txObj, error) => {
|
||||
// console.log('Error ', error)
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const deleteNovelCache = () => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'DELETE FROM novels WHERE followed = 0',
|
||||
null,
|
||||
(txObj, res) => showToast('Entries deleted'),
|
||||
(txObj, error) => {
|
||||
// console.log('Error ', error)
|
||||
},
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const restoreFromBackupQuery =
|
||||
'INSERT INTO novels (novelUrl, sourceUrl, sourceId, source, novelName, novelCover, novelSummary, author, artist, status, genre, followed, unread) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
|
||||
|
||||
export const restoreLibrary = async novel => {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.transaction(tx =>
|
||||
tx.executeSql(
|
||||
restoreFromBackupQuery,
|
||||
[
|
||||
novel.novelUrl,
|
||||
novel.sourceUrl,
|
||||
novel.sourceId,
|
||||
novel.source,
|
||||
novel.novelName,
|
||||
novel.novelCover,
|
||||
novel.novelSummary,
|
||||
novel.author,
|
||||
novel.artist,
|
||||
novel.status,
|
||||
novel.genre,
|
||||
novel.followed,
|
||||
novel.unread,
|
||||
],
|
||||
async (txObj, { insertId }) => {
|
||||
const chapters = await fetchChapters(novel.sourceId, novel.novelUrl);
|
||||
|
||||
if (chapters.length) {
|
||||
await insertChapters(insertId, chapters);
|
||||
|
||||
resolve();
|
||||
}
|
||||
},
|
||||
(txObj, error) => {
|
||||
resolve();
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const migrateNovelQuery =
|
||||
'INSERT INTO novels (novelUrl, sourceUrl, sourceId, source, novelName, novelCover, novelSummary, author, artist, status, genre, followed) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
|
||||
|
||||
export const migrateNovel = async (sourceId, novelUrl) => {
|
||||
try {
|
||||
const novel = await fetchNovel(sourceId, novelUrl);
|
||||
|
||||
const options = {
|
||||
taskName: 'Migration',
|
||||
taskTitle: `Migrating ${novel.novelName} to new source`,
|
||||
taskDesc: novel.source,
|
||||
taskIcon: {
|
||||
name: 'notification_icon',
|
||||
type: 'drawable',
|
||||
},
|
||||
color: '#00adb5',
|
||||
parameters: {
|
||||
delay: 1000,
|
||||
},
|
||||
progressBar: {
|
||||
max: 1,
|
||||
value: 0,
|
||||
indeterminate: true,
|
||||
},
|
||||
};
|
||||
|
||||
const veryIntensiveTask = async () => {
|
||||
await new Promise(async resolve => {
|
||||
db.transaction(tx =>
|
||||
tx.executeSql(
|
||||
migrateNovelQuery,
|
||||
[
|
||||
novel.novelUrl,
|
||||
novel.sourceUrl,
|
||||
novel.sourceId,
|
||||
novel.source,
|
||||
novel.novelName,
|
||||
novel.novelCover,
|
||||
novel.novelSummary,
|
||||
novel.author,
|
||||
novel.artist,
|
||||
novel.status,
|
||||
novel.genre,
|
||||
1,
|
||||
],
|
||||
async (txObj, { insertId }) => {
|
||||
const chapters = await fetchChapters(
|
||||
novel.sourceId,
|
||||
novel.novelUrl,
|
||||
);
|
||||
await insertChapters(insertId, chapters);
|
||||
resolve();
|
||||
},
|
||||
(txObj, error) => {
|
||||
// console.log('Error ', error)
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
await BackgroundService.start(veryIntensiveTask, options);
|
||||
await BackgroundService.updateNotification({
|
||||
progressBar: { value: 1, indeterminate: false },
|
||||
});
|
||||
} catch (error) {
|
||||
showToast(error.message);
|
||||
}
|
||||
};
|
||||
|
||||
export const updateNovelInfo = async (info, novelId) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE novels SET novelName = ?, novelSummary = ?, author = ?, genre = ?, status = ? WHERE novelId = ?',
|
||||
[
|
||||
info.novelName,
|
||||
info.novelSummary,
|
||||
info.author,
|
||||
info.genre,
|
||||
info.status,
|
||||
novelId,
|
||||
],
|
||||
(txObj, res) => {},
|
||||
(txObj, error) => {
|
||||
// console.log('Error ', error)
|
||||
},
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const pickCustomNovelCover = async novelId => {
|
||||
const image = await DocumentPicker.getDocumentAsync({ type: 'image/*' });
|
||||
|
||||
if (image.type === 'success' && image.uri) {
|
||||
const uri = 'file://' + image.uri;
|
||||
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE novels SET novelCover = ? WHERE novelId = ?',
|
||||
[uri, novelId],
|
||||
(txObj, res) => {},
|
||||
(txObj, error) => showToast(`Error: ${error}`),
|
||||
);
|
||||
});
|
||||
|
||||
return image.uri;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,361 @@
|
||||
import * as SQLite from 'expo-sqlite';
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
import * as DocumentPicker from 'expo-document-picker';
|
||||
import * as RNFS from 'react-native-fs';
|
||||
|
||||
import { fetchChapters, fetchImage, fetchNovel } from '@services/plugin/fetch';
|
||||
import { insertChapters } from './ChapterQueries';
|
||||
|
||||
import { showToast } from '@utils/showToast';
|
||||
import { txnErrorCallback } from '../utils/helpers';
|
||||
import { noop } from 'lodash-es';
|
||||
import { getString } from '@strings/translations';
|
||||
import { BackupNovel, NovelInfo } from '../types';
|
||||
import { SourceNovel } from '@plugins/types';
|
||||
import { NovelDownloadFolder } from '@utils/constants/download';
|
||||
|
||||
export const insertNovelAndChapters = async (
|
||||
pluginId: string,
|
||||
sourceNovel: SourceNovel,
|
||||
): Promise<number | undefined> => {
|
||||
const insertNovelQuery =
|
||||
'INSERT INTO Novel (url, pluginId, name, cover, summary, author, artist, status, genres) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)';
|
||||
const novelId: number | undefined = await new Promise(resolve => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
insertNovelQuery,
|
||||
[
|
||||
sourceNovel.url,
|
||||
pluginId,
|
||||
sourceNovel.name,
|
||||
sourceNovel.cover || null,
|
||||
sourceNovel.summary || null,
|
||||
sourceNovel.author || null,
|
||||
sourceNovel.artist || null,
|
||||
sourceNovel.status || null,
|
||||
sourceNovel.genres || null,
|
||||
],
|
||||
async (txObj, resultSet) => resolve(resultSet.insertId),
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
});
|
||||
if (novelId) {
|
||||
const promises = [insertChapters(novelId, sourceNovel.chapters)];
|
||||
if (sourceNovel.cover) {
|
||||
const novelDir = NovelDownloadFolder + '/' + pluginId + '/' + novelId;
|
||||
const novelCoverUri = 'file://' + novelDir + '/cover.png';
|
||||
promises.push(
|
||||
fetchImage(pluginId, sourceNovel.cover).then(base64 => {
|
||||
if (base64) {
|
||||
RNFS.mkdir(novelDir)
|
||||
.then(() => RNFS.writeFile(novelCoverUri, base64, 'base64'))
|
||||
.then(() => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql('UPDATE Novel SET cover = ? WHERE id = ?', [
|
||||
novelCoverUri,
|
||||
novelId,
|
||||
]);
|
||||
});
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
await Promise.all(promises);
|
||||
}
|
||||
return novelId;
|
||||
};
|
||||
|
||||
export const getAllNovels = async (): Promise<NovelInfo[]> => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql('SELECT * FROM Novel', [], (txObj, { rows }) =>
|
||||
resolve(rows._array),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const getNovel = async (novelUrl: string): Promise<NovelInfo | null> => {
|
||||
return new Promise(resolve =>
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'SELECT * FROM Novel WHERE url = ?',
|
||||
[novelUrl],
|
||||
(txObj, { rows }) => resolve(rows.item(0)),
|
||||
txnErrorCallback,
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
// if query is insert novel || add to library => add default category name for it
|
||||
// else remove all it's categories
|
||||
|
||||
export const switchNovelToLibrary = async (
|
||||
novelUrl: string,
|
||||
pluginId: string,
|
||||
) => {
|
||||
const novel = await getNovel(novelUrl);
|
||||
if (novel) {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE Novel SET inLibrary = ? WHERE id = ?',
|
||||
[Number(!novel.inLibrary), novel.id],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
if (novel.inLibrary) {
|
||||
tx.executeSql(
|
||||
'DELETE FROM NovelCategory WHERE novelId = ?',
|
||||
[novel.id],
|
||||
() => showToast(getString('browseScreen.removeFromLibrary')),
|
||||
txnErrorCallback,
|
||||
);
|
||||
} else {
|
||||
tx.executeSql(
|
||||
'INSERT INTO NovelCategory (novelId, categoryId) VALUES (?, (SELECT DISTINCT id FROM Category WHERE sort = 1))',
|
||||
[novel.id],
|
||||
() => showToast(getString('browseScreen.addedToLibrary')),
|
||||
txnErrorCallback,
|
||||
);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
const sourceNovel = await fetchNovel(pluginId, novelUrl);
|
||||
const novelId = await insertNovelAndChapters(pluginId, sourceNovel);
|
||||
if (novelId) {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE Novel SET inLibrary = 1 WHERE url = ?',
|
||||
[novelUrl],
|
||||
() => showToast(getString('browseScreen.addedToLibrary')),
|
||||
txnErrorCallback,
|
||||
);
|
||||
tx.executeSql(
|
||||
'INSERT INTO NovelCategory (novelId, categoryId) VALUES (?, (SELECT DISTINCT id FROM Category WHERE sort = 1))',
|
||||
[novelId],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// allow to delete local novels
|
||||
export const removeNovelsFromLibrary = (novelIds: Array<number>) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
`UPDATE Novel SET inLibrary = 0 WHERE id IN (${novelIds.join(', ')});`,
|
||||
);
|
||||
tx.executeSql(
|
||||
`DELETE FROM NovelCategory WHERE novelId IN (${novelIds.join(', ')});`,
|
||||
);
|
||||
});
|
||||
showToast('Removed from Library');
|
||||
};
|
||||
|
||||
export const getCachedNovels = (): Promise<NovelInfo[]> => {
|
||||
return new Promise(resolve => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'SELECT * FROM Novel WHERE inLibrary = 0',
|
||||
[],
|
||||
(txObj, { rows }) => resolve(rows._array as NovelInfo[]),
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
export const deleteCachedNovels = async () => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'DELETE FROM Novel WHERE inLibrary = 0',
|
||||
[],
|
||||
() => showToast('Cached novels deleted'),
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const restoreFromBackupQuery =
|
||||
'INSERT INTO Novel (url, name, pluginId, cover, summary, author, artist, status, genres, inLibrary) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
|
||||
|
||||
export const restoreLibrary = async (novel: NovelInfo) => {
|
||||
return new Promise(resolve => {
|
||||
db.transaction(tx =>
|
||||
tx.executeSql(
|
||||
restoreFromBackupQuery,
|
||||
[
|
||||
novel.url,
|
||||
novel.name,
|
||||
novel.pluginId,
|
||||
novel.cover || '',
|
||||
novel.summary || '',
|
||||
novel.author || '',
|
||||
novel.artist || '',
|
||||
novel.status || '',
|
||||
novel.genres || '',
|
||||
Number(novel.inLibrary),
|
||||
],
|
||||
async (txObj, { insertId }) => {
|
||||
if (!insertId) {
|
||||
return;
|
||||
}
|
||||
tx.executeSql(
|
||||
'INSERT INTO NovelCategory (novelId, categoryId) VALUES (?, (SELECT DISTINCT id FROM Category WHERE sort = 1))',
|
||||
[insertId],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
const chapters = await fetchChapters(novel.pluginId, novel.url);
|
||||
|
||||
if (chapters) {
|
||||
await insertChapters(insertId, chapters);
|
||||
resolve(insertId);
|
||||
}
|
||||
},
|
||||
txnErrorCallback,
|
||||
),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const updateNovelInfo = async (info: NovelInfo) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE Novel SET name = ?, cover = ?, url = ? , summary = ?, author = ?, artist = ?, genres = ?, status = ?, isLocal = ? WHERE id = ?',
|
||||
[
|
||||
info.name,
|
||||
info.cover || '',
|
||||
info.url,
|
||||
info.summary || '',
|
||||
info.author || '',
|
||||
info.artist || '',
|
||||
info.genres || '',
|
||||
info.status || '',
|
||||
Number(info.isLocal),
|
||||
info.id,
|
||||
],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const pickCustomNovelCover = async (novel: NovelInfo) => {
|
||||
const image = await DocumentPicker.getDocumentAsync({ type: 'image/*' });
|
||||
if (image.type === 'success' && image.uri) {
|
||||
const novelDir =
|
||||
NovelDownloadFolder + '/' + novel.pluginId + '/' + novel.id;
|
||||
let novelCoverUri = 'file://' + novelDir + '/cover.png';
|
||||
RNFS.copyFile(image.uri, novelCoverUri);
|
||||
novelCoverUri += '?' + Date.now();
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE Novel SET cover = ? WHERE id = ?',
|
||||
[novelCoverUri, novel.id],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
return novelCoverUri;
|
||||
}
|
||||
};
|
||||
|
||||
export const updateNovelCategoryById = async (
|
||||
novelId: number,
|
||||
categoryIds: number[],
|
||||
) => {
|
||||
db.transaction(tx => {
|
||||
categoryIds.forEach(categoryId => {
|
||||
tx.executeSql(
|
||||
'INSERT INTO NovelCategory (novelId, categoryId) VALUES (?, ?)',
|
||||
[novelId, categoryId],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const updateNovelCategories = async (
|
||||
novelIds: number[],
|
||||
categoryIds: number[],
|
||||
): Promise<void> => {
|
||||
let queries: string[] = [];
|
||||
// not allow others have local id;
|
||||
categoryIds = categoryIds.filter(id => id !== 2);
|
||||
queries.push(
|
||||
`DELETE FROM NovelCategory WHERE novelId IN (${novelIds.join(
|
||||
',',
|
||||
)}) AND categoryId != 2`,
|
||||
);
|
||||
novelIds.forEach(novelId => {
|
||||
categoryIds.forEach(categoryId =>
|
||||
queries.push(
|
||||
`INSERT INTO NovelCategory (novelId, categoryId) VALUES (${novelId}, ${categoryId})`,
|
||||
),
|
||||
);
|
||||
});
|
||||
db.transaction(tx => {
|
||||
queries.forEach(query => {
|
||||
tx.executeSql(query);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const _restoreNovelAndChapters = (novel: BackupNovel) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql('DELETE FROM Novel WHERE id = ?', [novel.id]);
|
||||
tx.executeSql(
|
||||
`INSERT INTO
|
||||
Novel (
|
||||
id, url, pluginId, name, cover, summary,
|
||||
author, artist, status, genres, inLibrary, isLocal
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
[
|
||||
novel.id,
|
||||
novel.url,
|
||||
novel.pluginId,
|
||||
novel.name,
|
||||
novel.cover || null,
|
||||
novel.summary || null,
|
||||
novel.author || null,
|
||||
novel.artist || null,
|
||||
novel.status || null,
|
||||
novel.genres || null,
|
||||
Number(novel.inLibrary),
|
||||
Number(novel.isLocal),
|
||||
],
|
||||
);
|
||||
for (const chapter of novel.chapters) {
|
||||
tx.executeSql(
|
||||
`INSERT INTO
|
||||
Chapter (
|
||||
id, novelId, url, name, releaseTime, bookmark,
|
||||
unread, readTime, isDownloaded, updatedTime
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`,
|
||||
[
|
||||
chapter.id,
|
||||
chapter.novelId,
|
||||
chapter.url,
|
||||
chapter.name,
|
||||
chapter.releaseTime || null,
|
||||
Number(chapter.bookmark),
|
||||
Number(chapter.unread),
|
||||
chapter.readTime,
|
||||
Number(chapter.isDownloaded),
|
||||
chapter.updatedTime,
|
||||
],
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,205 +0,0 @@
|
||||
import { noop, xor } from 'lodash-es';
|
||||
|
||||
import * as SQLite from 'expo-sqlite';
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
import { txnErrorCallback } from '../utils/helpers';
|
||||
import { LibraryNovelInfo } from '../types';
|
||||
import { fetchNovel } from '../../services/Source/source';
|
||||
import { showToast } from '@hooks/showToast';
|
||||
import { getString } from '@strings/translations';
|
||||
import { checkNovelInCache } from './NovelQueries';
|
||||
|
||||
export const getCategoryNovelsFromDb = async (
|
||||
categoryId: number,
|
||||
onlyOngoingNovels?: boolean,
|
||||
): Promise<LibraryNovelInfo[]> => {
|
||||
let query = `
|
||||
SELECT
|
||||
*
|
||||
FROM
|
||||
novels
|
||||
WHERE (
|
||||
categoryIds LIKE '[${categoryId}]'
|
||||
OR
|
||||
categoryIds LIKE '[${categoryId},%'
|
||||
OR
|
||||
categoryIds LIKE '%,${categoryId}]'
|
||||
OR
|
||||
categoryIds LIKE '%,${categoryId},%'
|
||||
)
|
||||
AND
|
||||
followed = 1
|
||||
`;
|
||||
|
||||
if (onlyOngoingNovels) {
|
||||
query += ' AND status NOT LIKE "Completed"';
|
||||
}
|
||||
|
||||
return new Promise(resolve => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
query,
|
||||
undefined,
|
||||
(txObj, { rows }) => resolve((rows as any)._array),
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const resetCategoryIdsToDefault = async (deletedCategoryId: number) => {
|
||||
const categoryNovels = await getCategoryNovelsFromDb(deletedCategoryId);
|
||||
|
||||
db.transaction(tx => {
|
||||
categoryNovels.forEach(novel => {
|
||||
let categoryIds = xor(JSON.parse(novel.categoryIds), [deletedCategoryId]);
|
||||
|
||||
categoryIds = categoryIds.length ? categoryIds : [1];
|
||||
|
||||
tx.executeSql('UPDATE novels SET categoryIds = ? WHERE novelId = ?', [
|
||||
JSON.stringify(categoryIds),
|
||||
novel.novelId,
|
||||
]);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const insertNovelInLibrary = async (
|
||||
sourceId: number,
|
||||
novelUrl: string,
|
||||
inLibrary: boolean,
|
||||
defaultCategoryId: number,
|
||||
) => {
|
||||
if (inLibrary) {
|
||||
showToast(getString('browseScreen.removeFromLibrary'));
|
||||
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
`
|
||||
UPDATE novels SET
|
||||
followed = 0
|
||||
WHERE
|
||||
sourceId = ?
|
||||
AND
|
||||
novelUrl = ?
|
||||
`,
|
||||
[sourceId, novelUrl],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
} else {
|
||||
showToast(getString('browseScreen.addedToLibrary'));
|
||||
|
||||
const novelSavedInDb = await checkNovelInCache(novelUrl);
|
||||
|
||||
if (novelSavedInDb) {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
`
|
||||
UPDATE novels SET
|
||||
followed = 1
|
||||
WHERE
|
||||
sourceId = ?
|
||||
AND
|
||||
novelUrl = ?
|
||||
`,
|
||||
[sourceId, novelUrl],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const novel = await fetchNovel(sourceId, novelUrl);
|
||||
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
`
|
||||
INSERT INTO novels
|
||||
(
|
||||
novelUrl,
|
||||
sourceUrl,
|
||||
sourceId,
|
||||
source,
|
||||
novelName,
|
||||
novelCover,
|
||||
novelSummary,
|
||||
author,
|
||||
artist,
|
||||
status,
|
||||
genre,
|
||||
followed,
|
||||
categoryIds
|
||||
)
|
||||
VALUES
|
||||
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)`,
|
||||
[
|
||||
novel.novelUrl,
|
||||
novel.sourceUrl,
|
||||
novel.sourceId,
|
||||
novel.source,
|
||||
novel.novelName,
|
||||
novel.novelCover,
|
||||
novel.novelSummary,
|
||||
novel.author,
|
||||
novel.artist,
|
||||
novel.status,
|
||||
novel.genre,
|
||||
JSON.stringify([defaultCategoryId]),
|
||||
],
|
||||
(txObj, { insertId }) => {
|
||||
novel.chapters?.map(chapter => {
|
||||
tx.executeSql(
|
||||
`
|
||||
INSERT INTO chapters
|
||||
(chapterUrl, chapterName, releaseDate, novelId)
|
||||
VALUES
|
||||
(?, ?, ?, ?)`,
|
||||
[
|
||||
chapter.chapterUrl,
|
||||
chapter.chapterName,
|
||||
chapter.releaseDate,
|
||||
insertId,
|
||||
],
|
||||
);
|
||||
});
|
||||
},
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const updateNovelCategoryById = async (
|
||||
novelId: number,
|
||||
categoryIds: number[],
|
||||
) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
'UPDATE novels SET categoryIds = ? WHERE novelId = ?',
|
||||
[JSON.stringify(categoryIds.length ? categoryIds : [1]), novelId],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const updateNovelCategoryByIds = async (
|
||||
novelIds: number[],
|
||||
categoryIds: number[],
|
||||
) => {
|
||||
db.transaction(tx => {
|
||||
novelIds.map(novelId =>
|
||||
tx.executeSql(
|
||||
'UPDATE novels SET categoryIds = ? WHERE novelId = ?',
|
||||
[JSON.stringify(categoryIds.length ? categoryIds : [1]), novelId],
|
||||
noop,
|
||||
txnErrorCallback,
|
||||
),
|
||||
);
|
||||
});
|
||||
};
|
||||
@@ -6,53 +6,53 @@ import { txnErrorCallback } from '../utils/helpers';
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
const getLibraryStatsQuery = `
|
||||
SELECT COUNT(*) as novelsCount, COUNT(DISTINCT sourceId) as sourcesCount
|
||||
FROM novels
|
||||
WHERE novels.followed = 1
|
||||
SELECT COUNT(*) as novelsCount, COUNT(DISTINCT pluginId) as sourcesCount
|
||||
FROM Novel
|
||||
WHERE inLibrary = 1
|
||||
`;
|
||||
|
||||
const getChaptersReadCountQuery = `
|
||||
SELECT COUNT(*) as chaptersRead
|
||||
FROM chapters
|
||||
JOIN novels
|
||||
ON chapters.novelId = novels.novelId
|
||||
WHERE chapters.read = 1 AND novels.followed = 1
|
||||
FROM Chapter
|
||||
JOIN Novel
|
||||
ON Chapter.novelId = Novel.id
|
||||
WHERE Chapter.unread = 0 AND Novel.inLibrary = 1
|
||||
`;
|
||||
|
||||
const getChaptersTotalCountQuery = `
|
||||
SELECT COUNT(*) as chaptersCount
|
||||
FROM chapters
|
||||
JOIN novels
|
||||
ON chapters.novelId = novels.novelId
|
||||
WHERE novels.followed = 1
|
||||
FROM Chapter
|
||||
JOIN Novel
|
||||
ON Chapter.novelId = Novel.id
|
||||
WHERE Novel.inLibrary = 1
|
||||
`;
|
||||
|
||||
const getChaptersUnreadCountQuery = `
|
||||
SELECT COUNT(*) as chaptersUnread
|
||||
FROM chapters
|
||||
JOIN novels
|
||||
ON chapters.novelId = novels.novelId
|
||||
WHERE chapters.read = 0 AND novels.followed = 1
|
||||
FROM Chapter
|
||||
JOIN Novel
|
||||
ON Chapter.novelId = Novel.id
|
||||
WHERE Chapter.unread = 1 AND Novel.inLibrary = 1
|
||||
`;
|
||||
|
||||
const getChaptersDownloadedCountQuery = `
|
||||
SELECT COUNT(*) as chaptersDownloaded
|
||||
FROM chapters
|
||||
JOIN novels
|
||||
ON chapters.novelId = novels.novelId
|
||||
WHERE chapters.downloaded = 1 AND novels.followed = 1
|
||||
FROM Chapter
|
||||
JOIN Novel
|
||||
ON Chapter.novelId = Novel.id
|
||||
WHERE Chapter.isDownloaded = 1 AND Novel.inLibrary = 1
|
||||
`;
|
||||
|
||||
const getNovelGenresQuery = `
|
||||
SELECT genre
|
||||
FROM novels
|
||||
WHERE novels.followed = 1
|
||||
SELECT genres
|
||||
FROM Novel
|
||||
WHERE Novel.inLibrary = 1
|
||||
`;
|
||||
|
||||
const getNovelStatusQuery = `
|
||||
SELECT status
|
||||
FROM novels
|
||||
WHERE novels.followed = 1
|
||||
FROM Novel
|
||||
WHERE Novel.inLibrary = 1
|
||||
`;
|
||||
|
||||
export const getLibraryStatsFromDb = async (): Promise<LibraryStats> => {
|
||||
@@ -61,8 +61,8 @@ export const getLibraryStatsFromDb = async (): Promise<LibraryStats> => {
|
||||
tx.executeSql(
|
||||
getLibraryStatsQuery,
|
||||
undefined,
|
||||
(txObj, { rows: { _array } }) => {
|
||||
resolve(_array[0]);
|
||||
(txObj, { rows }) => {
|
||||
resolve((rows as any)._array[0]);
|
||||
},
|
||||
txnErrorCallback,
|
||||
);
|
||||
@@ -76,8 +76,8 @@ export const getChaptersTotalCountFromDb = async (): Promise<LibraryStats> => {
|
||||
tx.executeSql(
|
||||
getChaptersTotalCountQuery,
|
||||
undefined,
|
||||
(txObj, { rows: { _array } }) => {
|
||||
resolve(_array[0]);
|
||||
(txObj, { rows }) => {
|
||||
resolve((rows as any)._array[0]);
|
||||
},
|
||||
txnErrorCallback,
|
||||
);
|
||||
@@ -91,8 +91,8 @@ export const getChaptersReadCountFromDb = async (): Promise<LibraryStats> => {
|
||||
tx.executeSql(
|
||||
getChaptersReadCountQuery,
|
||||
undefined,
|
||||
(txObj, { rows: { _array } }) => {
|
||||
resolve(_array[0]);
|
||||
(txObj, { rows }) => {
|
||||
resolve((rows as any)._array[0]);
|
||||
},
|
||||
txnErrorCallback,
|
||||
);
|
||||
@@ -106,8 +106,8 @@ export const getChaptersUnreadCountFromDb = async (): Promise<LibraryStats> => {
|
||||
tx.executeSql(
|
||||
getChaptersUnreadCountQuery,
|
||||
undefined,
|
||||
(txObj, { rows: { _array } }) => {
|
||||
resolve(_array[0]);
|
||||
(txObj, { rows }) => {
|
||||
resolve((rows as any)._array[0]);
|
||||
},
|
||||
txnErrorCallback,
|
||||
);
|
||||
@@ -122,8 +122,8 @@ export const getChaptersDownloadedCountFromDb =
|
||||
tx.executeSql(
|
||||
getChaptersDownloadedCountQuery,
|
||||
undefined,
|
||||
(txObj, { rows: { _array } }) => {
|
||||
resolve(_array[0]);
|
||||
(txObj, { rows }) => {
|
||||
resolve((rows as any)._array[0]);
|
||||
},
|
||||
txnErrorCallback,
|
||||
);
|
||||
@@ -137,11 +137,11 @@ export const getNovelGenresFromDb = async (): Promise<LibraryStats> => {
|
||||
tx.executeSql(
|
||||
getNovelGenresQuery,
|
||||
undefined,
|
||||
(txObj, { rows: { _array } }) => {
|
||||
(txObj, { rows }) => {
|
||||
let genres: string[] = [];
|
||||
|
||||
_array.forEach((item: { genre: string }) => {
|
||||
const novelGenres = item.genre?.split(/\s*,\s*/);
|
||||
(rows as any)._array.forEach((item: { genres: string }) => {
|
||||
const novelGenres = item.genres?.split(/\s*,\s*/);
|
||||
|
||||
if (novelGenres?.length) {
|
||||
genres.push(...novelGenres);
|
||||
@@ -162,10 +162,10 @@ export const getNovelStatusFromDb = async (): Promise<LibraryStats> => {
|
||||
tx.executeSql(
|
||||
getNovelStatusQuery,
|
||||
undefined,
|
||||
(txObj, { rows: { _array } }) => {
|
||||
(txObj, { rows }) => {
|
||||
let status: string[] = [];
|
||||
|
||||
_array.forEach((item: { status: string }) => {
|
||||
(rows as any)._array.forEach((item: { status: string }) => {
|
||||
status.push(item.status);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
|
||||
import * as SQLite from 'expo-sqlite';
|
||||
import { showToast } from '../../hooks/showToast';
|
||||
import { Update } from '../types';
|
||||
|
||||
const db = SQLite.openDatabase('lnreader.db');
|
||||
|
||||
const getUpdatesFromDbQuery = `
|
||||
SELECT
|
||||
chapters.chapterId,
|
||||
chapters.read,
|
||||
chapters.downloaded,
|
||||
chapters.chapterUrl,
|
||||
chapters.chapterName,
|
||||
chapters.bookmark,
|
||||
chapters.releaseDate,
|
||||
novels.novelUrl,
|
||||
novels.novelId,
|
||||
novels.novelCover,
|
||||
novels.novelName,
|
||||
novels.sourceId,
|
||||
updates.updateTime,
|
||||
updates.updateId
|
||||
FROM
|
||||
updates
|
||||
JOIN
|
||||
chapters
|
||||
ON
|
||||
updates.chapterId = chapters.chapterId
|
||||
JOIN
|
||||
novels
|
||||
ON
|
||||
updates.novelId = novels.novelId
|
||||
WHERE
|
||||
date(updates.updateTime) > date('now','-3 months')
|
||||
ORDER BY
|
||||
updates.updateTime DESC, chapters.chapterName DESC, chapters.releaseDate DESC
|
||||
`;
|
||||
|
||||
export const getUpdatesFromDb = async (): Promise<Update[]> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
getUpdatesFromDbQuery,
|
||||
[],
|
||||
(txObj, { rows: { _array } }) => resolve(_array),
|
||||
(txObj, error) => reject(error),
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const insertChapterUpdateQuery = `
|
||||
INSERT OR IGNORE INTO
|
||||
updates
|
||||
(chapterId, novelId, updateTime)
|
||||
VALUES
|
||||
(?, ?, (datetime('now','localtime')))`;
|
||||
|
||||
export const insertChapterUpdate = async (
|
||||
chapterId: number,
|
||||
novelId: number,
|
||||
) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
insertChapterUpdateQuery,
|
||||
[chapterId, novelId],
|
||||
(txOBJ, res) => {},
|
||||
(txOBJ, error) => showToast(error.message),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const deleteUpdateFromDbQuery = `
|
||||
DELETE FROM
|
||||
updates
|
||||
WHERE
|
||||
novelId = ?`;
|
||||
|
||||
export const deleteUpdateFromDb = (novelId: number) => {
|
||||
db.transaction(tx => {
|
||||
tx.executeSql(
|
||||
deleteUpdateFromDbQuery,
|
||||
[novelId],
|
||||
(txObj, res) => {},
|
||||
(txObj, error) => showToast(error.message),
|
||||
);
|
||||
});
|
||||
};
|
||||
const clearUpdatesQuery = `
|
||||
DELETE FROM updates;
|
||||
VACCUM;
|
||||
`;
|
||||
|
||||
export const clearUpdates = () =>
|
||||
db.transaction(tx =>
|
||||
tx.executeSql(
|
||||
clearUpdatesQuery,
|
||||
[],
|
||||
() => showToast('Updates cleared.'),
|
||||
(txObj, error) => showToast(error.message),
|
||||
),
|
||||
);
|
||||
@@ -1,17 +1,20 @@
|
||||
export const createCategoriesTableQuery = `
|
||||
CREATE TABLE IF NOT EXISTS categories(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
lastUpdatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
sort INTEGER DEFAULT NULL
|
||||
)
|
||||
`;
|
||||
CREATE TABLE IF NOT EXISTS Category (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
sort INTEGER
|
||||
);
|
||||
`;
|
||||
|
||||
export const createDefaultCategoryQuery =
|
||||
'INSERT INTO categories (id, name) VALUES (1, "Default");';
|
||||
export const createCategoryTriggerQuery = `
|
||||
CREATE TRIGGER IF NOT EXISTS add_category AFTER INSERT ON Category
|
||||
BEGIN
|
||||
UPDATE Category SET sort = (SELECT IFNULL(sort, new.id)) WHERE id = new.id;
|
||||
END;
|
||||
`;
|
||||
|
||||
export const createCategorydIndexQuery =
|
||||
'CREATE INDEX IF NOT EXISTS categoryIdIndex ON categories(id)';
|
||||
export const createCategoryDefaultQuery =
|
||||
'INSERT OR IGNORE INTO Category (id, name, sort) VALUES (1, "Default", 1)';
|
||||
|
||||
export const addCategorySortColumnQuery =
|
||||
'ALTER TABLE categories ADD COLUMN sort INTEGER DEFAULT NULL';
|
||||
export const createCategoryLocalQuery =
|
||||
'INSERT OR IGNORE INTO Category (id, name, sort) VALUES (2, "Local", 2)';
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
const createChapterTableQuery = `
|
||||
CREATE TABLE IF NOT EXISTS chapters(
|
||||
chapterId INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
chapterUrl TEXT,
|
||||
novelId INTEGER NOT NULL,
|
||||
chapterName TEXT NOT NULL,
|
||||
releaseDate TEXT,
|
||||
bookmark BOOLEAN NOT NULL DEFAULT 0,
|
||||
\`read\` INTEGER NOT NULL DEFAULT 0,
|
||||
downloaded INTEGER NOT NULL DEFAULT 0,
|
||||
UNIQUE(novelId, chapterUrl),
|
||||
FOREIGN KEY (novelId) REFERENCES novels(novelId)
|
||||
ON DELETE CASCADE
|
||||
)`;
|
||||
|
||||
const createNovelIdIndexQuery = `
|
||||
CREATE INDEX
|
||||
IF NOT EXISTS
|
||||
chapterNovelIdIndex ON chapters(novelId)`;
|
||||
|
||||
const createUnreadChaptersIndexQuery = `
|
||||
CREATE INDEX
|
||||
IF NOT EXISTS
|
||||
chapterUnreadByNovelIndex ON chapters(novelId, \`read\`) WHERE \`read\`=0`;
|
||||
|
||||
export {
|
||||
createChapterTableQuery,
|
||||
createNovelIdIndexQuery,
|
||||
createUnreadChaptersIndexQuery,
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
export const createChapterTableQuery = `
|
||||
CREATE TABLE IF NOT EXISTS Chapter (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
novelId INTEGER NOT NULL,
|
||||
url TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
releaseTime TEXT,
|
||||
bookmark INTEGER DEFAULT 0,
|
||||
unread INTEGER DEFAULT 1,
|
||||
readTime TEXT,
|
||||
isDownloaded INTEGER DEFAULT 0,
|
||||
updatedTime TEXT,
|
||||
chapterNumber REAL NULL,
|
||||
FOREIGN KEY (novelId) REFERENCES Novel(id) ON DELETE CASCADE
|
||||
)
|
||||
`;
|
||||
|
||||
export const createChapterNovelIdIndexQuery = `
|
||||
CREATE INDEX
|
||||
IF NOT EXISTS
|
||||
chapterNovelIdIndex ON Chapter(novelId)
|
||||
`;
|
||||
@@ -1,12 +0,0 @@
|
||||
export const createDownloadTableQuery = `
|
||||
CREATE TABLE IF NOT EXISTS downloads(
|
||||
downloadId INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
downloadChapterId INTEGER NOT NULL,
|
||||
chapterName TEXT,
|
||||
chapterText TEXT,
|
||||
FOREIGN KEY (downloadChapterId) REFERENCES chapters(chapterId) ON DELETE CASCADE
|
||||
)
|
||||
`;
|
||||
|
||||
export const createDownloadIdIndex =
|
||||
'CREATE INDEX IF NOT EXISTS downloadChapterIdIndex ON downloads(downloadChapterId)';
|
||||
@@ -1,12 +0,0 @@
|
||||
export const createHistoryTableQuery = `
|
||||
CREATE TABLE IF NOT EXISTS history(
|
||||
historyId INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
historyChapterId INTEGER NOT NULL UNIQUE,
|
||||
historyNovelId INTEGER NOT NULL,
|
||||
historyTimeRead DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (historyChapterId) REFERENCES chapters(chapterId)
|
||||
ON DELETE CASCADE
|
||||
)`;
|
||||
|
||||
export const createChapterIdIndexQuery =
|
||||
'CREATE INDEX IF NOT EXISTS historyChapterIdIndex ON history(historyChapterId)';
|
||||
@@ -0,0 +1,10 @@
|
||||
export const createNovelCategoryTableQuery = `
|
||||
CREATE TABLE IF NOT EXISTS NovelCategory (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
novelId INTEGER NOT NULL,
|
||||
categoryId INTEGER NOT NULL,
|
||||
UNIQUE(novelId, categoryId),
|
||||
FOREIGN KEY (novelId) REFERENCES Novel(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (categoryId) REFERENCES Category(id) ON DELETE CASCADE
|
||||
);
|
||||
`;
|
||||
@@ -1,27 +0,0 @@
|
||||
export const createNovelTableQuery = `
|
||||
CREATE TABLE IF NOT EXISTS novels(
|
||||
novelId INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
novelUrl TEXT NOT NULL,
|
||||
sourceUrl TEXT UNIQUE NOT NULL,
|
||||
sourceId INTEGER NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
novelName TEXT NOT NULL,
|
||||
novelCover TEXT,
|
||||
novelSummary TEXT,
|
||||
author TEXT,
|
||||
artist TEXT,
|
||||
status TEXT,
|
||||
genre TEXT,
|
||||
followed INTEGER DEFAULT 0,
|
||||
unread INTEGER DEFAULT 1,
|
||||
categoryIds TEXT DEFAULT "[1]"
|
||||
)`;
|
||||
|
||||
export const createUrlIndexQuery =
|
||||
'CREATE INDEX IF NOT EXISTS novelUrlIndex ON novels(novelUrl)';
|
||||
|
||||
export const createLibraryIndexQuery =
|
||||
'CREATE INDEX IF NOT EXISTS novelFollowedIndex ON novels(followed)';
|
||||
|
||||
export const addCategoryColumnQuery =
|
||||
'ALTER TABLE novels ADD COLUMN categoryIds TEXT DEFAULT "[1]"';
|
||||
@@ -0,0 +1,16 @@
|
||||
export const createNovelTableQuery = `
|
||||
CREATE TABLE IF NOT EXISTS Novel (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
url TEXT NOT NULL UNIQUE,
|
||||
pluginId TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
cover TEXT,
|
||||
summary TEXT,
|
||||
author TEXT,
|
||||
artist TEXT,
|
||||
status TEXT Default 'Unknown',
|
||||
genres TEXT,
|
||||
inLibrary INTEGER DEFAULT 0,
|
||||
isLocal INTERGER DEFAULT 0
|
||||
);
|
||||
`;
|
||||