Compare commits

..

90 Commits

Author SHA1 Message Date
Rajarshee Chatterjee e8fe0fdc83 Release v1.1.18 2023-10-09 09:50:11 +05:30
Isaac H 5df5a2ccd2 fix: EPUB Parser (#795)
* Move changes to master branch

* Fixed errors stemming from improper move

* Add EPub to library

* Extract everything in root folder, don't create subfolders

* made changes to epubparser.py

* changed json metadata file and added some safeguards for different epub formats

* Correctly read metadata and convert relative paths

* Corrected path for EPUB3

* fixed cover not showing up

* Get missing chapters names

* fixed conflict with export to epub

---------

Co-authored-by: Danisty <danisty.nori@gmail.com>
2023-10-09 09:44:22 +05:30
Rider21 3f6bcb2a8f fix(source): Ficbook (#793)
* Update ficbook.js

* sorted
2023-10-07 13:20:46 +05:30
K1ngfish3r f8fef4cb2c fix(source): Novel Updates, FastNovel & Arnovel (#782)
* inoveltranslation update

* Oops

* fix eslint check?

* update fastnovel

* update for arnovel

* xperimental

* novel.sourceId
2023-10-06 07:52:20 +05:30
Rajarshee Chatterjee c15144f633 fix(source): Update HizoManga Domain (Closes LNReader/lnreader-sources#590) 2023-09-22 08:00:23 +05:30
Rajarshee Chatterjee a0096cdacb fix(source): Bypass Cloudflare in Readwn (Closes LNReader/lnreader-sources#584) 2023-09-22 07:59:43 +05:30
Rajarshee Chatterjee 7afe230ec3 fix: Crash in EPUB Modal 2023-09-22 07:47:29 +05:30
Rider21 4a49f32823 feat(source): Add Смаколики, LitSpace (#778)
* add smakolykytl

* Update smakolykytl.ts

* fix

* LitSpace

* fix

* fix renovels

* Update renovels.js
2023-09-22 07:19:21 +05:30
Rajarshee Chatterjee 925855a0dd fix(source): Bypass Cloudflare in NovelPub 2023-09-15 07:45:06 +05:30
Nick Ignoffo 6f4fdd22dd Quick novel screen polishing pass (#772)
* Animate description expansion

* Add animated (opacity) background to appbar

* Refresh control colors should match rest of app

* Fix chapter download not updating when deleting all (Closes #748)

Also closes the menu when you delete all chapters
2023-09-03 10:26:51 +05:30
Rajarshee Chatterjee 918edc4362 [skip ci] Update Issue Templates 2023-09-02 19:13:22 +05:30
Rajarshee Chatterjee e955069190 fix: Volume Button Scroll on Next Chapter (Closes #719) 2023-09-02 17:17:05 +05:30
Rajarshee Chatterjee 5037fa693a fix(source): Novel Buddy 2023-09-02 13:52:47 +05:30
Rajarshee Chatterjee 527289372b feat(source): [LTNovel] Support Latest Novels
Closes LNReader/lnreader-sources#431
2023-09-02 12:52:32 +05:30
Rajarshee Chatterjee c1cc32bcf1 fix(source): NovelTranslate (Closes LNReader/lnreader-sources#580) 2023-09-02 12:00:57 +05:30
Rajarshee Chatterjee 3b2ee3d78b refactor: Custom CSS/JS Modal (#705)
* refactor: Custom CSS/JS Modal

* Close Modal on Selecting a File
2023-09-02 11:06:07 +05:30
Rajarshee Chatterjee 929b183478 fix: Limit Custom CSS/JS Preview to 3 Lines (Closes #668) 2023-09-02 10:45:23 +05:30
Isaac H f53b0eac80 feat: Local EPUB Support (#754)
Closes #38 

* Move changes to master branch

* Fixed errors stemming from improper move

* Add EPub to library

* Extract everything in root folder, don't create subfolders

* made changes to epubparser.py

* changed json metadata file and added some safeguards for different epub formats

* Correctly read metadata and convert relative paths

* Corrected path for EPUB3

* fixed cover not showing up

* Get missing chapters names

---------

Co-authored-by: Danisty <danisty.nori@gmail.com>
2023-09-02 10:25:12 +05:30
Rajarshee Chatterjee 8258059adb Wrap Stats Cards (Closes #749) 2023-08-19 11:22:30 +05:30
Rajarshee Chatterjee 66c9b80374 fix(source): FastNovel (Closes LNReader/lnreader-sources#558) 2023-08-19 10:55:59 +05:30
Rajarshee Chatterjee 490c9ee495 Show Unread Chapters in Reader Drawer (Closes #732) 2023-08-19 10:13:59 +05:30
Rajarshee Chatterjee 4cb6251409 Tweak Chapter Card (Closes #725) 2023-08-19 10:10:55 +05:30
Skoppy2 6349c26a49 fix(Source): Update Novelmt URL (#746)
* Done work modifing novelmt

* build.yml
2023-08-19 09:47:45 +05:30
Rajarshee Chatterjee f7f02dc179 fix: Always Save EPUB Options (Close #744) 2023-08-19 09:46:34 +05:30
Rajarshee Chatterjee 28b65e35d2 Refactor App Update Checker 2023-08-17 22:24:09 +05:30
Rajarshee Chatterjee be2cca88af Minor Fixes 2023-08-17 21:19:02 +05:30
Rajarshee Chatterjee 0c42e93238 fix: Restore Backup Getting
Closes #422
Closes #720
2023-08-17 21:03:12 +05:30
Rajarshee Chatterjee 895f7c7fbf Add Missing Dependencies 2023-08-17 18:43:14 +05:30
Rajarshee Chatterjee de816e5de4 Add "Export to EPUB" Back (#738)
* Add "Export to EPUB" Back

* Cleanup
2023-08-17 14:43:44 +05:30
Rajarshee Chatterjee fbc128c786 Refactor NavigationUtils 2023-08-17 08:40:55 +05:30
1-minute-to-midnight 8e0ec4ccf8 fix(source): Update Readwn URL (#726) 2023-08-08 00:36:25 +05:30
K1ngfish3r e092ad9ba8 fix(source): Update Kolnovel and Agitoon (#715)
* kolnovel fix draft

* kolnovel fix draft v2

* cleanup

* fix Agitoon landing page
2023-08-03 15:59:06 +05:30
Rajarshee Chatterjee 5b8cfebe3d Revert "Export to EPUB" and Release v1.1.17 (#703)
* Revert "feat: EPUB Export (#646)"

This reverts commit c0b4610910.

* Revert "Export to EPUB"

* Release v1.1.17

* Revert React Native to 0.69.9

* Fix Update Checker
2023-08-03 07:43:26 +05:30
alistair3149 e760bd1a9b fix(source): add all pages in the same chapter for Linovelib (#722) 2023-08-02 23:31:14 +05:30
danisty d260eb1b5e Performance fixes, general fixes and addition of features (#723)
* fix: Fixed images proxied through Cloudflare not loading

* feat: Add utility to render images from Cloudflare proxied sites

* feat(source): Add NOVA (Spanish source)

* fix(source): NovelasLigera display of images and improved display of chapters text

* fix(source): NovelasLigera properly parse metadata

* fix(source): YuukiTls display of novels

* fix(source): TuNovelaLigera missing Cloudflare bypass and not properly getting covers

* fix(source): Other significant changes related to the request of popular novels from sources with no more than 1 page

* fix(source): NOVA not added to source manager

* fix: Remove loading Novel shimmer effect item when nothing is loading

* fix: Properly update chapters and metadata of novels that aren't saved in the local library

* fix: sanitizer doing unnecessary parsing which may add noticable delay to chapter loading

* refac: Add <center> tag to the sanitizer allowed tags

* fix: sanitizer being called each re-render of ReaderScreen plus unnecessary re-render of the WebView

* fix: memoized chapter html conversion to text for TTS, operation can be expensive

* refactor: Moved cloudflareImagesBypass to sources/helpers and fixed NOVA novels summary format
2023-08-02 23:30:44 +05:30
alistair3149 d59f95f13a fix(source): bypass image CDN in Linovelib (#716)
* fix(source): bypass image CDN in Linovelib

* fix(source): also check for src attribute in img in Linovelib
2023-07-31 09:07:32 +05:30
alistair3149 0d9da26eff fix(source): fix various lazyload issue with Linovelib (#714)
* fix(source): load lazyloaded images in Linovelib

* fix(source): recover original text in Linovelib
2023-07-29 20:53:51 +05:30
alistair3149 a769110c70 fix(source): fix incorrect property name (#713) 2023-07-28 10:35:47 +05:30
alistair3149 71ea318503 refactor(source): Use fetchHtml for Linovelib (#710)
* refactor(source): Use fetchHtml for Linovelib

* Update src/sources/ch/linovelib.js

Co-authored-by: Rajarshee Chatterjee <rajarshee.adm@gmail.com>

---------

Co-authored-by: Rajarshee Chatterjee <rajarshee.adm@gmail.com>
2023-07-28 09:46:12 +05:30
alistair3149 59d5f08c83 feat(source): Add Linovelib (#709)
* feat(source): Add Linovelib

* fix(source): use fetchHtml for searchNovels in Linovelib
2023-07-27 09:34:00 +05:30
Rajarshee Chatterjee 36230cebea fix(source): Update Ranobes URL 2023-07-27 08:34:14 +05:30
Rajarshee Chatterjee cbee29ea85 fix: Highlight on Novel Selection 2023-07-26 07:53:20 +05:30
Rhino 9b5a44fe59 fix(source): Update Ranobes URL (#690)
Update Ranobes URL
2023-07-16 17:29:21 +05:30
Rajarshee Chatterjee 9f87edaa7c build: Fix Artifact Name 2023-07-15 14:36:33 +05:30
Rajarshee Chatterjee e976c9793c Release v1.1.16 2023-07-15 13:21:46 +05:30
Rajarshee Chatterjee a9a0a5ad83 chore: Update translations (#625)
* New translations strings.json (Romanian)
[ci skip]

* New translations strings.json (French)
[ci skip]

* New translations strings.json (Spanish)
[ci skip]

* New translations strings.json (Afrikaans)
[ci skip]

* New translations strings.json (Arabic)
[ci skip]

* New translations strings.json (Catalan)
[ci skip]

* New translations strings.json (Czech)
[ci skip]

* New translations strings.json (Danish)
[ci skip]

* New translations strings.json (German)
[ci skip]

* New translations strings.json (Greek)
[ci skip]

* New translations strings.json (Finnish)
[ci skip]

* New translations strings.json (Hebrew)
[ci skip]

* New translations strings.json (Hungarian)
[ci skip]

* New translations strings.json (Italian)
[ci skip]

* New translations strings.json (Japanese)
[ci skip]

* New translations strings.json (Korean)
[ci skip]

* New translations strings.json (Dutch)
[ci skip]

* New translations strings.json (Norwegian)
[ci skip]

* New translations strings.json (Polish)
[ci skip]

* New translations strings.json (Portuguese)
[ci skip]

* New translations strings.json (Russian)
[ci skip]

* New translations strings.json (Albanian)
[ci skip]

* New translations strings.json (Serbian (Cyrillic))
[ci skip]

* New translations strings.json (Swedish)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Ukrainian)
[ci skip]

* New translations strings.json (Chinese Simplified)
[ci skip]

* New translations strings.json (Chinese Traditional)
[ci skip]

* New translations strings.json (Vietnamese)
[ci skip]

* New translations strings.json (Portuguese, Brazilian)
[ci skip]

* New translations strings.json (Indonesian)
[ci skip]

* New translations strings.json (Hindi)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (French)
[ci skip]

* New translations strings.json (Hungarian)
[ci skip]

* New translations strings.json (Russian)
[ci skip]

* New translations strings.json (Portuguese, Brazilian)
[ci skip]

* New translations strings.json (Romanian)
[ci skip]

* New translations strings.json (French)
[ci skip]

* New translations strings.json (Spanish)
[ci skip]

* New translations strings.json (Afrikaans)
[ci skip]

* New translations strings.json (Arabic)
[ci skip]

* New translations strings.json (Catalan)
[ci skip]

* New translations strings.json (Czech)
[ci skip]

* New translations strings.json (Danish)
[ci skip]

* New translations strings.json (German)
[ci skip]

* New translations strings.json (Greek)
[ci skip]

* New translations strings.json (Finnish)
[ci skip]

* New translations strings.json (Hebrew)
[ci skip]

* New translations strings.json (Hungarian)
[ci skip]

* New translations strings.json (Italian)
[ci skip]

* New translations strings.json (Japanese)
[ci skip]

* New translations strings.json (Korean)
[ci skip]

* New translations strings.json (Dutch)
[ci skip]

* New translations strings.json (Norwegian)
[ci skip]

* New translations strings.json (Polish)
[ci skip]

* New translations strings.json (Portuguese)
[ci skip]

* New translations strings.json (Russian)
[ci skip]

* New translations strings.json (Albanian)
[ci skip]

* New translations strings.json (Serbian (Cyrillic))
[ci skip]

* New translations strings.json (Swedish)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Ukrainian)
[ci skip]

* New translations strings.json (Chinese Simplified)
[ci skip]

* New translations strings.json (Chinese Traditional)
[ci skip]

* New translations strings.json (Vietnamese)
[ci skip]

* New translations strings.json (Portuguese, Brazilian)
[ci skip]

* New translations strings.json (Indonesian)
[ci skip]

* New translations strings.json (Hindi)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Arabic)
[ci skip]

* New translations strings.json (Romanian)
[ci skip]

* New translations strings.json (French)
[ci skip]

* New translations strings.json (Spanish)
[ci skip]

* New translations strings.json (Afrikaans)
[ci skip]

* New translations strings.json (Arabic)
[ci skip]

* New translations strings.json (Catalan)
[ci skip]

* New translations strings.json (Czech)
[ci skip]

* New translations strings.json (Danish)
[ci skip]

* New translations strings.json (German)
[ci skip]

* New translations strings.json (Greek)
[ci skip]

* New translations strings.json (Finnish)
[ci skip]

* New translations strings.json (Hebrew)
[ci skip]

* New translations strings.json (Hungarian)
[ci skip]

* New translations strings.json (Italian)
[ci skip]

* New translations strings.json (Japanese)
[ci skip]

* New translations strings.json (Korean)
[ci skip]

* New translations strings.json (Dutch)
[ci skip]

* New translations strings.json (Norwegian)
[ci skip]

* New translations strings.json (Polish)
[ci skip]

* New translations strings.json (Portuguese)
[ci skip]

* New translations strings.json (Russian)
[ci skip]

* New translations strings.json (Albanian)
[ci skip]

* New translations strings.json (Serbian (Cyrillic))
[ci skip]

* New translations strings.json (Swedish)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Ukrainian)
[ci skip]

* New translations strings.json (Chinese Simplified)
[ci skip]

* New translations strings.json (Chinese Traditional)
[ci skip]

* New translations strings.json (Vietnamese)
[ci skip]

* New translations strings.json (Portuguese, Brazilian)
[ci skip]

* New translations strings.json (Indonesian)
[ci skip]

* New translations strings.json (Hindi)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Greek)
[ci skip]

* New translations strings.json (Greek)
[ci skip]

* New translations strings.json (Romanian)
[ci skip]

* New translations strings.json (French)
[ci skip]

* New translations strings.json (Spanish)
[ci skip]

* New translations strings.json (Afrikaans)
[ci skip]

* New translations strings.json (Arabic)
[ci skip]

* New translations strings.json (Catalan)
[ci skip]

* New translations strings.json (Czech)
[ci skip]

* New translations strings.json (Danish)
[ci skip]

* New translations strings.json (German)
[ci skip]

* New translations strings.json (Greek)
[ci skip]

* New translations strings.json (Finnish)
[ci skip]

* New translations strings.json (Hebrew)
[ci skip]

* New translations strings.json (Hungarian)
[ci skip]

* New translations strings.json (Italian)
[ci skip]

* New translations strings.json (Japanese)
[ci skip]

* New translations strings.json (Korean)
[ci skip]

* New translations strings.json (Dutch)
[ci skip]

* New translations strings.json (Norwegian)
[ci skip]

* New translations strings.json (Polish)
[ci skip]

* New translations strings.json (Portuguese)
[ci skip]

* New translations strings.json (Russian)
[ci skip]

* New translations strings.json (Albanian)
[ci skip]

* New translations strings.json (Serbian (Cyrillic))
[ci skip]

* New translations strings.json (Swedish)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Ukrainian)
[ci skip]

* New translations strings.json (Chinese Simplified)
[ci skip]

* New translations strings.json (Chinese Traditional)
[ci skip]

* New translations strings.json (Vietnamese)
[ci skip]

* New translations strings.json (Portuguese, Brazilian)
[ci skip]

* New translations strings.json (Indonesian)
[ci skip]

* New translations strings.json (Hindi)
[ci skip]
2023-07-15 13:21:29 +05:30
K1ngfish3r 4c00b2bc23 fix(source): Arnovel (#671)
* fix arnovel

* update 1stkissnovel url

* fix images 1stkissnovel

* QoL fixes for Agitoon and Pawread

* Partial fix for sakuranovel/indowebnovel chapnames

* Experimental lnp and pawread array

* I know how commas work

* fix inoveltranslation actual

* startCase

* fix bug
2023-07-15 13:15:32 +05:30
Patrick Loser 414ca51660 fix: Export to EPUB Improvements (#670)
* Test config

* update react-native-epub-creator

* updated deps

* option for export to epub

* added prettier to dev deps since I couldn't push

* removed white background when pulling up bottomsheet

* added options to the export to epub feature

* support for customCSS -JS and inchapter images

* package update

* fixed weird typing

* fixed weird KeyboardAvoidingView

* remove test config

* logic fix

* removed styles2

* fixed package problems

* fixed package problems

* notification icons

* package reinstallation

* package reinstallation

* customFileModal fix

* fixed ChapterItem alignment

* added github suggestions
2023-07-15 13:14:11 +05:30
Rajarshee Chatterjee 0d4e16509c fix: Env Variables 2023-07-03 22:50:04 +05:30
Rajarshee Chatterjee 0e131c039d fix: Crash in Reader (Closes #673) 2023-07-02 13:09:30 +05:30
Rajarshee Chatterjee 79639e6d29 feat: Add Bionic Reading (Closes #637) 2023-07-02 12:33:49 +05:30
Rajarshee Chatterjee 14ed97b2c3 fix: Shifting Text in CSS/JS Editor (Closes #654) 2023-06-30 08:51:03 +05:30
Rajarshee Chatterjee 0b5a012bfa fix: Persists Bookmark State (Closes #676) 2023-06-30 08:48:20 +05:30
Rajarshee Chatterjee 3074853fd6 fix: Update Patch Version to 15 (Closes #648) 2023-06-30 08:30:06 +05:30
Rajarshee Chatterjee 710cca66f3 fix: Remove Play Button from History 2023-06-30 08:24:48 +05:30
K1ngfish3r e66ee5f8ec fix: Update Sources (#657)
Closes LNReader/lnreader-sources#470
Closes LNReader/lnreader-sources#518
Closes LNReader/lnreader-sources#508
Closes LNReader/lnreader-sources#504
Closes LNReader/lnreader-sources#494
Closes LNReader/lnreader-sources#483
Closes LNReader/lnreader-sources#519
Closes LNReader/lnreader-sources#360
2023-06-16 09:36:21 +05:30
Patrick Loser c0b4610910 feat: EPUB Export (#646)
* Export to Epub

* removed uneccessary css

* updated dependency
2023-06-10 22:07:47 +05:30
Justin COLLON dd0ab5253e fix(source): NovelDeGlace (FR) (#658)
Closes LNReader/lnreader-sources#434
Closes LNReader/lnreader-sources#416
2023-06-10 22:05:45 +05:30
Patrick Loser 3adc655f7a feat: Add Trailing Skeleton Novel Covers (#629)
* TS NovelCover

* added some changes to the loading animation
2023-06-07 21:13:58 +05:30
Rider21 2d6251bddd feat(source): Add Bookriver (#641)
* add BookRiver

* Update bookriver.js

* updated tags, genres
2023-05-29 09:38:49 +05:30
Memexurer bbd134753b fix(source): NovelOnline (#635) 2023-05-15 10:05:55 +05:30
Rajarshee Chatterjee 61bf6794fa chore: Update Dependencies 2023-05-14 12:23:39 +05:30
Rajarshee Chatterjee 69d8a0012a fix: Don't Replace Characters in <> (Closes #602) 2023-05-14 10:59:09 +05:30
Rojikku ea82742190 fix(fetch): Add capacity to change UA string (#634)
* fix(fetch): Add capacity to change UA string

* fix(fetch): Set to string of false instead of empty

* fix(NovelUpdates): Enable Cloudflare Bypass

* fix(NovelUpdates): Add proper error throwing for bypass

* fix(NovelUpdates): Add dual output option to fetchHtml for NU

* fix(fetch+NU): Adjust fetch to not require a specific parameter

* fix(fetch+NU): Adjust away from raw to separate cloudflare check function
2023-05-14 10:49:58 +05:30
Rajarshee Chatterjee d161c393e4 fix: Add Chapter Name in Reader (Closes #601)
Memoize Webview Reader
2023-05-14 10:46:27 +05:30
Rajarshee Chatterjee a9c44ced4f Minor Tracker Fixes 2023-05-14 09:42:12 +05:30
Nick Ignoffo 135712c491 Normalized trackers refactor (+AniList) (#631)
* Begin AniList support

Mostly functional. Many large, sweeping changes to the data model used, so it may be worth looking into migrating the existing data structures. Otherwise it's a bad time for people already using MAL to track.

Much of the data model is documented with JSDoc, mostly for my sanity. I've never used JSDoc before so idk how correct these defs are 🤷

MAL has been mostly migrated over to the new format. There's a few straggling bits that seem to reference the old code that need to be cleared out.

Things to do:

* Status selector needs to respect AniList values/options when AL is in use
* Rating selector should respect the user's chosen rating format
* AniList option in the Discover section

* Use new MAL revalidator

* Clean up tracker creation/getting

* Generalize name for tracker cards file

* Normalize user list status

* Initialize trackers at app start

Fixes issues where things are initialized in the wrong order

* Tracker specific score implementations

MAL is effectively unchanged
AL supports all available formats. The UI leaves a bit to be desired, but it's functional.

* AniList browsing in discover

* Move AniList on top in settings for abc consistency

* Update tracker notifier when finishing chapter

* Migrate new tracker changes to TS

Additional cleanup pass

* Tracker data migration

* Fix AniList top novels info display
2023-05-14 09:37:23 +05:30
Nick Ignoffo daf40325d1 Fix scroll to progress on downloaded chapters (#632)
Fix scroll to progress
2023-05-14 08:27:05 +05:30
Rojikku c2438223c9 ScribbleHub: Convert to TS; Implement Latest, Genres, and Sorting (#626)
* ScribbleHub: Convert to TS

* ScribbleHub: Implement sorting; Debug TS

* ScribbleHub: Implement genres; Final TS debug
2023-05-11 21:10:06 +05:30
Patrick Loser 0ec250cff2 fix: Directly Add Novel to Library Category (#623)
Closes #611
2023-05-11 21:07:39 +05:30
Rojikku 55255ec64f fix(pre-commit): Make pre-commit executable for linux; gitignore jenv (#624) 2023-05-11 21:06:14 +05:30
Rojikku 3a8135ccd7 fix(ReadWN): Implemented better chapter assumption (#622)
fix(ReadWM): Implemented better chapter assumption
2023-05-08 07:06:56 +05:30
Patrick Loser 77bfc46d2a feat: Allow Accessing Variables in CustomJS (#619)
Co-authored-by: Rajarshee Chatterjee <rajarshee.adm@gmail.com>
2023-05-08 07:03:33 +05:30
Rajarshee Chatterjee 1afe254bf3 fix(source): ScribbleHub
Closes LNReader/lnreader-sources#463
Closes LNReader/lnreader-sources#491
2023-05-08 06:49:21 +05:30
Rajarshee Chatterjee 4199789683 chore: Update translations (#591)
* New translations strings.json (Italian)
[ci skip]

* New translations strings.json (Russian)
[ci skip]

* New translations strings.json (Romanian)
[ci skip]

* New translations strings.json (French)
[ci skip]

* New translations strings.json (Spanish)
[ci skip]

* New translations strings.json (Afrikaans)
[ci skip]

* New translations strings.json (Arabic)
[ci skip]

* New translations strings.json (Catalan)
[ci skip]

* New translations strings.json (Czech)
[ci skip]

* New translations strings.json (Danish)
[ci skip]

* New translations strings.json (German)
[ci skip]

* New translations strings.json (Greek)
[ci skip]

* New translations strings.json (Finnish)
[ci skip]

* New translations strings.json (Hebrew)
[ci skip]

* New translations strings.json (Hungarian)
[ci skip]

* New translations strings.json (Japanese)
[ci skip]

* New translations strings.json (Korean)
[ci skip]

* New translations strings.json (Dutch)
[ci skip]

* New translations strings.json (Norwegian)
[ci skip]

* New translations strings.json (Polish)
[ci skip]

* New translations strings.json (Portuguese)
[ci skip]

* New translations strings.json (Albanian)
[ci skip]

* New translations strings.json (Serbian (Cyrillic))
[ci skip]

* New translations strings.json (Swedish)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Ukrainian)
[ci skip]

* New translations strings.json (Chinese Simplified)
[ci skip]

* New translations strings.json (Chinese Traditional)
[ci skip]

* New translations strings.json (Vietnamese)
[ci skip]

* New translations strings.json (Portuguese, Brazilian)
[ci skip]

* New translations strings.json (Indonesian)
[ci skip]

* New translations strings.json (Hindi)
[ci skip]

* New translations strings.json (Arabic)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Italian)
[ci skip]

* New translations strings.json (Russian)
[ci skip]

* New translations strings.json (Romanian)
[ci skip]

* New translations strings.json (French)
[ci skip]

* New translations strings.json (Spanish)
[ci skip]

* New translations strings.json (Afrikaans)
[ci skip]

* New translations strings.json (Arabic)
[ci skip]

* New translations strings.json (Catalan)
[ci skip]

* New translations strings.json (Czech)
[ci skip]

* New translations strings.json (Danish)
[ci skip]

* New translations strings.json (German)
[ci skip]

* New translations strings.json (Greek)
[ci skip]

* New translations strings.json (Finnish)
[ci skip]

* New translations strings.json (Hebrew)
[ci skip]

* New translations strings.json (Hungarian)
[ci skip]

* New translations strings.json (Japanese)
[ci skip]

* New translations strings.json (Korean)
[ci skip]

* New translations strings.json (Dutch)
[ci skip]

* New translations strings.json (Norwegian)
[ci skip]

* New translations strings.json (Polish)
[ci skip]

* New translations strings.json (Portuguese)
[ci skip]

* New translations strings.json (Albanian)
[ci skip]

* New translations strings.json (Serbian (Cyrillic))
[ci skip]

* New translations strings.json (Swedish)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Ukrainian)
[ci skip]

* New translations strings.json (Chinese Simplified)
[ci skip]

* New translations strings.json (Chinese Traditional)
[ci skip]

* New translations strings.json (Vietnamese)
[ci skip]

* New translations strings.json (Portuguese, Brazilian)
[ci skip]

* New translations strings.json (Indonesian)
[ci skip]

* New translations strings.json (Hindi)
[ci skip]

* New translations strings.json (Italian)
[ci skip]

* New translations strings.json (Russian)
[ci skip]

* New translations strings.json (Romanian)
[ci skip]

* New translations strings.json (French)
[ci skip]

* New translations strings.json (Spanish)
[ci skip]

* New translations strings.json (Afrikaans)
[ci skip]

* New translations strings.json (Arabic)
[ci skip]

* New translations strings.json (Catalan)
[ci skip]

* New translations strings.json (Czech)
[ci skip]

* New translations strings.json (Danish)
[ci skip]

* New translations strings.json (German)
[ci skip]

* New translations strings.json (Greek)
[ci skip]

* New translations strings.json (Finnish)
[ci skip]

* New translations strings.json (Hebrew)
[ci skip]

* New translations strings.json (Hungarian)
[ci skip]

* New translations strings.json (Japanese)
[ci skip]

* New translations strings.json (Korean)
[ci skip]

* New translations strings.json (Dutch)
[ci skip]

* New translations strings.json (Norwegian)
[ci skip]

* New translations strings.json (Polish)
[ci skip]

* New translations strings.json (Portuguese)
[ci skip]

* New translations strings.json (Albanian)
[ci skip]

* New translations strings.json (Serbian (Cyrillic))
[ci skip]

* New translations strings.json (Swedish)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Ukrainian)
[ci skip]

* New translations strings.json (Chinese Simplified)
[ci skip]

* New translations strings.json (Chinese Traditional)
[ci skip]

* New translations strings.json (Vietnamese)
[ci skip]

* New translations strings.json (Portuguese, Brazilian)
[ci skip]

* New translations strings.json (Indonesian)
[ci skip]

* New translations strings.json (Hindi)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (French)
[ci skip]

* New translations strings.json (Indonesian)
[ci skip]

* New translations strings.json (Indonesian)
[ci skip]
2023-05-06 10:50:55 +05:30
K1ngfish3r f0d0696a8f fix: Source Updates (#615)
Closes LNReader/lnreader-sources#476
Closes LNReader/lnreader-sources#478
Closes LNReader/lnreader-sources#485
Closes LNReader/lnreader-sources#487
Closes LNReader/lnreader-sources#486
2023-05-06 10:41:38 +05:30
Patrick Loser 7221070963 fix: App Crash on Chapter End (#598)
* fixed midnightdusk

* fixed missing key

* fixed navigationbar visible after closing drawer

* removed insets

* Novelscreen warning removal

* removed remove Prefix

* fixed App crash at the end of chapter

* added Tooltip
2023-05-06 10:39:56 +05:30
Rajarshee Chatterjee ec5df867c3 fix: Downgrade React Native 2023-04-11 07:36:07 +05:30
Rajarshee Chatterjee 2dc226bbaf feat(source): Add Novels Online 2023-04-10 21:04:14 +05:30
Rajarshee Chatterjee 920b33ce17 fix: Revert to AsyncStorage for redux-persist Storage 2023-04-10 08:39:06 +05:30
Patrick Loser 5dcfc0c69c feat: Source Specific CSS (#597)
* copied settingsreaderscreen

* copied plusminusfield

* copied SettingsReaderScreen

* copied strings

* fix

* PlusMinusField -> Counter

* sourcecard change

* WebViewReaderChange

* Fixed ReaderLineHeight and ReaderTextSize

* showToast for CustomFileModal
2023-04-10 08:12:00 +05:30
Rajarshee Chatterjee 2e73cd6fd4 refactor: Use BottomSheetModal 2023-04-09 16:28:29 +05:30
Rajarshee Chatterjee da87f3a393 chore(deps): Update React Native 2023-04-09 12:50:53 +05:30
Rajarshee Chatterjee 4de8fab76a chore: Update Workflows 2023-04-08 19:22:29 +05:30
Rajarshee Chatterjee 9b7eb06027 Release v1.1.15 2023-04-06 21:55:10 +05:30
Rajarshee Chatterjee c210ddddc5 fix: Only Show Update Modal if New Version is Higher 2023-04-06 21:55:10 +05:30
Rajarshee Chatterjee ca163d83fb Minor Fixes 2023-04-06 21:55:10 +05:30
Rajarshee Chatterjee 49e4d78c92 chore: Update translations (#569)
* New translations strings.json (Romanian)
[ci skip]

* New translations strings.json (French)
[ci skip]

* New translations strings.json (Spanish)
[ci skip]

* New translations strings.json (Afrikaans)
[ci skip]

* New translations strings.json (Arabic)
[ci skip]

* New translations strings.json (Catalan)
[ci skip]

* New translations strings.json (Czech)
[ci skip]

* New translations strings.json (Danish)
[ci skip]

* New translations strings.json (German)
[ci skip]

* New translations strings.json (Greek)
[ci skip]

* New translations strings.json (Finnish)
[ci skip]

* New translations strings.json (Hebrew)
[ci skip]

* New translations strings.json (Hungarian)
[ci skip]

* New translations strings.json (Italian)
[ci skip]

* New translations strings.json (Japanese)
[ci skip]

* New translations strings.json (Korean)
[ci skip]

* New translations strings.json (Dutch)
[ci skip]

* New translations strings.json (Norwegian)
[ci skip]

* New translations strings.json (Polish)
[ci skip]

* New translations strings.json (Portuguese)
[ci skip]

* New translations strings.json (Russian)
[ci skip]

* New translations strings.json (Albanian)
[ci skip]

* New translations strings.json (Serbian (Cyrillic))
[ci skip]

* New translations strings.json (Swedish)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Ukrainian)
[ci skip]

* New translations strings.json (Chinese Simplified)
[ci skip]

* New translations strings.json (Chinese Traditional)
[ci skip]

* New translations strings.json (Vietnamese)
[ci skip]

* New translations strings.json (Portuguese, Brazilian)
[ci skip]

* New translations strings.json (Indonesian)
[ci skip]

* New translations strings.json (Hindi)
[ci skip]

* New translations strings.json (Turkish)
[ci skip]

* New translations strings.json (Vietnamese)
[ci skip]

* New translations strings.json (Portuguese, Brazilian)
[ci skip]

* New translations strings.json (German)
[ci skip]

* New translations strings.json (German)
[ci skip]

* New translations strings.json (Italian)
[ci skip]

* New translations strings.json (Russian)
[ci skip]

* New translations strings.json (Russian)
[ci skip]
2023-04-06 21:54:50 +05:30
r1di c88b2e5d2a feat: extending Volume button feature, by scroll amount (#587)
Closes #447 

* Main
Added volume button scroll amount

* Volume button scroll amount

---------

Co-authored-by: Ridi <Ridi>
2023-04-06 20:42:36 +05:30
Rider21 be2dab5b5d feat: Add New Sources (#583)
* fix

* Update ranobelib.js

* fix

* test

* fix

* fix path

* test

* added sources

* added ALL sources on novel.tl

* add tags

* Update NovelTlScraper.js

* fix
2023-03-30 13:19:00 +05:30
471 changed files with 44303 additions and 17479 deletions
+2 -2
View File
@@ -45,7 +45,7 @@ body:
label: LNReader version
description: You can find your LNReader version in **More → About**.
placeholder: |
Example: "2.0.0"
Example: "1.1.18"
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 **[2.0.0](https://github.com/lnreader/lnreader/releases/latest)**.
- label: I have updated the app to version **[1.1.18](https://github.com/lnreader/lnreader/releases/latest)**.
required: true
- label: I will fill out all of the requested information in this form.
required: true
+1 -1
View File
@@ -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 **[2.0.0](https://github.com/LNReader/lnreader/releases/latest)**.
- label: I have updated the app to version **[1.1.18](https://github.com/LNReader/lnreader/releases/latest)**.
required: true
- label: I will fill out all of the requested information in this form.
required: true
+3 -8
View File
@@ -2,7 +2,7 @@ name: CI
on:
push:
branches:
- master
- main
jobs:
build-android:
name: Build App
@@ -14,16 +14,11 @@ jobs:
fetch-depth: 0
- uses: actions/setup-node@v3
with:
node-version: '18'
node-version: '16'
- 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:
+4 -1
View File
@@ -13,9 +13,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Moderate issues
uses: tachiyomiorg/issue-moderator-action@v1
uses: tachiyomiorg/issue-moderator-action@v2
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
duplicate-label: Duplicate
auto-close-rules: |
[
{
@@ -29,3 +31,4 @@ jobs:
"message": "Requested information in the template was not filled out."
}
]
auto-close-ignore-label: do-not-autoclose
+3 -3
View File
@@ -2,10 +2,10 @@ name: CI
on:
push:
branches:
- master
- main
pull_request:
branches:
- master
- main
jobs:
build:
@@ -14,6 +14,6 @@ jobs:
steps:
- uses: actions/checkout@v2
- name: Install modules
run: npm install
run: npm i
- name: Run ESLint
run: npm run lint
+19
View File
@@ -0,0 +1,19 @@
name: Lock threads
on:
# Daily
schedule:
- cron: '0 0 * * *'
# Manual trigger
workflow_dispatch:
inputs:
jobs:
lock:
runs-on: ubuntu-latest
steps:
- uses: dessant/lock-threads@v4
with:
github-token: ${{ github.token }}
issue-inactive-days: '2'
pr-inactive-days: '2'
+5 -2
View File
@@ -9,7 +9,7 @@ npm-debug.*
*.orig.*
web-build/
.env
reader_playground/index.html
# macOS
.DS_Store
@@ -74,4 +74,7 @@ web-build/
# @end expo-cli
.vscode/
src/sources/en/generators/
src/sources/en/generators/
# jenv
.java-version
Regular → Executable
View File
-1
View File
@@ -1 +0,0 @@
18
+26 -22
View File
@@ -9,18 +9,22 @@ 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 { BottomSheetModalProvider } from '@gorhom/bottom-sheet';
import { createTables } from '@database/db';
import { createDatabase } from '@database/db';
import { persistor, store } from '@redux/store';
import AppErrorBoundary from '@components/AppErrorBoundary/AppErrorBoundary';
import { collectPlugins } from '@plugins/pluginManager';
import NewUpdateDialog from '@components/NewUpdateDialog';
import Main from './src/navigators/Main';
import { BottomSheetModalProvider } from '@gorhom/bottom-sheet';
import { usePlugins } from '@hooks/persisted';
import { MMKVStorage } from '@utils/mmkv/mmkv';
import { BACKGROUND_ACTION } from '@services/constants';
// Initialize trackers
import './src/services/Trackers/index';
import './src/services/Trackers/aniList';
import './src/services/Trackers/myAnimeList';
Notifications.setNotificationHandler({
handleNotification: async () => {
@@ -33,27 +37,27 @@ Notifications.setNotificationHandler({
});
const App = () => {
const { refreshPlugins } = usePlugins();
useEffect(() => {
createTables();
collectPlugins().then(() => LottieSplashScreen.hide());
refreshPlugins();
if (!BackgroundService.isRunning()) {
MMKVStorage.delete(BACKGROUND_ACTION);
}
LottieSplashScreen.hide();
createDatabase();
}, []);
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<AppErrorBoundary>
<SafeAreaProvider>
<PaperProvider>
<BottomSheetModalProvider>
<StatusBar translucent={true} backgroundColor="transparent" />
<Main />
</BottomSheetModalProvider>
</PaperProvider>
</SafeAreaProvider>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<SafeAreaProvider>
<PaperProvider>
<BottomSheetModalProvider>
<NewUpdateDialog />
<StatusBar translucent={true} backgroundColor="transparent" />
<Main />
</BottomSheetModalProvider>
</PaperProvider>
</SafeAreaProvider>
</PersistGate>
</Provider>
</AppErrorBoundary>
</GestureHandlerRootView>
);
-43
View File
@@ -57,46 +57,3 @@ 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
}
```
+158 -67
View File
@@ -1,87 +1,130 @@
apply plugin: "com.android.application"
apply plugin: "com.facebook.react"
apply plugin: "com.chaquo.python"
import com.android.build.OutputFile
/**
* 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.
* 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: []
* ]
*/
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")
/* 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"]
project.ext.react = [
entryFile: "index.js",
enableHermes: true, // clean and rebuild if changing
hermesCommand: '../../node_modules/react-native/sdks/hermesc/%OS-BIN%/hermesc',
]
/* 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"]
}
apply from: "../../node_modules/react-native/react.gradle"
/**
* 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.
* 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.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Set this to true to Run Proguard on Release builds to minify the Java bytecode.
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore (JSC).
* The preferred build flavor of JavaScriptCore.
*
* 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:+'
/**
* 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.
* 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.
*/
def reactNativeArchitectures() {
def value = project.getProperties().get("reactNativeArchitectures")
@@ -89,23 +132,38 @@ def reactNativeArchitectures() {
}
ext {
versionMajor = 2
versionMinor = 0
versionPatch = 0
versionMajor = 1
versionMinor = 1
versionPatch = 18
}
android {
ndkVersion rootProject.ext.ndkVersion
compileSdkVersion rootProject.ext.compileSdkVersion
namespace "com.rajarsheechatterjee.LNReader"
defaultConfig {
applicationId 'com.rajarsheechatterjee.LNReader'
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
// Generated version code. Supports versions up to 1024.1024.2048
versionCode ((((versionMajor << 10) | versionMinor) << 11) | versionPatch)
versionCode((((versionMajor << 10) | versionMinor) << 11) | versionPatch)
versionName "$versionMajor.$versionMinor.$versionPatch"
buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
ndk {
abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
}
python {
//buildPython "C:/Users/kijij/AppData/Local/Programs/Python/Python39/python.exe" //don't believe you need this
pip {
install "-r", "./requirements.txt"
}
}
sourceSets {
main {
python.srcDirs = ["./src/main/python"]
}
}
}
splits {
abi {
@@ -153,14 +211,17 @@ android {
}
dependencies {
// 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 fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
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";
@@ -185,11 +246,41 @@ dependencies {
}
}
if (hermesEnabled.toBoolean()) {
implementation("com.facebook.react:hermes-android")
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'
}
} else {
implementation jscFlavor
}
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
// 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"
}
+19
View File
@@ -0,0 +1,19 @@
"""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,
)
-47
View File
@@ -1,47 +0,0 @@
{
"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"
}
+8
View File
@@ -12,3 +12,11 @@
-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 *;
}
+1
View File
@@ -0,0 +1 @@
lxml==4.6.3
+1 -1
View File
@@ -9,4 +9,4 @@
tools:ignore="GoogleAppIndexingWarning">
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" android:exported="false"/>
</application>
</manifest>
</manifest>
@@ -0,0 +1,70 @@
/**
* 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());
}
}
}
}
+2 -1
View File
@@ -1,4 +1,5 @@
<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" />
-155
View File
@@ -1,155 +0,0 @@
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);
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

File diff suppressed because one or more lines are too long
-181
View File
@@ -1,181 +0,0 @@
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);
@@ -1,174 +0,0 @@
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;
}
}
@@ -1,32 +0,0 @@
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.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactActivityDelegate;
import com.facebook.react.ReactRootView;
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.up(VolumeButtonListener.getScrollAmount());
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.down(VolumeButtonListener.getScrollAmount());
if (!VolumeButtonListener.prevent)
return super.dispatchKeyEvent(event);
}
@@ -77,13 +77,29 @@ public class MainActivity extends ReactActivity {
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
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
return new ReactActivityDelegateWrapper(this, BuildConfig.IS_NEW_ARCHITECTURE_ENABLED,
new MainActivityDelegate(this, getMainComponentName()
));
}
}
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,30 +1,34 @@
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 DefaultReactNativeHost(this) {
new ReactNativeHostWrapper(this, new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
@@ -32,8 +36,9 @@ public class MainApplication extends Application implements ReactApplication {
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new NavigationBarColorPackage());
packages.add(new com.rajarsheechatterjee.LNReader.NavigationBarColorPackage());
packages.add(new VolumeButtonListenerPackage());
packages.add(new EpubParserPackage());
return packages;
@@ -45,14 +50,11 @@ public class MainApplication extends Application implements ReactApplication {
}
@Override
protected boolean isNewArchEnabled() {
return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage();
}
@Override
protected Boolean isHermesEnabled() {
return BuildConfig.IS_HERMES_ENABLED;
}
});
}
);
@Override
public ReactNativeHost getReactNativeHost() {
@@ -63,16 +65,46 @@ public class MainApplication extends Application implements ReactApplication {
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
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();
}
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();
}
}
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig);
}
}
}
@@ -1,18 +1,21 @@
package com.rajarsheechatterjee.NavigationBarColor;
package com.rajarsheechatterjee.LNReader;
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.NavigationBarColor;
package com.rajarsheechatterjee.LNReader;
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,9 +27,10 @@ public class VolumeButtonListener extends ReactContextBaseJavaModule {
public static boolean prevent = false;
public static void sendEvent(boolean up) {
public static void sendEvent(boolean up, int amount) {
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
@@ -37,12 +38,22 @@ public class VolumeButtonListener extends ReactContextBaseJavaModule {
}
}
public static void down() {
sendEvent(false);
public static void down(int amount) {
sendEvent(false, amount);
}
public static void up() {
sendEvent(true);
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;
}
@ReactMethod
@@ -90,4 +101,14 @@ 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());
}
}
@@ -0,0 +1,123 @@
package com.rajarsheechatterjee.EpubParser;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import android.app.Activity;
import android.content.Intent;
import android.content.Context;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.BaseActivityEventListener;
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.modules.core.DeviceEventManagerModule;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.util.Log;
public class EpubParser extends ReactContextBaseJavaModule implements ActivityEventListener{
private static final int REQUEST_DIRECTORY=100; //constant request code dunno if will use it
private static String epubPath;
private static Promise promise;
private final EpubParserActivityEventListener activityEventListener;
private static ReactApplicationContext appContext = null;
public EpubParser(ReactApplicationContext context){
super(context);
appContext = context;
activityEventListener = new EpubParserActivityEventListener(context, this);
context.addActivityEventListener(activityEventListener);
if (!Python.isStarted()) {
// Initialize Python with the Chaquopy SDK
Python.start(new AndroidPlatform(context));
}
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
if (activity != null && requestCode == REQUEST_DIRECTORY && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
String epubPath = getFilePathFromUri(uri);
Python py = Python.getInstance();
PyObject epubParser = py.getModule("epubParser");
if (epubPath != null && epubPath.toLowerCase().endsWith(".epub")) {
PyObject savePath = epubParser.callAttr("parseEpub", epubPath, "/data/data/com.rajarsheechatterjee.LNReader/files/");
promise.resolve(savePath.toString());
}
}
}
@Override
public String getName(){
return "EpubParser";
}
@ReactMethod
public void openDirectory(Promise promise){
this.promise = promise;
try{
Intent intent=new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*"); //there's an extra backslash in there
final Activity activity = getCurrentActivity();
activity.startActivityForResult(intent,REQUEST_DIRECTORY);
} catch (Exception e){
promise.reject(e);
}
}
private String getFilePathFromUri(Uri uri){
String filePath=null;
if(uri!=null){
ContentResolver resolver = getCurrentActivity().getContentResolver();
Cursor cursor=resolver.query(uri,null,null,null,null);
if(cursor!=null&&cursor.moveToFirst()){
int index=cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
String fileName=cursor.getString(index);
cursor.close();
File file=new File(getReactApplicationContext().getCacheDir(),fileName);
filePath=file.getAbsolutePath();
try{
InputStream inputStream=resolver.openInputStream(uri);
OutputStream outputStream=new FileOutputStream(file);
byte[]buffer=new byte[4096];
int bytesRead;
while((bytesRead=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,bytesRead);
}
outputStream.close();
inputStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
return filePath;
}
@Override
public void onNewIntent(Intent intent) {
// Handle new intents if needed
}
}
@@ -0,0 +1,25 @@
package com.rajarsheechatterjee.EpubParser;
import android.app.Activity;
import android.content.Intent;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.BaseActivityEventListener;
import com.facebook.react.bridge.ReactMethod;
public class EpubParserActivityEventListener extends BaseActivityEventListener {
private final ReactApplicationContext reactContext;
private final EpubParser epubParser;
public EpubParserActivityEventListener(ReactApplicationContext reactContext, EpubParser epubParser) {
this.reactContext = reactContext;
this.epubParser = epubParser;
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
epubParser.onActivityResult(activity, requestCode, resultCode, data);
}
}
@@ -0,0 +1,26 @@
package com.rajarsheechatterjee.EpubParser;
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 {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<NativeModule>();
modules.add(new EpubParser(reactContext));
return modules;
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
+268
View File
@@ -0,0 +1,268 @@
import json
import os.path
import os
import re
import zipfile
from lxml import etree
# import shutil
# from PIL import Image #not necessary only for debugging
'''export interface SourceNovel {
url: string; //must be absoulute
name: string;
cover?: string;
genres?: string;
summary?: string;
author?: string;
artist?: string;
status?: string;
chapters?: ChapterItem[];
}
export interface ChapterItem {
name: string;
url: string; //must be absoulute
releaseTime?: string;
}'''
class ChapterItem:
def __init__(self, name, url, releaseTime):
self.name = name
self.url = url
self.releaseTime = releaseTime # perhaps epub creation date?
namespaces = {
'calibre': 'http://calibre.kovidgoyal.net/2009/metadata',
'dc': 'http://purl.org/dc/elements/1.1/',
'dcterms': 'http://purl.org/dc/terms/',
'opf': 'http://www.idpf.org/2007/opf',
'ncx': 'http://www.daisy.org/z3986/2005/ncx/',
'u': 'urn:oasis:names:tc:opendocument:xmlns:container',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xhtml': 'http://www.w3.org/1999/xhtml'
}
def getContentOPF(epub_path):
with zipfile.ZipFile(epub_path) as z:
text = z.read('META-INF/container.xml') # get container xml to get content
tree = etree.fromstring(text)
rootfile_path = tree.xpath('/u:container/u:rootfiles/u:rootfile',
namespaces=namespaces)[0].get('full-path')
tree = etree.fromstring(z.read(rootfile_path))
return tree
def cleanTitle(dir_name):
# cleans a string so that it is valid for directories
pattern = r'[<>:"/\\|?*\x00-\x1F]'
# Remove any disallowed characters from the directory name string
clean_dir_name = re.sub(pattern, '', dir_name)
return clean_dir_name
def getContent(epub_path, dest_dir):
extensions = ['.html', '.htm', '.xhtml', '.css', '.png', '.jpeg', '.jpg', '.gif', '.ncx',
'.opf'] # still need the content.opf file
with zipfile.ZipFile(epub_path) as z:
for filename in z.namelist():
if (filename.endswith('opf')):
contentOPF = filename # search for opf file
break
tree = etree.XML(z.read(contentOPF))
title = tree.find('.//dc:title', namespaces=namespaces).text
cleanedTitle = cleanTitle(title)
dir = dest_dir + 'convertedEpubs/' + cleanedTitle # temporary directory for saving
for fileInfo in z.infolist():
if any(fileInfo.filename.endswith(ext) for ext in extensions):
z.extract(fileInfo, path=dir)
return dir
def treeFindsAll(queryString, XMLtree):
list = XMLtree.findall(queryString, namespaces=namespaces)
query = ''
if len(list) == 0:
query = 'N/A'
return query
for item in list:
query += (item.text + ' ')
return query
class SourceNovel:
def __init__(self, url, name, cover, genres, summary, author, artist, chapters):
self.url = url # file location?
self.name = name
self.cover = cover
self.genres = genres
self.summary = summary
self.author = author
self.artist = artist
self.status = 'local'
self.chapters = chapters
def getChapters(z: zipfile.ZipFile, opf_tree, dir_path):
isEPUB2 = False
chapters = []
for filename in z.namelist():
if filename.endswith('toc.ncx'):
isEPUB2 = True
chpts_data_filename = filename
break
if isEPUB2:
name_by_path = {}
tree = etree.XML(z.read(chpts_data_filename))
for nav_point in tree.xpath('.//ncx:navPoint', namespaces=namespaces):
name = nav_point.find('.//ncx:text', namespaces=namespaces).text
path = nav_point.find('.//ncx:content', namespaces=namespaces).attrib['src']
chapter_path = path[:path.index('#')] if '#' in path else path
if chapter_path not in name_by_path:
name_by_path[chapter_path] = name
chapters_elements = opf_tree.xpath('//opf:spine//opf:itemref', namespaces=namespaces)
for i, chapter_el in enumerate(chapters_elements):
id = chapter_el.get('idref')
item = opf_tree.find(f".//opf:manifest/opf:item[@id='{id}']", namespaces=namespaces)
path = item.attrib['href']
chapter_has_name = path in name_by_path
print(chapter_has_name)
if chapter_has_name:
chapter_name = name_by_path[path]
if chapter_name.isnumeric():
chapterName = f'Chapter {chapter_name}'
else:
chapterName = chapter_name
else:
chapterName = id.split('_')[0]
chapters.append({
'name': chapterName,
'path': dir_path + '/' + path if len(dir_path) > 0 else path,
})
else:
# EPUB3 uses nav.xhtml instead but I don't have an example rn
# For now it will list all files without their corresponding chapter names
chapters_elements = opf_tree.xpath('//opf:spine//opf:itemref', namespaces=namespaces)
for i, chapter_el in enumerate(chapters_elements):
id = chapter_el.get('idref')
item = opf_tree.find(f".//opf:manifest/opf:item[@id='{id}']", namespaces=namespaces)
path = item.attrib['href']
chapters.append({
'name': f'EPUB3 - Chapter {i + 1}',
'path': dir_path + '/' + path if len(dir_path) > 0 else path,
})
return chapters
def getMetadata(epub_path, save_path):
with zipfile.ZipFile(epub_path) as z:
for filename in z.namelist():
if (filename.endswith('opf')):
contentOPF = filename # search for opf file
break
print('content.opf', contentOPF)
tree = etree.XML(z.read(contentOPF))
title = tree.find('.//dc:title', namespaces=namespaces).text
# print('title', title)
cover = getCover(epub_path)
# print('cover', cover)
authors = ''
for author in tree.findall('.//dc:creator', namespaces=namespaces):
authors += (author.text + ' ')
# print('authors', authors)
genre = treeFindsAll('.//dc:subject', tree)
# print('genre', genre)
summary = treeFindsAll('.//dc:description', tree)
# print('summary', summary)
artist = '' # this will be included with author as epub files do not need to have an artist role and distinction is probably not necessary
chapters = getChapters(z, tree, os.path.dirname(contentOPF))
print('chapters', chapters)
return {
'url': save_path,
'title': title,
'cover': cover,
'genre': genre,
'summary': summary,
'authors': authors.strip(),
'artist': artist,
'chapters': chapters,
}
def getCover(epub_path):
with zipfile.ZipFile(epub_path) as z:
for filename in z.namelist():
if (filename.endswith('opf')):
contentOPF = filename # search for opf file
tree = etree.XML(z.read(contentOPF))
coverHREF = None
try:
coverID = tree.xpath("//opf:metadata/opf:meta[@name='cover']", namespaces=namespaces)[0].get('content')
# print('coverID 2', coverID) # now we know where the cover image is located
coverHREF = tree.xpath("//opf:manifest/opf:item[@id='" + coverID + "']", namespaces=namespaces)[0].get(
'href')
except IndexError: # not an EPUB 2.0
# print('EPUB 2 failure')
pass
if not coverHREF: # try EPUB 3.0
try:
coverHREF = tree.xpath("//opf:manifest/opf:item[@properties='cover-image']", namespaces=namespaces)[
0].get('href')
except IndexError:
# print('EPUB 3 failure')
pass
elif not coverHREF: # some EPUBs don't explicitly declare cover images
try:
coverID = tree.xpath("//opf:spine/open:itemref[@idref='cover']", namespaces=namespaces)[0].get('idref')
temp = tree.xpath("//opf:manifest/opf:item[@id='" + coverID + "']", namespaces=namespaces)[0].get(
'href')
tree = etree.fromstring(z.read(temp))
coverHREF = tree.xpath('//xhtml:img', namespaces=namespaces)[0].get('src')
except IndexError:
print('Edge case failure')
elif not coverHREF:
# print('No cover found')
return None
coverPath = coverHREF.replace('\\', '/')
# print('coverPath', coverPath)
return coverPath if os.path.dirname(contentOPF) == 0 else os.path.dirname(contentOPF) + '/' + coverPath
def dumpMetaData(metaData, dest_dir):
dir = dest_dir + 'convertedEpubs/' + cleanTitle(metaData.get('title')) + '/'
with open(dir + 'metadata.json', 'w') as fileout:
json.dump(metaData, fileout)
def parseEpub(epub_path, dest_dir):
save_path = getContent(epub_path, dest_dir) # simultaneously writes and saves content to a variable
metaData = getMetadata(epub_path, save_path)
dumpMetaData(metaData, dest_dir)
return save_path
Binary file not shown.

After

Width:  |  Height:  |  Size: 936 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 558 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

After

Width:  |  Height:  |  Size: 67 KiB

+1 -1
View File
@@ -25,4 +25,4 @@
<!-- <item name="icon">@drawable/no_icon</item> -->
<item name="android:windowBackground">@drawable/splashscreen</item>
</style>
</resources>
</resources>
@@ -1,20 +0,0 @@
/**
* 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.
}
}
+53 -6
View File
@@ -4,20 +4,67 @@ import org.apache.tools.ant.taskdefs.condition.Os
buildscript {
ext {
buildToolsVersion = "33.0.0"
buildToolsVersion = "31.0.0"
minSdkVersion = 21
compileSdkVersion = 33
targetSdkVersion = 33
compileSdkVersion = 31
targetSdkVersion = 31
// We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
ndkVersion = "23.1.7779620"
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"
}
}
repositories {
google()
mavenCentral()
maven { url "https://chaquo.com/maven" }
}
dependencies {
classpath("com.android.tools.build:gradle:7.4.1")
classpath("com.android.tools.build:gradle:7.1.2")
classpath("com.facebook.react:react-native-gradle-plugin")
classpath("de.undercouch:gradle-download-task:5.0.1")
classpath ("com.chaquo.python:gradle:14.0.2")
// 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' }
}
}
+3 -5
View File
@@ -27,6 +27,8 @@ 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
@@ -38,14 +40,10 @@ 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
Binary file not shown.
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+1 -1
View File
@@ -231,4 +231,4 @@ eval "set -- $(
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
exec "$JAVACMD" "$@"
+89 -89
View File
@@ -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
+6 -5
View File
@@ -1,15 +1,16 @@
rootProject.name = 'LNReader'
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('@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()
include ':app'
includeBuild('../node_modules/react-native-gradle-plugin')
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')
+4 -3
View File
@@ -3,8 +3,9 @@
"name": "LNReader",
"slug": "LNReader",
"scheme": "lnreader",
"plugins": [
"expo-localization"
]
"notification": {
"icon": "./assets/notification.png",
"color": "#00adb5"
}
}
}
+2 -5
View File
@@ -1,7 +1,7 @@
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo', 'module:metro-react-native-babel-preset'],
presets: ['babel-preset-expo'],
plugins: [
[
'module-resolver',
@@ -14,12 +14,9 @@ module.exports = function (api) {
'@strings': './strings',
'@redux': './src/redux',
'@services': './src/services',
'@plugins': './src/plugins',
'@sources': './src/sources',
'@utils': './src/utils',
'@theme': './src/theme',
'@navigators': './src/navigators',
'@native': './src/native',
'@api': './src/api',
},
},
],
+4
View File
@@ -0,0 +1,4 @@
module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
+4805 -3752
View File
File diff suppressed because it is too large Load Diff
+58 -46
View File
@@ -1,90 +1,102 @@
{
"name": "lnreader",
"version": "2.0.0",
"version": "1.1.18",
"private": true,
"scripts": {
"android": "react-native run-android --active-arch-only",
"android": "react-native run-android",
"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": {
"@cd-z/react-native-epub-creator": "^2.0.4",
"@gorhom/bottom-sheet": "^4.4.5",
"@react-native-community/slider": "4.4.2",
"@react-native-google-signin/google-signin": "^11.0.0",
"@react-native-picker/picker": "2.4.8",
"@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-navigation/material-bottom-tabs": "^6.0.9",
"@react-navigation/native": "^6.1.9",
"@react-navigation/native": "^6.0.6",
"@react-navigation/stack": "^6.0.11",
"@shopify/flash-list": "1.4.0",
"@reduxjs/toolkit": "^1.9.5",
"@shopify/flash-list": "1.1.0",
"cheerio": "^1.0.0-rc.10",
"color": "^4.2.3",
"dayjs": "^1.11.4",
"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",
"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",
"i18n-js": "^3.8.0",
"lodash-es": "^4.17.21",
"qs": "^6.10.3",
"react": "18.2.0",
"react-native": "0.71.14",
"react-native-background-actions": "^3.0.1",
"react": "18.0.0",
"react-fast-compare": "^3.2.1",
"react-native": "^0.69.9",
"react-native-background-actions": "^2.6.5",
"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.9.0",
"react-native-gesture-handler": "~2.5.0",
"react-native-lottie-splash-screen": "^1.0.1",
"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-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-saf-x": "^2.2.1",
"react-native-safe-area-context": "4.3.1",
"react-native-screens": "~3.15.0",
"react-native-shimmer-placeholder": "^2.0.9",
"react-native-tab-view": "^3.5.2",
"react-native-tab-view": "^3.1.1",
"react-native-tts": "^4.1.0",
"react-native-vector-icons": "^9.0.0",
"react-native-webview": "11.26.0",
"react-native-webview": "11.23.0",
"react-native-zip-archive": "^6.0.9",
"react-redux": "^7.2.6",
"redux-persist": "^6.0.0",
"rn-fetch-blob": "^0.12.0",
"sanitize-html": "^2.7.0",
"urlencode": "^2.0.0"
"text-vide": "^1.7.0"
},
"devDependencies": {
"@babel/core": "^7.20.0",
"@babel/runtime": "^7.20.0",
"@react-native-community/eslint-config": "^3.2.0",
"@tsconfig/react-native": "^2.0.2",
"@babel/core": "^7.21.4",
"@react-native-community/eslint-config": "^3.0.1",
"@types/color": "^3.0.3",
"@types/i18n-js": "^3.8.2",
"@types/jest": "^27.4.0",
"@types/lodash-es": "^4.17.6",
"@types/react": "^18.0.24",
"@types/react-native": "~0.69.1",
"@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.10.2",
"@typescript-eslint/parser": "^5.10.2",
"@typescript-eslint/eslint-plugin": "^5.57.1",
"@typescript-eslint/parser": "^5.57.1",
"babel-plugin-module-resolver": "^4.1.0",
"eslint": "^8.19.0",
"eslint-plugin-react-native": "^4.1.0",
"eslint": "^8.0.0",
"eslint-plugin-react-native": "^4.0.0",
"husky": "^7.0.4",
"lint-staged": "^12.3.7",
"metro-react-native-babel-preset": "^0.73.10",
"prettier": "^2.4.1",
"react-native-dotenv": "^3.4.9",
"typescript": "4.8.4"
"prettier": "^2.8.8",
"typescript": "^4.6.3"
},
"resolutions": {
"@types/react": "^17"
-410
View File
@@ -1,410 +0,0 @@
#!/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()
+7
View File
@@ -0,0 +1,7 @@
module.exports = {
project: {
ios: {},
android: {},
},
assets: ['./assets/fonts/'],
};
-5
View File
@@ -1,5 +0,0 @@
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.
-71
View File
@@ -1,71 +0,0 @@
<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>
+79
View File
@@ -0,0 +1,79 @@
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);
}
},
);
}
});
+327
View File
@@ -0,0 +1,327 @@
/**
* 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);
}
-1
View File
@@ -1 +0,0 @@
export const PATH_SEPARATOR = '&&';
-111
View File
@@ -1,111 +0,0 @@
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);
}
};
-117
View File
@@ -1,117 +0,0 @@
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',
},
});
});
}
});
};
-35
View File
@@ -1,35 +0,0 @@
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
}
-90
View File
@@ -1,90 +0,0 @@
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 -1
View File
@@ -1,4 +1,4 @@
import { useTheme } from '@hooks/persisted';
import { useTheme } from '@hooks/useTheme';
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/persisted';
import { useTheme } from '@hooks';
interface ErrorFallbackProps {
error: Error;
+1 -2
View File
@@ -6,10 +6,9 @@ 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,6 +6,8 @@ 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;
@@ -13,6 +15,8 @@ interface BottomSheetProps extends Omit<BottomSheetModalProps, 'ref'> {
const BottomSheet: React.FC<BottomSheetProps> = props => {
const { bottom } = useSafeAreaInsets();
const theme = useTheme();
const renderBackdrop = useCallback(
(backdropProps: BottomSheetBackdropProps) => (
<BottomSheetBackdrop
@@ -23,12 +27,14 @@ 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}
+2 -2
View File
@@ -4,9 +4,9 @@ import {
ButtonProps as PaperButtonProps,
} from 'react-native-paper';
import { useTheme } from '@hooks/persisted';
import { useTheme } from '@hooks';
interface ButtonProps extends Partial<PaperButtonProps> {
interface ButtonProps extends Omit<PaperButtonProps, 'children' | 'theme'> {
title?: string;
}
@@ -1,13 +1,13 @@
import React from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { ThemeColors } from '../../theme/types';
import { ThemeType } from '../../theme/types';
interface ColorPreferenceItemProps {
label: string;
description?: string;
onPress: () => void;
theme: ThemeColors;
theme: ThemeType;
}
const ColorPreferenceItem: React.FC<ColorPreferenceItemProps> = ({
@@ -1,20 +1,15 @@
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,
}: {
children?: React.ReactNode;
theme: ThemeColors;
}) => {
const ScreenContainer = ({ children, theme }) => {
const { bottom } = useSafeAreaInsets();
return (
<View
style={{
flex: 1,
backgroundColor: theme.colorPrimaryDark,
paddingBottom: bottom,
}}
>
@@ -23,13 +18,9 @@ const ScreenContainer = ({
);
};
const Row = ({
children,
style = {},
}: {
children?: React.ReactNode;
style?: any;
}) => <View style={[styles.row, style]}>{children}</View>;
const Row = ({ children, style = {} }) => (
<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 '../Button/Button';
import { Button } from '@components/index';
interface ConfirmationDialogProps {
title: string;
+114
View File
@@ -0,0 +1,114 @@
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,22 +1,8 @@
import { useTheme } from '@hooks/persisted';
import { useTheme } from '@hooks/useTheme';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
interface EmptyViewProps {
icon: string;
description: string;
style?: any;
children?: React.ReactNode;
iconStyle?: any;
}
const EmptyView = ({
icon,
description,
style,
children,
iconStyle,
}: EmptyViewProps) => {
const EmptyView = ({ icon, description, style, children, iconStyle }) => {
const theme = useTheme();
return (
@@ -1,7 +1,7 @@
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { useTheme } from '@hooks/persisted';
import { useTheme } from '@hooks/useTheme';
interface ErrorScreenProps {
error: string;
@@ -1,23 +1,10 @@
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・;)', 'Σ(ಠ_ಠ)', 'ಥ_ಥ', '(˘・_・˘)', '(; ̄Д ̄)', '(・Д・。'];
interface ErrorAction {
name: string;
icon: string;
onPress: () => void;
}
interface ErrorViewProps {
errorName: string;
actions: ErrorAction[];
theme: ThemeColors;
}
export const ErrorView = ({ errorName, actions, theme }: ErrorViewProps) => (
export const ErrorView = ({ errorName, actions, theme }) => (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={[styles.emptyViewIcon, { color: theme.outline }]}>
{/* {icons[Math.floor(Math.random() * 5)]} */}
@@ -49,7 +36,12 @@ export const ErrorView = ({ errorName, actions, theme }: ErrorViewProps) => (
minWidth: 100,
}}
>
<IconButton icon={action.icon} size={24} style={{ margin: 0 }} />
<IconButton
icon={action.icon}
color={theme.outline}
size={24}
style={{ margin: 0 }}
/>
<Text
style={{
fontSize: 12,
+4 -16
View File
@@ -9,10 +9,9 @@ interface ListItemProps {
title: string;
description?: string | null;
icon?: string;
right?: string;
onPress?: () => void;
theme: ThemeColors;
disabled?: boolean;
right?: string;
}
const Section = ({ children }: { children: ReactNode }) => (
@@ -37,16 +36,13 @@ const Item: React.FC<ListItemProps> = ({
icon,
onPress,
theme,
disabled,
right,
}) => (
<PaperList.Item
title={title}
titleStyle={{ color: disabled ? theme.onSurfaceDisabled : theme.onSurface }}
titleStyle={{ color: theme.onSurface }}
description={description}
descriptionStyle={{
color: disabled ? theme.onSurfaceDisabled : theme.onSurfaceVariant,
}}
descriptionStyle={{ color: theme.onSurfaceVariant }}
left={
icon
? () => (
@@ -69,7 +65,6 @@ const Item: React.FC<ListItemProps> = ({
)
: undefined
}
disabled={disabled}
onPress={onPress}
rippleColor={theme.rippleColor}
style={styles.listItemCtn}
@@ -101,14 +96,7 @@ const Icon = ({ icon, theme }: { icon: string; theme: ThemeColors }) => (
<PaperList.Icon color={theme.primary} icon={icon} style={{ margin: 0 }} />
);
interface ColorItemProps {
title: string;
description: string;
theme: ThemeColors;
onPress: () => void;
}
const ColorItem = ({ title, description, theme, onPress }: ColorItemProps) => (
const ColorItem = ({ title, description, theme, onPress }) => (
<Pressable
style={{
padding: 16,
@@ -1,23 +1,13 @@
import React from 'react';
import { StyleSheet, View, Text, Pressable } from 'react-native';
import { Image } from 'react-native';
import FastImage from 'react-native-fast-image';
import { coverPlaceholderColor } from '../theme/colors';
import color from 'color';
import { ThemeColors } from '@theme/types';
import { NovelInfo } from '@database/types';
import { getSourceStorage } from '@hooks/useSourceStorage';
import { defaultUserAgentString } from '@utils/fetch/fetch';
interface ListViewProps {
item: NovelInfo;
downloadBadge?: React.ReactNode;
unreadBadge?: React.ReactNode;
inLibraryBadge?: React.ReactNode;
theme: ThemeColors;
onPress: () => void;
isSelected?: boolean;
onLongPress?: () => void;
}
import color from 'color';
const ListView = ({
item,
@@ -28,7 +18,8 @@ const ListView = ({
onPress,
isSelected,
onLongPress,
}: ListViewProps) => {
}) => {
const { cookies = '' } = getSourceStorage(item.sourceId);
return (
<Pressable
android_ripple={{ color: theme.rippleColor }}
@@ -41,17 +32,18 @@ const ListView = ({
onPress={onPress}
onLongPress={onLongPress}
>
<Image
<FastImage
source={{
uri: item.cover,
uri: item.novelCover,
headers: { Cookie: cookies, 'User-Agent': defaultUserAgentString },
}}
style={[styles.extensionIcon, inLibraryBadge ? { opacity: 0.5 } : {}]}
style={[styles.extensionIcon, inLibraryBadge && { opacity: 0.5 }]}
/>
<Text
style={[{ color: theme.onSurface }, styles.novelName]}
numberOfLines={1}
>
{item.name}
{item.novelName}
</Text>
<View style={styles.badgeContainer}>
{downloadBadge}
+30 -31
View File
@@ -1,54 +1,57 @@
import React, { useState } from 'react';
import { StyleSheet, View, Text, Dimensions } from 'react-native';
import React, { useEffect } from 'react';
import { ScrollView, StyleSheet, View, Text, Dimensions } from 'react-native';
import { Portal, Modal } from 'react-native-paper';
import * as Linking from 'expo-linking';
import { ScrollView } from 'react-native-gesture-handler';
import Button from './Button/Button';
import { Button } from '@components';
import { useBoolean, useReleaseChecker, useTheme } from '@hooks';
import { getString } from '@strings/translations';
import { useTheme } from '@hooks/persisted';
interface NewUpdateDialogProps {
newVersion: {
tag_name: string;
body: string;
downloadUrl: string;
};
}
const NewUpdateDialog: React.FC<NewUpdateDialogProps> = ({ newVersion }) => {
const [newUpdateDialog, showNewUpdateDialog] = useState(true);
const NewUpdateDialog: React.FC = () => {
const theme = useTheme();
const newRelease = useReleaseChecker();
const {
value: isVisible,
setFalse: hideModal,
setValue: setModalVisible,
} = useBoolean();
useEffect(() => {
setModalVisible(Boolean(newRelease));
}, [newRelease]);
const modalHeight = Dimensions.get('window').height / 2;
if (!newRelease) {
return null;
}
return (
<Portal>
<Modal
visible={newUpdateDialog}
onDismiss={() => showNewUpdateDialog(false)}
visible={isVisible}
onDismiss={hideModal}
contentContainerStyle={[
styles.containerStyle,
{ backgroundColor: theme.overlay3 },
]}
>
<Text style={[styles.modalHeader, { color: theme.onSurface }]}>
{`${getString('common.newUpdateAvailable')} ${newVersion.tag_name}`}
{`${getString('common.newUpdateAvailable')} ${newRelease?.tagName}`}
</Text>
<ScrollView style={{ height: modalHeight }}>
<Text style={[styles.body, { color: theme.onSurfaceVariant }]}>
{newVersion.body.split('\n').join('\n\n')}
<Text style={{ color: theme.onSurface }}>
{newRelease?.changelog}
</Text>
</ScrollView>
<View style={styles.buttonCtn}>
<Button
title={getString('common.cancel')}
onPress={() => showNewUpdateDialog(false)}
/>
<Button title={getString('common.cancel')} onPress={hideModal} />
<Button
title={getString('common.install')}
onPress={() => Linking.openURL(newVersion.downloadUrl)}
onPress={() => Linking.openURL(newRelease?.downloadUrl)}
/>
</View>
</Modal>
@@ -69,10 +72,6 @@ const styles = StyleSheet.create({
fontSize: 20,
marginBottom: 16,
},
body: {
fontSize: 15,
fontWeight: '500',
},
buttonCtn: {
flexDirection: 'row',
marginTop: 16,
+93 -85
View File
@@ -8,49 +8,40 @@ import {
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { Image } from 'react-native';
import FastImage from 'react-native-fast-image';
import ListView from './ListView';
import { useDeviceOrientation } from '@hooks';
import { useDeviceOrientation } from '@hooks/useDeviceOrientation';
import { coverPlaceholderColor } from '../theme/colors';
import { useLibrarySettings } from '@hooks/useSettings';
import { DisplayModes } from '@screens/library/constants/constants';
import { LibraryNovelInfo, NovelInfo } from '@database/types';
import { NovelItem } from '@plugins/types';
import { LibraryNovelInfo } from '@database/types';
import { SourceNovelItem } from 'src/sources/types';
import { ThemeColors } from '@theme/types';
import { useLibrarySettings } from '@hooks/persisted';
import { getUserAgent } from '@hooks/persisted/useUserAgent';
import SourceScreenSkeletonLoading from '@screens/browse/loadingAnimation/SourceScreenSkeletonLoading';
interface UnreadBadgeProps {
chaptersDownloaded: number;
chaptersUnread: number;
showDownloadBadges: boolean;
import { getSourceStorage } from '@hooks/useSourceStorage';
import { defaultUserAgentString } from '@utils/fetch/fetch';
interface NovelCoverProps {
item: LibraryNovelInfo;
onPress: () => void;
libraryStatus?: boolean;
theme: ThemeColors;
isSelected?: boolean;
onLongPress: (novelId: number) => void;
selectedNovels?: Array<SourceNovelItem>;
}
interface DownloadBadgeProps {
chaptersDownloaded: number;
chaptersUnread: number;
showUnreadBadges: boolean;
theme: ThemeColors;
}
function NovelCover<TNovel extends NovelItem | NovelInfo | LibraryNovelInfo>({
const NovelCover: React.FC<NovelCoverProps> = ({
item,
onPress,
libraryStatus,
theme,
isSelected,
onLongPress,
selectedNovelIds,
}: {
item: TNovel;
onPress: () => void;
libraryStatus: boolean;
theme: ThemeColors;
isSelected: boolean;
onLongPress: (item: TNovel) => void;
selectedNovelIds: number[];
}) {
selectedNovels,
}) => {
const {
displayMode = DisplayModes.Comfortable,
showDownloadBadges = true,
@@ -69,21 +60,25 @@ function NovelCover<TNovel extends NovelItem | NovelInfo | LibraryNovelInfo>({
const coverHeight = useMemo(
() => (window.width / numColumns) * (4 / 3),
// eslint-disable-next-line react-hooks/exhaustive-deps
[numColumns],
);
const selectNovel = () => onLongPress(item);
const selectNovel = () => onLongPress && onLongPress(item.novelId);
const uri = item.cover;
return displayMode !== DisplayModes.List ? (
const uri = item.novelCover;
const { cookies = '' } = getSourceStorage(item.sourceId);
return item.sourceId < 0 ? (
<SourceScreenSkeletonLoading theme={theme} completeRow={item.sourceId} />
) : displayMode !== DisplayModes.List ? (
<View
style={[
{
flex: 1 / numColumns,
borderRadius: 6,
overflow: 'hidden',
margin: 2,
},
styles.standardNovelCover,
isSelected && {
backgroundColor: theme.primary,
opacity: 0.8,
@@ -94,15 +89,13 @@ function NovelCover<TNovel extends NovelItem | NovelInfo | LibraryNovelInfo>({
android_ripple={{ color: theme.rippleColor }}
style={styles.opac}
onPress={
selectedNovelIds && selectedNovelIds.length > 0
? selectNovel
: onPress
selectedNovels && selectedNovels.length > 0 ? selectNovel : onPress
}
onLongPress={selectNovel}
>
<View style={styles.badgeContainer}>
{libraryStatus && <InLibraryBadge theme={theme} />}
{showDownloadBadges && item.chaptersDownloaded > 0 && (
{showDownloadBadges && item.chaptersDownloaded && (
<DownloadBadge
showUnreadBadges={showUnreadBadges}
chaptersDownloaded={item.chaptersDownloaded}
@@ -110,7 +103,7 @@ function NovelCover<TNovel extends NovelItem | NovelInfo | LibraryNovelInfo>({
theme={theme}
/>
)}
{showUnreadBadges && item.chaptersUnread > 0 && (
{showUnreadBadges && item.chaptersUnread && (
<UnreadBadge
theme={theme}
chaptersDownloaded={item.chaptersDownloaded}
@@ -119,24 +112,27 @@ function NovelCover<TNovel extends NovelItem | NovelInfo | LibraryNovelInfo>({
/>
)}
</View>
<Image
source={{ uri, headers: { 'User-Agent': getUserAgent() } }}
<FastImage
source={{
uri,
headers: { Cookie: cookies, 'User-Agent': defaultUserAgentString },
}}
style={[
{
height: coverHeight,
borderRadius: 4,
backgroundColor: coverPlaceholderColor,
},
libraryStatus && { opacity: 0.5 },
styles.standardBorderRadius,
libraryStatus && styles.opacityPoint5,
]}
/>
<View style={styles.compactTitleContainer}>
{displayMode === DisplayModes.Compact && (
<CompactTitle novelName={item.name} />
<CompactTitle novelName={item.novelName} />
)}
</View>
{displayMode === DisplayModes.Comfortable && (
<ComfortableTitle novelName={item.name} theme={theme} />
<ComfortableTitle novelName={item.novelName} theme={theme} />
)}
</Pressable>
</View>
@@ -168,30 +164,27 @@ function NovelCover<TNovel extends NovelItem | NovelInfo | LibraryNovelInfo>({
inLibraryBadge={libraryStatus && <InLibraryBadge theme={theme} />}
theme={theme}
onPress={
selectedNovelIds && selectedNovelIds.length > 0 ? selectNovel : onPress
selectedNovels && selectedNovels.length > 0 ? selectNovel : onPress
}
onLongPress={selectNovel}
isSelected={isSelected}
/>
);
}
};
export default memo(NovelCover);
const ComfortableTitle = ({
const ComfortableTitle: React.FC<{ theme: ThemeColors; novelName: string }> = ({
theme,
novelName,
}: {
theme: ThemeColors;
novelName: string;
}) => (
<Text
numberOfLines={2}
style={[
styles.title,
styles.padding4,
{
color: theme.onSurface,
padding: 4,
},
]}
>
@@ -199,61 +192,57 @@ const ComfortableTitle = ({
</Text>
);
const CompactTitle = ({ novelName }: { novelName: string }) => (
const CompactTitle: React.FC<{ novelName: string }> = ({ novelName }) => (
<View style={styles.titleContainer}>
<LinearGradient
colors={['transparent', 'rgba(0,0,0,0.7)']}
style={styles.linearGradient}
>
<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,
},
]}
>
<Text numberOfLines={2} style={[styles.title, styles.compactTitle]}>
{novelName}
</Text>
</LinearGradient>
</View>
);
const InLibraryBadge = ({ theme }: { theme: ThemeColors }) => (
const InLibraryBadge: React.FC<{ theme: ThemeColors }> = ({ theme }) => (
<Text
style={[
styles.inLibraryBadge,
{
backgroundColor: theme.primary,
color: theme.onPrimary,
borderRadius: 4,
},
styles.standardBorderRadius,
]}
>
In library
</Text>
);
const UnreadBadge = ({
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> = ({
chaptersDownloaded,
chaptersUnread,
showDownloadBadges,
theme,
}: UnreadBadgeProps) => (
}) => (
<Text
style={[
styles.unreadBadge,
!chaptersDownloaded && {
borderTopLeftRadius: 4,
borderBottomLeftRadius: 4,
},
!showDownloadBadges && {
borderRadius: 4,
},
!chaptersDownloaded && styles.LeftBorderRadius,
!showDownloadBadges && styles.standardBorderRadius,
{
backgroundColor: theme.primary,
color: theme.onPrimary,
@@ -264,22 +253,17 @@ const UnreadBadge = ({
</Text>
);
const DownloadBadge = ({
const DownloadBadge: React.FC<DownloadBadgeProps> = ({
chaptersDownloaded,
showUnreadBadges,
chaptersUnread,
theme,
}: DownloadBadgeProps) => (
}) => (
<Text
style={[
styles.downloadBadge,
!chaptersUnread && {
borderTopRightRadius: 4,
borderBottomRightRadius: 4,
},
!showUnreadBadges && {
borderRadius: 4,
},
!chaptersUnread && styles.RightBorderRadius,
!showUnreadBadges && styles.standardBorderRadius,
{
backgroundColor: theme.tertiary,
color: theme.onTertiary,
@@ -291,6 +275,19 @@ const DownloadBadge = ({
);
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,
@@ -354,4 +351,15 @@ 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,
},
});
+29 -9
View File
@@ -1,23 +1,27 @@
import { useLibrarySettings } from '@hooks/persisted';
import { useLibrarySettings } from '@hooks/useSettings';
import { DisplayModes } from '@screens/library/constants/constants';
import React, { useMemo } from 'react';
import React, { useCallback, useMemo } from 'react';
import {
StyleSheet,
FlatList,
FlatListProps,
ListRenderItem,
} from 'react-native';
import { NovelItem } from '@plugins/types';
import { SourceNovelItem } from '../sources/types';
import { LibraryNovelInfo, NovelInfo } from '../database/types';
import { useDeviceOrientation } from '@hooks';
import { useDeviceOrientation } from '@hooks/useDeviceOrientation';
export type NovelListRenderItem = ListRenderItem<
LibraryNovelInfo | NovelInfo | NovelItem
LibraryNovelInfo | NovelInfo | SourceNovelItem
>;
const NovelList: React.FC<
FlatListProps<LibraryNovelInfo | NovelInfo | NovelItem>
> = props => {
interface NovelListProps
extends FlatListProps<LibraryNovelInfo | NovelInfo | SourceNovelItem> {
isFetchingNextPage?: boolean;
inSource?: boolean;
}
const NovelList: React.FC<NovelListProps> = props => {
const { displayMode = DisplayModes.Comfortable, novelsPerRow = 3 } =
useLibrarySettings();
@@ -37,6 +41,21 @@ const NovelList: React.FC<
}
}, [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={[
@@ -45,8 +64,9 @@ const NovelList: React.FC<
]}
numColumns={numColumns}
key={numColumns}
keyExtractor={item => item.url}
keyExtractor={keyExtractor}
{...props}
data={extendedNovelList}
/>
);
};
@@ -1,37 +1,14 @@
import { ThemeColors } from '@theme/types';
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
import { RadioButton as MaterialRadioButton } from 'react-native-paper';
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) => (
export const RadioButtonGroup = ({ children, value, onValueChange }) => (
<MaterialRadioButton.Group onValueChange={onValueChange} value={value}>
{children}
</MaterialRadioButton.Group>
);
export const RadioButton = ({
value,
label,
theme,
labelStyle,
}: RadioButtonProps) => (
export const RadioButton = ({ value, label, theme, labelStyle }) => (
<View style={styles.radioButtonContainer}>
<MaterialRadioButton
value={value}
+25 -26
View File
@@ -20,31 +20,6 @@ const SwitchSetting: React.FC<SwitchProps> = ({
icon,
value,
}) => {
const styles = StyleSheet.create({
container: {
paddingHorizontal: 16,
flexDirection: 'row',
justifyContent: 'space-between',
paddingVertical: description ? 16 : 12,
},
row: {
flexDirection: 'row',
flex: 1,
},
icon: {
margin: 0,
},
textContainer: {
marginLeft: icon && 16,
},
text: {
fontSize: 16,
flex: 1,
textAlignVertical: 'center',
},
switch: { marginLeft: 8 },
});
return (
<Pressable
android_ripple={{
@@ -57,7 +32,7 @@ const SwitchSetting: React.FC<SwitchProps> = ({
{icon && (
<List.Icon color={theme.primary} icon={icon} style={styles.icon} />
)}
<View style={styles.textContainer}>
<View>
<Text style={[styles.text, { color: theme.onSurface }]}>{label}</Text>
{description && (
<Text style={{ color: theme.onSurfaceVariant }}>{description}</Text>
@@ -75,3 +50,27 @@ const SwitchSetting: React.FC<SwitchProps> = ({
};
export default SwitchSetting;
const styles = StyleSheet.create({
container: {
paddingHorizontal: 16,
flexDirection: 'row',
justifyContent: 'space-between',
paddingVertical: 16,
},
row: {
flexDirection: 'row',
flex: 1,
},
icon: {
margin: 0,
marginRight: 16,
},
text: {
fontSize: 16,
textAlignVertical: 'center',
},
switch: {
marginLeft: 8,
},
});
@@ -3,19 +3,8 @@ 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';
interface ThemePickerProps {
theme: ThemeColors;
currentTheme: ThemeColors;
onPress: () => void;
}
export const ThemePicker = ({
theme,
currentTheme,
onPress,
}: ThemePickerProps) => (
export const ThemePicker = ({ theme, currentTheme, onPress }) => (
<View
style={{
justifyContent: 'center',
+74 -24
View File
@@ -1,50 +1,100 @@
import * as SQLite from 'expo-sqlite';
import {
createCategoriesTableQuery,
createCategoryDefaultQuery,
createCategoryLocalQuery,
createCategoryTriggerQuery,
} from './tables/CategoryTable';
import { createNovelTableQuery } from './tables/NovelTable';
import { createNovelCategoryTableQuery } from './tables/NovelCategoryTable';
createNovelTableQuery,
createUrlIndexQuery,
createLibraryIndexQuery,
addCategoryColumnQuery,
} from './tables/NovelTable';
import {
createChapterTableQuery,
createChapterNovelIdIndexQuery,
createNovelIdIndexQuery,
createUnreadChaptersIndexQuery,
} from './tables/ChapterTable';
import { dbTxnErrorCallback } from './utils/helpers';
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 { noop } from 'lodash-es';
const dbName = 'lnreader.db';
const db = SQLite.openDatabase(dbName);
export const createTables = () => {
db.exec([{ sql: 'PRAGMA foreign_keys = ON', args: [] }], false, () => {});
const createTables = () => {
db.transaction(tx => {
tx.executeSql(createNovelTableQuery);
tx.executeSql(createCategoriesTableQuery, [], () => {
tx.executeSql(createCategoryDefaultQuery);
tx.executeSql(createCategoryLocalQuery);
tx.executeSql(createCategoryTriggerQuery);
tx.executeSql(
addCategorySortColumnQuery,
undefined,
noop,
txnErrorCallbackWithoutToast,
);
tx.executeSql(
createDefaultCategoryQuery,
undefined,
noop,
txnErrorCallbackWithoutToast,
);
});
tx.executeSql(createNovelCategoryTableQuery);
tx.executeSql(createChapterTableQuery, [], () => {
tx.executeSql(createChapterNovelIdIndexQuery);
tx.executeSql(createNovelTableQuery, [], () => {
tx.executeSql(
addCategoryColumnQuery,
undefined,
noop,
txnErrorCallbackWithoutToast,
);
});
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 = async () => {
export const deleteDatabase = () => {
db.transaction(
tx => {
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');
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');
},
dbTxnErrorCallback,
noop,
+24 -94
View File
@@ -1,15 +1,14 @@
import * as SQLite from 'expo-sqlite';
import { noop } from 'lodash-es';
import { BackupCategory, Category, NovelCategory, CCategory } from '../types';
import { showToast } from '@utils/showToast';
import { Category } from '../types';
import { txnErrorCallback } from '../utils/helpers';
const db = SQLite.openDatabase('lnreader.db');
const getCategoriesQuery = `
SELECT * FROM Category ORDER BY sort
SELECT * FROM categories ORDER BY CASE WHEN id > 1 THEN 1 ELSE 0 END, IFNULL(sort, 9999)
`;
export const getCategoriesFromDb = async (): Promise<Category[]> => {
export const getCategoriesFromDb = (): Promise<Category[]> => {
return new Promise(resolve =>
db.transaction(tx => {
tx.executeSql(
@@ -22,67 +21,31 @@ export const getCategoriesFromDb = async (): Promise<Category[]> => {
);
};
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
const createCategoryQuery = `
INSERT INTO categories (name)
VALUES
(?)
`;
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 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 = ?';
const deleteCategoryQuery = `
DELETE FROM categories
WHERE
id = ?
`;
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);
});
};
export const deleteCategoryById = (categoryId: number): void =>
db.transaction(tx =>
tx.executeSql(deleteCategoryQuery, [categoryId], noop, txnErrorCallback),
);
const updateCategoryQuery = 'UPDATE Category SET name = ? WHERE id = ?';
const updateCategoryQuery = `
UPDATE categories SET name = ? WHERE id = ?
`;
export const updateCategory = (
categoryId: number,
@@ -98,7 +61,7 @@ export const updateCategory = (
);
const isCategoryNameDuplicateQuery = `
SELECT COUNT(*) as isDuplicate FROM Category WHERE name = ?
SELECT COUNT(*) as isDuplicate FROM categories WHERE name = ?
`;
export const isCategoryNameDuplicate = (
@@ -119,13 +82,11 @@ export const isCategoryNameDuplicate = (
);
};
const updateCategoryOrderQuery = 'UPDATE Category SET sort = ? WHERE id = ?';
const updateCategoryOrderQuery = `
UPDATE categories SET sort = ? WHERE id = ?
`;
export const updateCategoryOrderInDb = (categories: Category[]): void => {
// Do not set local as default one
if (categories.length && categories[0].id == 2) {
return;
}
export const updateCategoryOrderInDb = (categories: Category[]): void =>
db.transaction(tx => {
categories.map(category => {
tx.executeSql(
@@ -136,34 +97,3 @@ 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],
);
}
});
};
+294 -213
View File
@@ -1,25 +1,21 @@
import RNFS from 'react-native-fs';
import * as SQLite from 'expo-sqlite';
import { showToast } from '@utils/showToast';
import { getPlugin } from '@plugins/pluginManager';
import { ChapterInfo, DownloadedChapter } from '../types';
import { ChapterItem } from '@plugins/types';
import { showToast } from '../../hooks/showToast';
import { sourceManager } from '../../sources/sourceManager';
import { ChapterItem } from '../types';
import * as cheerio from 'cheerio';
import { NovelDownloadFolder } from '@utils/constants/download';
import RNFetchBlob from 'rn-fetch-blob';
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 insertChapterQuery = `
INSERT INTO Chapter (
url, name, releaseTime, novelId, chapterNumber
const insertChaptersQuery = `
INSERT INTO chapters (
chapterUrl, chapterName, releaseDate,
novelId
)
Values
(?, ?, ?, ?, ?)
values
(?, ?, ?, ?)
`;
export const insertChapters = async (
@@ -29,56 +25,53 @@ export const insertChapters = async (
if (!chapters?.length) {
return;
}
db.transaction(tx => {
chapters.forEach(chapter => {
tx.executeSql(
insertChapterQuery,
[
chapter.url,
chapter.name,
chapter.releaseTime || '',
novelId,
chapter.chapterNumber || null,
],
noop,
txnErrorCallback,
);
});
chapters.map(chapter =>
tx.executeSql(insertChaptersQuery, [
chapter.chapterUrl,
chapter.chapterName,
chapter.releaseDate,
novelId,
]),
);
});
};
const getChaptersQuery = (sort = 'ORDER BY id ASC', filter = '') =>
`SELECT * FROM Chapter WHERE novelId = ? ${filter} ${sort}`;
const getChaptersQuery = (sort = 'ORDER BY chapterId ASC', filter = '') =>
`SELECT * FROM chapters WHERE novelId = ? ${filter} ${sort}`;
export const getChapters = (
novelId: number,
sort?: string,
filter?: string,
): Promise<ChapterInfo[]> => {
export const getChapters = (novelId: number, sort: string, filter: string) => {
return new Promise(resolve =>
db.transaction(tx => {
tx.executeSql(
getChaptersQuery(sort, filter),
[novelId],
(txObj, { rows }) => resolve((rows as any)._array),
(txObj, { rows }) => {
const _array = (rows as any)._array;
resolve(_array);
},
txnErrorCallback,
);
}),
);
};
// downloaded chapter
const getChapterQuery =
'SELECT chapterText FROM Download WHERE Download.chapterId = ?';
const getChapterQuery = 'SELECT * FROM downloads WHERE downloadChapterId = ?';
export const getChapterFromDB = (chapterId: number): Promise<string> => {
export const getChapterFromDB = async (chapterId: number) => {
return new Promise(resolve =>
db.transaction(tx => {
tx.executeSql(
getChapterQuery,
[chapterId],
(txObj, { rows }) => resolve(rows.item(0)?.chapterText),
txnErrorCallback,
(txObj, results) => {
resolve(results.rows.item(0));
},
(_txObj, _error) => {
// console.log('Error ', error)
return false;
},
);
}),
);
@@ -86,19 +79,19 @@ export const getChapterFromDB = (chapterId: number): Promise<string> => {
const getPrevChapterQuery = `
SELECT
id, *
*
FROM
Chapter
chapters
WHERE
novelId = ?
AND
id < ?
chapterId < ?
`;
export const getPrevChapter = (
novelId: number,
chapterId: number,
): Promise<ChapterInfo> => {
): Promise<ChapterItem> => {
return new Promise(resolve =>
db.transaction(tx => {
tx.executeSql(
@@ -106,8 +99,8 @@ export const getPrevChapter = (
[novelId, chapterId],
(_txObj, results) =>
resolve(results.rows.item(results.rows.length - 1)),
() => {
showToast("There's no previous chapter");
(_txObj, error) => {
showToast(error.message);
return false;
},
);
@@ -117,27 +110,27 @@ export const getPrevChapter = (
const getNextChapterQuery = `
SELECT
id, *
*
FROM
Chapter
chapters
WHERE
novelId = ?
AND
id > ?
chapterId > ?
`;
export const getNextChapter = (
novelId: number,
chapterId: number,
): Promise<ChapterInfo> => {
): Promise<ChapterItem> => {
return new Promise(resolve =>
db.transaction(tx => {
tx.executeSql(
getNextChapterQuery,
[novelId, chapterId],
(_txObj, results) => resolve(results.rows.item(0)),
() => {
showToast("There's no next Chapter");
(_txObj, error) => {
showToast(error.message);
return false;
},
);
@@ -145,126 +138,227 @@ export const getNextChapter = (
);
};
const markChapterReadQuery = 'UPDATE Chapter SET `unread` = 0 WHERE id = ?';
const markChapterReadQuery =
'UPDATE chapters SET `read` = 1 WHERE chapterId = ?';
export const markChapterRead = async (chapterId: number) => {
db.transaction(tx => {
tx.executeSql(markChapterReadQuery, [chapterId], noop, (_txObj, _error) => {
// console.log(error)
return false;
});
tx.executeSql(
markChapterReadQuery,
[chapterId],
(_txObj, _res) => {},
(_txObj, _error) => {
// console.log(error)
return false;
},
);
});
};
const markChapterUnreadQuery = 'UPDATE Chapter SET `unread` = 1 WHERE id = ?';
const markChapterUnreadQuery =
'UPDATE chapters SET `read` = 0 WHERE chapterId = ?';
export const markChapterUnread = async (chapterId: number) => {
db.transaction(tx => {
tx.executeSql(markChapterUnreadQuery, [chapterId], noop, txnErrorCallback);
tx.executeSql(
markChapterUnreadQuery,
[chapterId],
(_txObj, _res) => {},
(_txObj, _error) => {
// console.log(error)
return false;
},
);
});
};
const markAllChaptersReadQuery =
'UPDATE Chapter SET `unread` = 0 WHERE novelId = ?';
'UPDATE chapters SET `read` = 1 WHERE novelId = ?';
export const markAllChaptersRead = async (novelId: number) => {
db.transaction(tx => {
tx.executeSql(markAllChaptersReadQuery, [novelId], noop, txnErrorCallback);
tx.executeSql(
markAllChaptersReadQuery,
[novelId],
(_txObj, _res) => {},
(_txObj, _error) => {
// console.log(error)
return false;
},
);
});
};
const markAllChaptersUnreadQuery =
'UPDATE Chapter SET `unread` = 1 WHERE novelId = ?';
'UPDATE chapters SET `read` = 0 WHERE novelId = ?';
export const markAllChaptersUnread = async (novelId: number) => {
db.transaction(tx => {
tx.executeSql(
markAllChaptersUnreadQuery,
[novelId],
noop,
txnErrorCallback,
(_txObj, _res) => {},
(_txObj, _error) => {
// console.log(error)
return false;
},
);
});
};
const createChapterFolder = async (
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 (
path: string,
data: {
pluginId: string;
data?: {
sourceId: number;
novelId: number;
chapterId: number;
},
): Promise<string> => {
const mkdirIfNot = async (p: string, nomedia: boolean) => {
const mkdirIfNot = async (p: string) => {
const nomediaPath =
p + (p.charAt(p.length - 1) === '/' ? '' : '/') + '.nomedia';
if (!(await RNFS.exists(p))) {
await RNFS.mkdir(p);
if (nomedia) {
await RNFS.writeFile(nomediaPath, ',', 'utf8');
}
if (!(await RNFetchBlob.fs.exists(p))) {
await RNFetchBlob.fs.mkdir(p);
await RNFetchBlob.fs.createFile(nomediaPath, ',', 'utf8');
}
};
await mkdirIfNot(path, false);
await mkdirIfNot(path);
const { pluginId, novelId, chapterId } = data;
await mkdirIfNot(`${path}/${pluginId}/${novelId}/${chapterId}/`, true);
return `${path}/${pluginId}/${novelId}/${chapterId}/`;
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 downloadFiles = async (
const downloadImages = async (
html: string,
plugin: Plugin,
sourceId: number,
novelId: number,
chapterId: number,
): Promise<void> => {
): Promise<string> => {
try {
const folder = await createChapterFolder(NovelDownloadFolder, {
pluginId: plugin.id,
novelId,
chapterId,
}).catch(error => {
throw error;
});
const headers = sourceManager(sourceId)?.headers || {};
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 plugin.fetchImage(url);
const fileurl = folder + i + '.b64.png';
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();
}
elem.attr('src', `file://${fileurl}`);
RNFS.writeFile(fileurl, imageb64, 'base64');
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(folder + 'index.html', loadedCheerio.html());
} catch (error) {
throw error;
loadedCheerio('body').prepend("<input type='hidden' offline />");
return loadedCheerio.html();
} catch (e) {
return html;
}
};
// novelId for determine folder %LNReaderDownloadDir%/novelId/ChapterId/
export const downloadChapter = async (
pluginId: string,
sourceId: number,
novelUrl: string,
novelId: number,
chapterId: number,
chapterUrl: string,
chapterId: number,
) => {
try {
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);
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,
));
db.transaction(tx => {
tx.executeSql(
"UPDATE Chapter SET isDownloaded = 1, updatedTime = datetime('now','localtime') WHERE id = ?",
'UPDATE chapters SET downloaded = 1 WHERE chapterId = ?',
[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");
@@ -274,59 +368,81 @@ export const downloadChapter = async (
}
};
const deleteDownloadedFiles = async (
pluginId: string,
const deleteDownloadedImages = async (
sourceId: number,
novelId: number,
chapterId: number,
) => {
try {
const path = await createChapterFolder(NovelDownloadFolder, {
pluginId,
novelId,
chapterId,
});
const files = await RNFS.readDir(path);
const path = await createImageFolder(
`${RNFetchBlob.fs.dirs.DownloadDir}/LNReader`,
{ sourceId, novelId, chapterId },
);
const files = await RNFetchBlob.fs.ls(path);
for (let i = 0; i < files.length; i++) {
await RNFS.unlink(files[i].path);
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(path);
} catch (error) {
throw new Error('Cant delete chapter chapter folder');
}
} catch (error) {}
};
// delete downloaded chapter
export const deleteChapter = async (
pluginId: string,
sourceId: number,
novelId: number,
chapterId: number,
) => {
const updateIsDownloadedQuery =
'UPDATE Chapter SET isDownloaded = 0 WHERE id = ?';
'UPDATE chapters SET downloaded = 0 WHERE chapterId=?';
const deleteChapterQuery = 'DELETE FROM downloads WHERE downloadChapterId=?';
await deleteDownloadedFiles(pluginId, novelId, chapterId);
await deleteDownloadedImages(sourceId, novelId, chapterId);
db.transaction(tx => {
tx.executeSql(updateIsDownloadedQuery, [chapterId], noop, txnErrorCallback);
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;
},
);
});
};
export const deleteChapters = async (
pluginId: string,
novelId: number,
chapters?: ChapterInfo[],
sourceId: number,
chapters?: ChapterItem[],
) => {
if (!chapters?.length) {
return;
}
const chapterIdsString = chapters?.map(chapter => chapter.id).toString();
const chapterIdsString = chapters
?.map(chapter => chapter.chapterId)
.toString();
const updateIsDownloadedQuery = `UPDATE Chapter SET isDownloaded = 0 WHERE id IN (${chapterIdsString})`;
const updateIsDownloadedQuery = `UPDATE chapters SET downloaded = 0 WHERE chapterId IN (${chapterIdsString})`;
const deleteChapterQuery = `DELETE FROM downloads WHERE downloadChapterId IN (${chapterIdsString})`;
await Promise.all(
chapters?.map(chapter =>
deleteDownloadedFiles(pluginId, novelId, chapter.id),
deleteDownloadedImages(sourceId, chapter.novelId, chapter.chapterId),
),
);
@@ -337,62 +453,42 @@ export const deleteChapters = async (
undefined,
txnErrorCallback,
);
tx.executeSql(deleteChapterQuery, undefined, undefined, txnErrorCallback);
});
};
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'),
);
});
};
const getLastReadChapterQuery = `
SELECT chapters.*
FROM history
JOIN chapters
ON history.historyChapterId = chapters.chapterId
WHERE history.historyNovelId = ?
`;
const getReadDownloadedChapters = async (): Promise<DownloadedChapter[]> => {
export const getLastReadChapter = async (novelId: number) => {
return new Promise(resolve => {
db.transaction(tx => {
tx.executeSql(
`
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),
getLastReadChapterQuery,
[novelId],
(txObj, { rows }) => resolve(rows.item(0)),
(_txObj, _error) => {
// console.log('Error ', error)
return false;
},
);
});
});
};
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 = ?';
const bookmarkChapterQuery =
'UPDATE chapters SET bookmark = ? WHERE chapterId = ?';
export const bookmarkChapter = async (bookmark: boolean, chapterId: number) => {
db.transaction(tx => {
tx.executeSql(
bookmarkChapterQuery,
[1 - Number(bookmark), chapterId],
[!bookmark, chapterId],
(_txObj, _res) => {},
(_txObj, _error) => {
// console.log('Error ', error)
@@ -403,7 +499,7 @@ export const bookmarkChapter = async (bookmark: boolean, chapterId: number) => {
};
const markPreviuschaptersReadQuery =
'UPDATE Chapter SET `unread` = 0 WHERE id <= ? AND novelId = ?';
'UPDATE chapters SET `read` = 1 WHERE chapterId < ? AND novelId = ?';
export const markPreviuschaptersRead = async (
chapterId: number,
@@ -423,7 +519,7 @@ export const markPreviuschaptersRead = async (
};
const markPreviousChaptersUnreadQuery =
'UPDATE Chapter SET `unread` = 1 WHERE id <= ? AND novelId = ?';
'UPDATE chapters SET `read` = 0 WHERE chapterId < ? AND novelId = ?';
export const markPreviousChaptersUnread = async (
chapterId: number,
@@ -443,23 +539,21 @@ export const markPreviousChaptersUnread = async (
};
const getDownloadedChaptersQuery = `
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
`;
SELECT chapters.*, novels.sourceId, novels.novelName, novels.novelCover, novels.novelUrl
FROM chapters
JOIN novels
ON chapters.novelId = novels.novelId
WHERE chapters.downloaded = 1`;
export const getDownloadedChapters = (): Promise<DownloadedChapter[]> => {
export const getDownloadedChapters = () => {
return new Promise(resolve =>
db.transaction(tx => {
tx.executeSql(
getDownloadedChaptersQuery,
undefined,
(txObj, { rows }) => {
resolve(rows._array);
const _array = (rows as any)._array;
resolve(_array);
},
(_txObj, _error) => {
// console.log('Error ', error)
@@ -470,38 +564,25 @@ export const getDownloadedChapters = (): Promise<DownloadedChapter[]> => {
);
};
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 clearUpdates = () => {
export const deleteDownloads = async () => {
db.transaction(tx => {
tx.executeSql(
'UPDATE Chapter SET updatedTime = NULL',
[],
noop,
txnErrorCallback,
);
tx.executeSql('UPDATE chapters SET downloaded = 0');
tx.executeSql('DELETE FROM downloads; VACCUM;');
});
};
export const updateChapterDownloadedQuery = `
UPDATE
chapters
SET
downloaded = 1
WHERE
chapterId = ?`;
export const updateChapterDeletedQuery = `
UPDATE
chapters
SET
downloaded = 0
WHERE
chapterId = ?`;
+138
View File
@@ -0,0 +1,138 @@
/* 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,
);
});
};
+69
View File
@@ -0,0 +1,69 @@
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.');
};
-61
View File
@@ -1,61 +0,0 @@
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.');
};
+65 -82
View File
@@ -5,83 +5,43 @@ import { txnErrorCallback } from '../utils/helpers';
const db = SQLite.openDatabase('lnreader.db');
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'";
}
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
`;
return new Promise(resolve =>
db.transaction(tx => {
tx.executeSql(
query,
[categoryId],
(txObj, { rows }) => resolve((rows as any)._array),
txnErrorCallback,
);
}),
);
};
export const getLibraryNovelsFromDb = (
onlyOngoingNovels?: boolean,
): Promise<NovelInfo[]> => {
let getLibraryNovelsQuery = 'SELECT * FROM Novel WHERE inLibrary = 1';
if (onlyOngoingNovels) {
getLibraryNovelsQuery += " AND status NOT LIKE 'Completed'";
}
return new Promise(resolve =>
db.transaction(tx => {
tx.executeSql(
getLibraryNovelsQuery,
undefined,
(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 = ({
export const getLibrary = ({
filter,
searchText,
sortOrder,
@@ -92,28 +52,51 @@ export const getLibraryWithCategory = ({
searchText?: string;
downloadedOnlyMode?: boolean;
}): Promise<LibraryNovelInfo[]> => {
let query = getLibraryWithCategoryQuery;
let query = getLibraryQuery;
if (filter) {
query += ` AND ${filter} `;
query += ` AND ${filter}`;
}
if (downloadedOnlyMode) {
query += ' ' + LibraryFilter.DownloadedOnly;
}
if (searchText) {
query += ` AND name LIKE '%${searchText}%' `;
query += ` AND novelName LIKE '%${searchText}%'`;
}
if (sortOrder) {
query += ` ORDER BY ${sortOrder} `;
query += ` ORDER BY ${sortOrder}`;
}
return new Promise(resolve =>
db.transaction(tx => {
tx.executeSql(
query,
[],
(txObj, { rows }) => resolve((rows as any)._array),
undefined,
(txObj, { rows: { _array } }) => resolve(_array),
txnErrorCallback,
);
}),
);
};
export const getLibraryNovelsFromDb = (
onlyOngoingNovels?: boolean,
): Promise<NovelInfo[]> => {
let getLibraryNovelsQuery = 'SELECT * FROM novels WHERE followed = 1';
if (onlyOngoingNovels) {
getLibraryNovelsQuery += " AND status NOT LIKE 'Completed'";
}
return new Promise(resolve =>
db.transaction(tx => {
tx.executeSql(
getLibraryNovelsQuery,
undefined,
(txObj, { rows: { _array } }) => resolve(_array),
txnErrorCallback,
);
}),
+254
View File
@@ -0,0 +1,254 @@
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;
}
};
-361
View File
@@ -1,361 +0,0 @@
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,
],
);
}
});
};
+205
View File
@@ -0,0 +1,205 @@
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,
),
);
});
};
+39 -39
View File
@@ -6,53 +6,53 @@ import { txnErrorCallback } from '../utils/helpers';
const db = SQLite.openDatabase('lnreader.db');
const getLibraryStatsQuery = `
SELECT COUNT(*) as novelsCount, COUNT(DISTINCT pluginId) as sourcesCount
FROM Novel
WHERE inLibrary = 1
SELECT COUNT(*) as novelsCount, COUNT(DISTINCT sourceId) as sourcesCount
FROM novels
WHERE novels.followed = 1
`;
const getChaptersReadCountQuery = `
SELECT COUNT(*) as chaptersRead
FROM Chapter
JOIN Novel
ON Chapter.novelId = Novel.id
WHERE Chapter.unread = 0 AND Novel.inLibrary = 1
FROM chapters
JOIN novels
ON chapters.novelId = novels.novelId
WHERE chapters.read = 1 AND novels.followed = 1
`;
const getChaptersTotalCountQuery = `
SELECT COUNT(*) as chaptersCount
FROM Chapter
JOIN Novel
ON Chapter.novelId = Novel.id
WHERE Novel.inLibrary = 1
FROM chapters
JOIN novels
ON chapters.novelId = novels.novelId
WHERE novels.followed = 1
`;
const getChaptersUnreadCountQuery = `
SELECT COUNT(*) as chaptersUnread
FROM Chapter
JOIN Novel
ON Chapter.novelId = Novel.id
WHERE Chapter.unread = 1 AND Novel.inLibrary = 1
FROM chapters
JOIN novels
ON chapters.novelId = novels.novelId
WHERE chapters.read = 0 AND novels.followed = 1
`;
const getChaptersDownloadedCountQuery = `
SELECT COUNT(*) as chaptersDownloaded
FROM Chapter
JOIN Novel
ON Chapter.novelId = Novel.id
WHERE Chapter.isDownloaded = 1 AND Novel.inLibrary = 1
FROM chapters
JOIN novels
ON chapters.novelId = novels.novelId
WHERE chapters.downloaded = 1 AND novels.followed = 1
`;
const getNovelGenresQuery = `
SELECT genres
FROM Novel
WHERE Novel.inLibrary = 1
SELECT genre
FROM novels
WHERE novels.followed = 1
`;
const getNovelStatusQuery = `
SELECT status
FROM Novel
WHERE Novel.inLibrary = 1
FROM novels
WHERE novels.followed = 1
`;
export const getLibraryStatsFromDb = async (): Promise<LibraryStats> => {
@@ -61,8 +61,8 @@ export const getLibraryStatsFromDb = async (): Promise<LibraryStats> => {
tx.executeSql(
getLibraryStatsQuery,
undefined,
(txObj, { rows }) => {
resolve((rows as any)._array[0]);
(txObj, { rows: { _array } }) => {
resolve(_array[0]);
},
txnErrorCallback,
);
@@ -76,8 +76,8 @@ export const getChaptersTotalCountFromDb = async (): Promise<LibraryStats> => {
tx.executeSql(
getChaptersTotalCountQuery,
undefined,
(txObj, { rows }) => {
resolve((rows as any)._array[0]);
(txObj, { rows: { _array } }) => {
resolve(_array[0]);
},
txnErrorCallback,
);
@@ -91,8 +91,8 @@ export const getChaptersReadCountFromDb = async (): Promise<LibraryStats> => {
tx.executeSql(
getChaptersReadCountQuery,
undefined,
(txObj, { rows }) => {
resolve((rows as any)._array[0]);
(txObj, { rows: { _array } }) => {
resolve(_array[0]);
},
txnErrorCallback,
);
@@ -106,8 +106,8 @@ export const getChaptersUnreadCountFromDb = async (): Promise<LibraryStats> => {
tx.executeSql(
getChaptersUnreadCountQuery,
undefined,
(txObj, { rows }) => {
resolve((rows as any)._array[0]);
(txObj, { rows: { _array } }) => {
resolve(_array[0]);
},
txnErrorCallback,
);
@@ -122,8 +122,8 @@ export const getChaptersDownloadedCountFromDb =
tx.executeSql(
getChaptersDownloadedCountQuery,
undefined,
(txObj, { rows }) => {
resolve((rows as any)._array[0]);
(txObj, { rows: { _array } }) => {
resolve(_array[0]);
},
txnErrorCallback,
);
@@ -137,11 +137,11 @@ export const getNovelGenresFromDb = async (): Promise<LibraryStats> => {
tx.executeSql(
getNovelGenresQuery,
undefined,
(txObj, { rows }) => {
(txObj, { rows: { _array } }) => {
let genres: string[] = [];
(rows as any)._array.forEach((item: { genres: string }) => {
const novelGenres = item.genres?.split(/\s*,\s*/);
_array.forEach((item: { genre: string }) => {
const novelGenres = item.genre?.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 }) => {
(txObj, { rows: { _array } }) => {
let status: string[] = [];
(rows as any)._array.forEach((item: { status: string }) => {
_array.forEach((item: { status: string }) => {
status.push(item.status);
});
+104
View File
@@ -0,0 +1,104 @@
/* 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),
),
);
+13 -16
View File
@@ -1,20 +1,17 @@
export const createCategoriesTableQuery = `
CREATE TABLE IF NOT EXISTS Category (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
sort INTEGER
);
`;
CREATE TABLE IF NOT EXISTS categories(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
lastUpdatedAt DATETIME DEFAULT CURRENT_TIMESTAMP,
sort INTEGER DEFAULT NULL
)
`;
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 createDefaultCategoryQuery =
'INSERT INTO categories (id, name) VALUES (1, "Default");';
export const createCategoryDefaultQuery =
'INSERT OR IGNORE INTO Category (id, name, sort) VALUES (1, "Default", 1)';
export const createCategorydIndexQuery =
'CREATE INDEX IF NOT EXISTS categoryIdIndex ON categories(id)';
export const createCategoryLocalQuery =
'INSERT OR IGNORE INTO Category (id, name, sort) VALUES (2, "Local", 2)';
export const addCategorySortColumnQuery =
'ALTER TABLE categories ADD COLUMN sort INTEGER DEFAULT NULL';
+30
View File
@@ -0,0 +1,30 @@
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,
};
-22
View File
@@ -1,22 +0,0 @@
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)
`;

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