Compare commits

...
199 Commits
Author SHA1 Message Date
seven332 0f15d82f16 Merge branch 'master' into order 2019-05-28 14:01:12 +08:00
seven332 54b6dd99a9 1.7.1 2019-05-27 23:03:47 +08:00
seven332 6389b09d64 Fix thumb url 2019-05-27 22:57:00 +08:00
seven332 998d87b206 1.7.0 2019-05-25 19:32:59 +08:00
seven332 0b6a9da664 Update libraries 2019-05-25 19:04:43 +08:00
seven332 6086175ef6 Disable view transition in GalleryDetailScene 2019-05-25 15:31:38 +08:00
seven332 5e690c6983 Android Studio 3.4.1 2019-05-23 14:18:49 +08:00
seven332 a898f289fe Remove default text from gallery detail tip 2019-05-14 13:19:30 +08:00
seven332 a215389b98 Add loading more comments 2019-05-11 22:58:57 +08:00
seven332 60af7937c7 Add GalleryCommentList to hold hasMore 2019-05-11 17:59:25 +08:00
seven332 4064510b14 Implement editing comment 2019-05-08 11:29:59 +08:00
seven332 c9146324f8 Use ThemeOverlay instead of Theme for views 2019-05-07 22:44:32 +08:00
seven332 bd7c806ad9 Check text to get comment actions 2019-05-07 21:00:07 +08:00
seven332 efe7d4757a Show empty page tip if getting empty html string 2019-05-07 19:31:39 +08:00
seven332 3554fe1188 Add release link to readme 2019-05-07 16:46:26 +08:00
seven332 06357b37d6 Update libraries 2019-05-07 14:28:26 +08:00
seven332 ae2443fbf0 Always save crash file if onCreate() is not done 2019-05-07 14:24:12 +08:00
seven332 19403975ba Add go to and refresh to FavouriteScene 2019-05-06 23:10:11 +08:00
seven332 73e91d440d Merge branch 'master' into order 2019-04-22 22:30:11 +08:00
seven332 5087311b26 Add ReLinker dependency 2019-04-22 22:08:39 +08:00
seven332 de854ac7ac Ignore gone fabs in FabLayout 2019-04-19 16:20:15 +08:00
seven332 40c0506f6e Android Studio 3.4.0 2019-04-19 13:38:38 +08:00
seven332 7beb49e599 Remove wrong RecyclerView.hasFixedSize() 2019-04-16 20:40:05 +08:00
seven332 7c5486aa08 Fix RecyclerView drag and drop 2019-04-16 20:39:14 +08:00
seven332 120124101a Fix spanish translation file 2019-04-07 14:46:39 +08:00
seven332 c286d2c543 Merge pull request #592 from scese250/patch-6
Updated Spanish translation
2019-04-07 14:45:03 +08:00
scese250 5f411661e9 Updated Spanish translation
Some options weren't transladated. And minor fixes.
2019-04-06 02:11:09 -04:00
seven332 981a7c7851 Apply fullscreen for phone with notch 2019-04-06 12:43:33 +08:00
seven332 40bc23a144 New version name 2019-04-04 10:50:55 +08:00
seven332 e75fe4667e Adjust option order 2019-04-04 10:48:50 +08:00
seven332 43b169371d Update firebase-core 2019-04-04 10:43:58 +08:00
seven332 311dabba17 Throw ParseException if no gallery found 2019-04-04 10:20:20 +08:00
seven332 c7d7ce8225 1.6.3 2019-04-03 20:16:25 +08:00
seven332 4b1c6ac917 Fix parsing title 2019-04-03 19:56:51 +08:00
seven332 24612b7d14 Fix parsing thumbnail url 2019-04-03 19:37:55 +08:00
seven332 3530faabf1 Fix GalleryListParser 2019-04-03 19:13:08 +08:00
seven332 0f3a95575c Fix spanish translation file 2019-04-01 19:44:29 +08:00
seven332 0334833bf8 Merge pull request #581 from scese250/patch-5
Updated Spanish translation
2019-04-01 19:35:23 +08:00
scese250 1b1d94a98d Updated Spanish translation
Thanks for continuing updating the app.
2019-04-01 03:09:07 -04:00
seven332 dfa1de9745 Close #578, search in subscriptions if subscriptions are shown 2019-03-31 01:45:19 +08:00
seven332 84fe397c18 1.6.2 2019-03-29 12:09:31 +08:00
seven332 07b1b5034d Check mSearchLayout null in onUpdateUrlBuilder() 2019-03-29 12:08:39 +08:00
seven332 7f73eb0bd4 Add device_language as user property 2019-03-29 11:01:49 +08:00
seven332 f129ac649d Don't quote quoted keyword 2019-03-28 18:33:38 +08:00
seven332 e9d5569e81 Escape quotation marks 2019-03-28 18:27:38 +08:00
seven332 db31e5c740 Wrap keywords with quotation marks if they are tags 2019-03-28 18:22:02 +08:00
seven332 c83fcee21a Merge pull request #574 from UShimamura/master
Update German, French and Japanese translations
2019-03-27 16:02:40 +08:00
UShimamura 6270e1695d Fix another typo 2019-03-27 11:15:36 +08:00
UShimamura a8b11c8e21 Fix a typo 2019-03-27 11:02:16 +08:00
UShimamura a12b2c4eac Add contributers for Japanese translations 2019-03-27 11:00:39 +08:00
UShimamura 31412b78cf Remove duplicate translations 2019-03-26 23:36:39 +08:00
UShimamura 4a986a8428 Remove duplicate translations 2019-03-26 23:35:25 +08:00
UShimamura d58b2ba03e Update Japanese translations 2019-03-26 23:34:05 +08:00
UShimamura 176c64330f Update French translations 2019-03-26 23:32:40 +08:00
UShimamura 342ed0c709 Update German translations 2019-03-26 23:31:05 +08:00
UShimamura d8ee689db7 Update French translations 2019-03-26 22:56:52 +08:00
UShimamura 229e429809 Remove old translations 2019-03-26 22:30:47 +08:00
seven332 f5128cd17a Add latest release preference 2019-03-26 17:05:21 +08:00
UShimamura 5e5a736f1c Update Japanese translations 2019-03-25 23:42:53 +08:00
seven332 1ec3681b7c Add @string/search_sp_suffix for some languages 2019-03-25 23:02:07 +08:00
seven332 67f9b6cb83 Remove useless analytics reporting 2019-03-25 13:58:56 +08:00
seven332 58ac39cf2c Filter is back 2019-03-25 13:34:24 +08:00
seven332 3cd4fc7ce9 Classify EhFilter 2019-03-22 14:46:15 +08:00
seven332 d731719f1c Add readonly FilterActivity 2019-03-22 14:36:35 +08:00
seven332 be0c394de1 1.6.1 2019-03-22 13:23:14 +08:00
seven332 a739300260 Use mEndPage to restrict mPages instead of mPages itself 2019-03-22 13:16:55 +08:00
seven332 da9940d581 Merge ContentLayout.setPages() to onGetPageData() 2019-03-22 13:12:52 +08:00
seven332 a2523aae75 Don't make mEndPage beyond mPages 2019-03-22 13:02:26 +08:00
seven332 3ae3602671 Cancel footer refreshing if can't get next page 2019-03-22 12:36:03 +08:00
seven332 6350fc1ece Fix parsing next page 2019-03-22 12:27:25 +08:00
seven332 29a27cbe00 Fix null FavouriteStatusRouter 2019-03-22 12:21:56 +08:00
seven332 5fc0fb997a 1.6.0 2019-03-22 02:09:29 +08:00
seven332 aa01ddd594 Disable ChangeImageTransform on Android 5 2019-03-22 02:08:05 +08:00
seven332 8774268adf Check map null 2019-03-22 01:27:02 +08:00
seven332 265cbd0df5 Add GalleryInfoContentHelper to hold a data map 2019-03-22 01:19:40 +08:00
seven332 82cdfeb1b2 Remove gallery from local favourites in CommonOperations.removeFromFavorites() 2019-03-22 01:17:49 +08:00
seven332 71dd9d3693 Remove download listener and favourite listener in GalleryListScene.onDestroy() 2019-03-21 23:57:14 +08:00
seven332 fd9f1bd219 Add FavouriteStatusRouter to forward the favourite status 2019-03-21 23:17:09 +08:00
seven332 956b7455a3 Notify download status on GalleryListScene 2019-03-21 21:41:45 +08:00
seven332 b3c855a5dc Enrich gallery list item menu 2019-03-21 21:26:36 +08:00
seven332 06e624a1e3 Remove EhFilter 2019-03-21 20:38:21 +08:00
seven332 871c0a43ca Add disable default filters options 2019-03-21 20:19:00 +08:00
seven332 6775246d4c Add login tip for EHentai Setting and My Tags 2019-03-21 19:16:14 +08:00
seven332 a0b0109424 Switch to subscription search in subscription screen 2019-03-21 18:48:27 +08:00
seven332 c5566aa5e8 Add subscription search 2019-03-21 18:31:32 +08:00
seven332 1d70572d92 Add arrow icon callback on MyTagsActivity 2019-03-21 16:47:48 +08:00
seven332 5dc6446d64 Close #561, add launch page selector 2019-03-21 16:44:42 +08:00
seven332 13eb9e2f16 Add all cookie entries to CookieStore in WebViewSignIn 2019-03-21 15:47:09 +08:00
seven332 7e1e4a0f57 Only show tips for subscription if no watched tags 2019-03-21 15:30:33 +08:00
seven332 c0933eb8f0 Add tips for subscription 2019-03-21 15:14:31 +08:00
seven332 a0e6a847ab Remove help route 2019-03-21 15:07:26 +08:00
seven332 23a7053597 Adjust EhUrl fields 2019-03-21 14:36:31 +08:00
seven332 d463cf2295 Close #559, add subscription 2019-03-21 14:33:28 +08:00
seven332 94db37c899 Hide IME after searching 2019-03-21 13:08:46 +08:00
seven332 94f6eecbc7 Add the entry of My Tags 2019-03-21 12:57:03 +08:00
seven332 c0f20ca975 Always apply Name, Tags and Note on favourite search 2019-03-21 10:06:13 +08:00
seven332 749f2610af Use switch string 2019-03-20 20:31:46 +08:00
seven332 a2a6422917 Parse page from and page to from url 2019-03-20 20:25:00 +08:00
seven332 df72243bb6 Add page from and page to 2019-03-20 19:00:38 +08:00
seven332 50c7a23566 Fix description about show_jpn_title and show_gallery_pages 2019-03-20 14:59:02 +08:00
seven332 1cbb725920 Add nextPage field to avoid require duplicate page 2019-03-20 14:30:49 +08:00
seven332 8b76eaa740 Remove duplicate galleries 2019-03-20 13:43:25 +08:00
seven332 65f320f8f7 Close #550, add language pattern for Japanese title 2019-03-20 11:07:18 +08:00
seven332 a7e4a2cd61 1.5.0 2019-03-19 23:32:13 +08:00
seven332 88baeeb335 Revert "Show pages if it's available"
This reverts commit 08d1ef8
2019-03-19 23:21:05 +08:00
seven332 00289d106d Update EhDns 2019-03-19 23:14:33 +08:00
seven332 08d1ef87d4 Show pages if it's available 2019-03-19 23:04:34 +08:00
seven332 388d507257 Parsing GalleryInfo.rated 2019-03-19 23:03:51 +08:00
seven332 89209a3c44 Don't call API if all data is got 2019-03-19 23:02:08 +08:00
seven332 9208c53d4f Fix gallery list url builder 2019-03-19 22:37:37 +08:00
seven332 defa670a26 Add missing generateSLang() 2019-03-19 21:36:16 +08:00
seven332 2ec229c8ef Fix parsing popular 2019-03-19 21:22:43 +08:00
seven332 e5df5714de Don't show favourited icon on FavouritesScene 2019-03-19 21:04:29 +08:00
seven332 5b8e031e50 Add GalleryListParserTest 2019-03-19 20:57:45 +08:00
seven332 b0ccfe4793 Fix parse category of gallery detail 2019-03-19 20:54:57 +08:00
seven332 b101ae142d Fix parsing gallery list 2019-03-19 20:51:19 +08:00
seven332 c165c9071d Enable builtin hosts if the country is CN 2019-03-15 15:45:14 +08:00
seven332 7fc9ef9e1f Android Studio 3.3.2 2019-03-15 15:44:45 +08:00
seven332 c4514589c0 Fix France name 2019-03-13 13:35:34 +08:00
seven332 0305c541aa Fix Thai translations 2019-03-13 13:03:45 +08:00
seven332 7631e3b4f9 Apply Thai translations 2019-03-13 13:02:09 +08:00
seven332 350d846a39 Merge pull request #544 from maxjame5432/master
Add Thai langauge
2019-03-13 12:38:29 +08:00
maxjame5432 c119562c16 First commit 2019-03-13 01:24:06 +07:00
Mekokung 37de170729 Add Thai language
Add Thai language
2019-03-12 20:44:34 +07:00
Mekokung 8d992d737e Merge pull request #1 from maxjame5432/thai-lang
Add Thai language
2019-03-12 20:40:24 +07:00
Mekokung 81434a682f Add Thai Language
Add thai language in your app
2019-03-12 17:10:46 +07:00
Mekokung b3a446ffcd Add thai language
add thai language translation
2019-03-12 16:32:52 +07:00
seven332 e659ba91b4 Fix English translations
"Swipe to left" or "Swipe left"?
2019-03-11 22:24:41 +08:00
seven332 7866722ec4 Fix ripple clipping in pre-L devices 2019-03-05 14:44:28 +08:00
seven332 2a944f5e0a Adjust the center of circular reveal in gallery detail scene 2019-03-05 14:20:18 +08:00
seven332 34eccad8be Use AndroidX transition library 2019-03-05 12:39:48 +08:00
seven332 57a18b7215 Add warning about minors 2019-02-27 15:22:12 +08:00
seven332 6c253238ad Show an icon if the gallery is downloaded 2019-02-23 17:04:17 +08:00
seven332 c08068eeea Show heart icon if the gallery is favourited 2019-02-23 16:23:14 +08:00
seven332 303c51f93d Remove "No more new SkipHathKey" tip
It's confusing.
2019-02-23 00:40:23 +08:00
seven332 e1a88cdfe3 1.4.2 2019-02-19 10:19:09 +08:00
seven332 6adad86bc5 Revert okhttp to 3.12.1
okhttp 3.13.1 doesn't support Android 4.x
2019-02-19 10:18:44 +08:00
seven332 0dbb030663 1.4.1 2019-02-18 22:05:28 +08:00
seven332 169f4c3eb8 Add operation records analytics 2019-02-18 22:03:36 +08:00
seven332 dd700a0f2d Add Referer and Origin to HTTP request 2019-02-17 14:31:36 +08:00
seven332 77a2875b9f Remove EhConfig from EhRequestBuilder 2019-02-17 12:59:03 +08:00
seven332 fd5f6c3466 Use api to get page image url 2019-02-16 15:07:16 +08:00
seven332 3380389453 Remove useless exception is EhRequestBuilder 2019-02-16 15:06:04 +08:00
seven332 fc9270d48c Thrown exception if no test resource 2019-02-16 15:03:35 +08:00
seven332 a3aa4ba17f Add GalleryPageApiParser 2019-02-16 15:02:40 +08:00
seven332 cca6e2a72e Get show key from gallery page html 2019-02-16 15:01:37 +08:00
seven332 cc9205700c EhException supports cause now 2019-02-16 15:00:03 +08:00
seven332 ced2139703 Update libraries 2019-02-16 12:08:17 +08:00
seven332 2ad5edfe3b Merge pull request #528 from lilymaniac/l10n-ko
Update Korean localization
2019-02-14 10:59:29 +08:00
lilymaniac b6e822e6d1 Update Korean localization
Catch up to commit 4d4571aa30 ("Remove android-chinese-string plugin").
2019-02-13 15:19:22 +09:00
seven332 4d4571aa30 Remove android-chinese-string plugin 2019-02-12 23:08:06 +08:00
seven332 c326adfe48 Remove image cache after refreshing 2019-02-11 23:23:46 +08:00
seven332 b8cb9f66b6 Update libraries
Remove GLView ColorMatrix support
2019-02-11 23:16:55 +08:00
seven332 c5a6526171 Add saving crash log 2019-02-11 18:14:35 +08:00
seven332 6d72349ee7 Fix missing Firebase gradle plugin 2019-02-11 11:47:35 +08:00
seven332 334c248acb Use classloader in the SavedState of TaskPreference 2019-02-10 13:42:20 +08:00
seven332 41ef8d2374 Catch all exception when saving tag translations 2019-02-10 13:07:02 +08:00
seven332 fef42c0832 Fix wrong widget in xml 2019-02-09 19:46:39 +08:00
seven332 8ffd959659 Fix gallery detail rating bar 2019-02-09 19:41:56 +08:00
seven332 5c0772e5b9 Update android-advancedrecyclerview 2019-02-09 19:29:49 +08:00
seven332 0afb78da3f Use AndroidX 2019-02-09 19:25:15 +08:00
seven332 04a5c762dd Update libraries 2019-02-09 17:44:08 +08:00
seven332 1eaad6f669 Support proxy 2019-02-03 19:19:50 +08:00
seven332 beeb083cb3 Avoid MalformedURLException in ChromeRequestBuilder 2019-02-03 18:59:13 +08:00
seven332 ce5655def6 Fix image transition 2019-02-02 15:16:51 +08:00
seven332 f1c446f7de Adjust description about chinese tag translations 2019-01-31 12:00:13 +08:00
seven332 ca6b2c6917 Apply CN tag translations to HK and TW 2019-01-31 11:45:17 +08:00
seven332 95bb75c9b4 Add tag translations source 2019-01-30 15:37:55 +08:00
seven332 073934a2a0 Disable google-services plugin if can't find google-services.json
It fix compiling without google-services.json.
2019-01-27 23:24:25 +08:00
seven332 1edb8941ee Clear EhTagDatabase if it's not available 2019-01-27 14:17:55 +08:00
seven332 81195726d5 Put tag translation metadata to xml resources 2019-01-27 13:55:09 +08:00
seven332 bc2b21b0f5 1.4.0 2019-01-26 15:56:19 +08:00
seven332 ec132440e7 Close #514, extend the duration of SnackBar 2019-01-24 22:50:05 +08:00
seven332 9d49973504 Add new downloaded gallery to history 2019-01-22 22:23:07 +08:00
seven332 016ec23fbd Fix rating if the gallery has been rated by the user 2019-01-21 20:17:27 +08:00
seven332 59d141fc8e Improve ChromeRequestBuilder
Add request header Accept and Accept-Language.
Update User-Agent.
2019-01-21 16:46:41 +08:00
Tsuki 3d3c3a9273 Update License year 2019-01-21 12:19:41 +08:00
seven332 c580938806 Support tag translations 2019-01-20 00:49:54 +08:00
seven332 3904406d74 Add IoThreadPoolExecutor 2019-01-19 14:05:33 +08:00
seven332 879b8fa50a Support downloading galleries from FavoritesScene 2019-01-17 18:41:49 +08:00
seven332 7228736c95 Avoid crash in unbindService() 2019-01-16 18:46:47 +08:00
seven332 e8eb126135 Catch SQLException in SearchDatabase 2019-01-16 18:38:31 +08:00
seven332 0eb86e37e6 Android Studio 3.3.0 2019-01-16 18:20:12 +08:00
seven332 eff2ed94fe Update GLView
Support OpenGL ES 1.x
2019-01-14 19:38:37 +08:00
seven332 fb2011a408 Adjust thumbnail aspect 2019-01-14 15:32:13 +08:00
seven332 a442578927 Update okhttp 2019-01-14 00:56:11 +08:00
seven332 673735ab2e Update a7zip 2019-01-14 00:55:06 +08:00
seven332 f1bab7e3d4 Add FixedThumb to fix thumbnail size 2019-01-13 02:38:48 +08:00
seven332 1d5b26ee51 Update a7zip 2019-01-10 14:02:01 +08:00
seven332 a1a82b0ce9 Restrict GalleryDetailUrlParser token to 10 characters 2019-01-10 10:34:35 +08:00
seven332 5b961d71b8 Block drawer gesture if it's on ScrollView 2019-01-07 13:01:44 +08:00
seven332 0353c1cebb Update DrawerLayout 2019-01-07 11:49:07 +08:00
seven332 7b07bdc51f 1.3.5 2019-01-05 14:56:25 +08:00
seven332 cf1ac32e17 Add android.max_aspect 2019-01-05 13:37:24 +08:00
seven332 bb28dd97cc Ignore IllegalArgumentException in URLDecoder.decode() 2019-01-05 13:24:42 +08:00
seven332 a33bd63e6e Safe number string parsing 2019-01-05 13:13:37 +08:00
seven332 a0b786b2a6 Avoid NumberFormatException in Html.getHtmlColor() 2019-01-05 12:38:43 +08:00
seven332 9dd39412d4 Update a7zip 2019-01-04 21:55:08 +08:00
seven332 3fdf9453ef Fix Pipe stuck 2019-01-04 21:48:33 +08:00
277 changed files with 7311 additions and 2529 deletions

No files matched your search

+8 -1
View File
@@ -33,6 +33,13 @@ Linux
The apk is in app\build\outputs\apk
# Download
[下载](https://github.com/seven332/EhViewer/releases)
[Download](https://github.com/seven332/EhViewer/releases)
# Thanks
本项目受到了诸多开源项目的帮助
@@ -57,7 +64,7 @@ Here is the libraries
# License
Copyright (C) 2014-2016 Hippo Seven
Copyright (C) 2014-2019 Hippo Seven
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
+24 -22
View File
@@ -1,7 +1,9 @@
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric'
apply plugin: 'android-chinese-string'
if (file('google-services.json').exists()) {
apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric'
}
android {
compileSdkVersion 28
@@ -10,11 +12,12 @@ android {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 28
versionCode 91
versionName "1.3.4"
versionCode 102
versionName "1.7.1-order"
vectorDrawables.useSupportLibrary = true
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW",
"es", "ja", "ko", "fr", "de"
"es", "ja", "ko", "fr", "de", "th"
testOptions.unitTests.includeAndroidResources = true
ndk {
abiFilters "armeabi-v7a", "x86"
}
@@ -66,52 +69,51 @@ clean {
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "com.android.support:appcompat-v7:$supportLibrary"
implementation "com.android.support:cardview-v7:$supportLibrary"
implementation "com.android.support:design:$supportLibrary"
implementation 'com.google.firebase:firebase-core:16.0.6'
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.8'
implementation 'com.github.seven332:a7zip:4a484317b0'
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
implementation 'com.getkeepsafe.relinker:relinker:1.3.1'
implementation 'com.github.amlcurran.showcaseview:library:5.4.3'
implementation 'com.github.seven332.a7zip:extract-lite:d4ddec5793'
implementation 'com.github.seven332:android-recaptcha:2bbb3459a8'
implementation 'com.github.seven332:android-resource:0.1.0'
implementation 'com.github.seven332:animator:0.1.0'
implementation 'com.github.seven332:beerbelly:0.1.4'
implementation 'com.github.seven332:conaco:0.1.5-eh'
implementation 'com.github.seven332:drawerlayout:0.2.1'
implementation 'com.github.seven332:drawerlayout:ea2bb388f0'
implementation 'com.github.seven332:easyrecyclerview:0.1.1'
implementation 'com.github.seven332:glgallery:0.1.2'
implementation 'com.github.seven332:glview:0.1.0'
implementation 'com.github.seven332:glview-image:0.1.0'
implementation 'com.github.seven332:hotspot:0.1.0'
implementation 'com.github.seven332:image:0.1.12'
implementation 'com.github.seven332:okhttp:3.5.0'
implementation 'com.github.seven332:refreshlayout:0.1.0'
implementation 'com.github.seven332:ripple:0.1.2'
implementation 'com.github.seven332:streampipe:0.1.0'
implementation 'com.github.seven332:tuxiang:0.1.2'
implementation 'com.github.seven332:tuxiang:0.1.6'
implementation 'com.github.seven332:unifile:9ec57bcd8f'
implementation 'com.github.seven332:yorozuya:0.1.2'
implementation 'com.github.seven332:yorozuya-thread:0.1.1'
implementation 'com.github.seven332:yorozuya-collect:0.1.4'
implementation 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.11.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:1.0.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.3'
implementation 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
implementation 'org.greenrobot:greendao:2.2.1'
implementation 'org.jsoup:jsoup:1.11.3'
testImplementation 'junit:junit:4.12'
testImplementation 'org.robolectric:robolectric:3.8'
testImplementation 'org.robolectric:robolectric:4.2.1'
testImplementation 'org.jooq:joor:0.9.6'
}
configurations.all {
resolutionStrategy {
force 'com.github.seven332:glgallery:bb2a43fdd5'
force 'com.github.seven332:glview:cc3f18d1b2'
force 'com.github.seven332:glview-image:69930e924e'
force 'com.github.seven332:glgallery:25893283ca'
force 'com.github.seven332:glview:ba6aee61d7'
force 'com.github.seven332:glview-image:68d94b0fc2'
force 'com.github.seven332:image:09b43c0c68'
exclude group: 'com.github.seven332', module: 'okhttp'
exclude group: 'com.squareup.okio', module: 'okio'
}
}
+9 -1
View File
@@ -39,6 +39,8 @@
android:largeHeap="true"
android:networkSecurityConfig="@xml/network_security_config">
<meta-data android:name="android.max_aspect" android:value="2.1"/>
<activity
android:name="com.hippo.ehviewer.ui.MainActivity"
android:configChanges="screenSize|uiMode"
@@ -168,6 +170,12 @@
android:theme="@style/AppTheme.Toolbar"
android:label="@string/u_config"/>
<activity
android:name="com.hippo.ehviewer.ui.MyTagsActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/my_tags"/>
<activity
android:name="com.hippo.ehviewer.ui.HostsActivity"
android:configChanges="screenSize|uiMode"
@@ -193,7 +201,7 @@
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:name="com.hippo.content.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths"/>
</provider>
@@ -16,39 +16,70 @@
package com.hippo.app;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.CallSuper;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatCallback;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import androidx.annotation.CallSuper;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatCallback;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.widget.VectorEnabledTintResources;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NavUtils;
import androidx.core.app.TaskStackBuilder;
public abstract class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider {
TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider {
private AppCompatDelegate mDelegate;
private int mThemeId = 0;
private Resources mResources;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
final AppCompatDelegate delegate = getDelegate();
delegate.installViewFactory();
delegate.onCreate(savedInstanceState);
if (delegate.applyDayNight() && mThemeId != 0) {
// If DayNight has been applied, we need to re-apply the theme for
// the changes to take effect. On API 23+, we should bypass
// setTheme(), which will no-op if the theme ID is identical to the
// current theme ID.
if (Build.VERSION.SDK_INT >= 23) {
onApplyThemeResource(getTheme(), mThemeId, false);
} else {
setTheme(mThemeId);
}
}
super.onCreate(savedInstanceState);
}
@Override
public void setTheme(@StyleRes final int resid) {
super.setTheme(resid);
// Keep hold of the theme id so that we can re-set it later if needed
mThemeId = resid;
}
@Override
protected void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
@@ -68,26 +99,25 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
}
/**
* Set a {@link android.widget.Toolbar Toolbar} to act as the {@link android.support.v7.app.ActionBar} for this
* Activity window.
* Set a {@link android.widget.Toolbar Toolbar} to act as the
* {@link androidx.appcompat.app.ActionBar} for this Activity window.
*
* <p>When set to a non-null value the {@link #getActionBar()} method will return
* an {@link android.support.v7.app.ActionBar} object that can be used to control the given toolbar as if it were
* a traditional window decor action bar. The toolbar's menu will be populated with the
* Activity's options menu and the navigation button will be wired through the standard
* {@link android.R.id#home home} menu select action.</p>
* an {@link androidx.appcompat.app.ActionBar} object that can be used to control the given
* toolbar as if it were a traditional window decor action bar. The toolbar's menu will be
* populated with the Activity's options menu and the navigation button will be wired through
* the standard {@link android.R.id#home home} menu select action.</p>
*
* <p>In order to use a Toolbar within the Activity's window content the application
* must not request the window feature
* {@link android.view.Window#FEATURE_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p>
*
* @param toolbar Toolbar to set as the Activity's action bar
* @param toolbar Toolbar to set as the Activity's action bar, or {@code null} to clear it
*/
public void setSupportActionBar(@Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
@NonNull
@Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
@@ -117,6 +147,24 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
if (mResources != null) {
// The real (and thus managed) resources object was already updated
// by ResourcesManager, so pull the current metrics from there.
final DisplayMetrics newMetrics = super.getResources().getDisplayMetrics();
mResources.updateConfiguration(newConfig, newMetrics);
}
}
@Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
@Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
}
@Override
@@ -125,10 +173,10 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
getDelegate().onStop();
}
@SuppressWarnings("TypeParameterUnusedInFormals")
@Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
public <T extends View> T findViewById(@IdRes int id) {
return getDelegate().findViewById(id);
}
@Override
@@ -139,7 +187,7 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
final ActionBar ab = getSupportActionBar();
if (item.getItemId() == android.R.id.home && ab != null &&
(ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
(ab.getDisplayOptions() & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
return onSupportNavigateUp();
}
return false;
@@ -165,7 +213,7 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
* </p>
*
* @param featureId The desired feature as defined in
* {@link android.view.Window} or {@link android.support.v4.view.WindowCompat}.
* {@link android.view.Window} or {@link androidx.core.view.WindowCompat}.
* @return Returns true if the requested feature is supported and now enabled.
*
* @see android.app.Activity#requestWindowFeature
@@ -192,7 +240,7 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
*/
@Override
@CallSuper
public void onSupportActionModeStarted(ActionMode mode) {
public void onSupportActionModeStarted(@NonNull ActionMode mode) {
}
/**
@@ -203,7 +251,7 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
*/
@Override
@CallSuper
public void onSupportActionModeFinished(ActionMode mode) {
public void onSupportActionModeFinished(@NonNull ActionMode mode) {
}
/**
@@ -217,14 +265,49 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
*/
@Nullable
@Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
public ActionMode onWindowStartingSupportActionMode(@NonNull ActionMode.Callback callback) {
return null;
}
public ActionMode startSupportActionMode(ActionMode.Callback callback) {
/**
* Start an action mode.
*
* @param callback Callback that will manage lifecycle events for this context mode
* @return The ContextMode that was started, or null if it was canceled
*/
@Nullable
public ActionMode startSupportActionMode(@NonNull ActionMode.Callback callback) {
return getDelegate().startSupportActionMode(callback);
}
/**
* @deprecated Progress bars are no longer provided in AppCompat.
*/
@Deprecated
public void setSupportProgressBarVisibility(boolean visible) {
}
/**
* @deprecated Progress bars are no longer provided in AppCompat.
*/
@Deprecated
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
}
/**
* @deprecated Progress bars are no longer provided in AppCompat.
*/
@Deprecated
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
}
/**
* @deprecated Progress bars are no longer provided in AppCompat.
*/
@Deprecated
public void setSupportProgress(int progress) {
}
/**
* Support version of {@link #onCreateNavigateUpTaskStack(android.app.TaskStackBuilder)}.
* This method will be called on all platform versions.
@@ -233,7 +316,7 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
* a different task.
*
* <p>The default implementation of this method adds the parent chain of this activity
* as specified in the manifest to the supplied {@link android.support.v4.app.TaskStackBuilder}. Applications
* as specified in the manifest to the supplied {@link androidx.core.app.TaskStackBuilder}. Applications
* may choose to override this method to construct the desired task stack in a different
* way.</p>
*
@@ -243,12 +326,12 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
*
* <p>Applications that wish to supply extra Intent parameters to the parent stack defined
* by the manifest should override
* {@link #onPrepareSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)}.</p>
* {@link #onPrepareSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)}.</p>
*
* @param builder An empty TaskStackBuilder - the application should add intents representing
* the desired task stack
*/
public void onCreateSupportNavigateUpTaskStack(TaskStackBuilder builder) {
public void onCreateSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) {
builder.addParentStack(this);
}
@@ -259,15 +342,15 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
* Prepare the synthetic task stack that will be generated during Up navigation
* from a different task.
*
* <p>This method receives the {@link android.support.v4.app.TaskStackBuilder} with the constructed series of
* Intents as generated by {@link #onCreateSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)}.
* <p>This method receives the {@link androidx.core.app.TaskStackBuilder} with the constructed series of
* Intents as generated by {@link #onCreateSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)}.
* If any extra data should be added to these intents before launching the new task,
* the application should override this method and add that data here.</p>
*
* @param builder A TaskStackBuilder that has been populated with Intents by
* onCreateNavigateUpTaskStack.
*/
public void onPrepareSupportNavigateUpTaskStack(TaskStackBuilder builder) {
public void onPrepareSupportNavigateUpTaskStack(@NonNull TaskStackBuilder builder) {
}
/**
@@ -278,7 +361,7 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
* default Up navigation will be handled automatically. See
* {@link #getSupportParentActivityIntent()} for how to specify the parent. If any activity
* along the parent chain requires extra Intent arguments, the Activity subclass
* should override the method {@link #onPrepareSupportNavigateUpTaskStack(android.support.v4.app.TaskStackBuilder)}
* should override the method {@link #onPrepareSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)}
* to supply those arguments.</p>
*
* <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and
@@ -286,7 +369,7 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
* <a href="{@docRoot}design/patterns/navigation.html">Navigation</a> from the design guide
* for more information about navigating within your app.</p>
*
* <p>See the {@link android.support.v4.app.TaskStackBuilder} class and the Activity methods
* <p>See the {@link androidx.core.app.TaskStackBuilder} class and the Activity methods
* {@link #getSupportParentActivityIntent()}, {@link #supportShouldUpRecreateTask(android.content.Intent)}, and
* {@link #supportNavigateUpTo(android.content.Intent)} for help implementing custom Up navigation.</p>
*
@@ -322,15 +405,15 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
/**
* Obtain an {@link android.content.Intent} that will launch an explicit target activity
* specified by sourceActivity's {@link android.support.v4.app.NavUtils#PARENT_ACTIVITY} &lt;meta-data&gt;
* specified by sourceActivity's {@link androidx.core.app.NavUtils#PARENT_ACTIVITY} &lt;meta-data&gt;
* element in the application's manifest. If the device is running
* Jellybean or newer, the android:parentActivityName attribute will be preferred
* if it is present.
*
* @return a new Intent targeting the defined parent activity of sourceActivity
*/
@Override
@Nullable
@Override
public Intent getSupportParentActivityIntent() {
return NavUtils.getParentActivityIntent(this);
}
@@ -342,13 +425,13 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
* <p>If this method returns false the app can trivially call
* {@link #supportNavigateUpTo(android.content.Intent)} using the same parameters to correctly perform
* up navigation. If this method returns false, the app should synthesize a new task stack
* by using {@link android.support.v4.app.TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
* by using {@link androidx.core.app.TaskStackBuilder} or another similar mechanism to perform up navigation.</p>
*
* @param targetIntent An intent representing the target destination for up navigation
* @return true if navigating up should recreate a new task stack, false if the same task
* should be used for the destination
*/
public boolean supportShouldUpRecreateTask(Intent targetIntent) {
public boolean supportShouldUpRecreateTask(@NonNull Intent targetIntent) {
return NavUtils.shouldUpRecreateTask(this, targetIntent);
}
@@ -364,7 +447,7 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
*
* @param upIntent An intent representing the target destination for up navigation
*/
public void supportNavigateUpTo(Intent upIntent) {
public void supportNavigateUpTo(@NonNull Intent upIntent) {
NavUtils.navigateUpTo(this, upIntent);
}
@@ -374,13 +457,114 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity imp
return getDelegate().getDrawerToggleDelegate();
}
/**
* {@inheritDoc}
*
* <p>Please note: AppCompat uses its own feature id for the action bar:
* {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p>
*/
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
return super.onMenuOpened(featureId, menu);
}
/**
* {@inheritDoc}
*
* <p>Please note: AppCompat uses its own feature id for the action bar:
* {@link AppCompatDelegate#FEATURE_SUPPORT_ACTION_BAR FEATURE_SUPPORT_ACTION_BAR}.</p>
*/
@Override
public void onPanelClosed(int featureId, Menu menu) {
super.onPanelClosed(featureId, menu);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getDelegate().onSaveInstanceState(outState);
}
/**
* @return The {@link AppCompatDelegate} being used by this Activity.
*/
@NonNull
public AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, this);
}
return mDelegate;
}
@SuppressLint("RestrictedApi")
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// Let support action bars open menus in response to the menu key prioritized over
// the window handling it
final int keyCode = event.getKeyCode();
final ActionBar actionBar = getSupportActionBar();
if (keyCode == KeyEvent.KEYCODE_MENU
&& actionBar != null && actionBar.onMenuKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
@SuppressLint("RestrictedApi")
@Override
public Resources getResources() {
if (mResources == null && VectorEnabledTintResources.shouldBeUsed()) {
mResources = new VectorEnabledTintResources(this, super.getResources());
}
return mResources == null ? super.getResources() : mResources;
}
/**
* KeyEvents with non-default modifiers are not dispatched to menu's performShortcut in API 25
* or lower. Here, we check if the keypress corresponds to a menuitem's shortcut combination
* and perform the corresponding action.
*/
private boolean performMenuItemShortcut(int keycode, KeyEvent event) {
if (!(Build.VERSION.SDK_INT >= 26) && !event.isCtrlPressed()
&& !KeyEvent.metaStateHasNoModifiers(event.getMetaState())
&& event.getRepeatCount() == 0
&& !KeyEvent.isModifierKey(event.getKeyCode())) {
final Window currentWindow = getWindow();
if (currentWindow != null && currentWindow.getDecorView() != null) {
final View decorView = currentWindow.getDecorView();
if (decorView.dispatchKeyShortcutEvent(event)) {
return true;
}
}
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (performMenuItemShortcut(keyCode, event)) {
return true;
}
return super.onKeyDown(keyCode, event);
}
@SuppressLint("RestrictedApi")
@Override
public void openOptionsMenu() {
ActionBar actionBar = getSupportActionBar();
if (getWindow().hasFeature(Window.FEATURE_OPTIONS_PANEL)
&& (actionBar == null || !actionBar.openOptionsMenu())) {
super.openOptionsMenu();
}
}
@SuppressLint("RestrictedApi")
@Override
public void closeOptionsMenu() {
ActionBar actionBar = getSupportActionBar();
if (getWindow().hasFeature(Window.FEATURE_OPTIONS_PANEL)
&& (actionBar == null || !actionBar.closeOptionsMenu())) {
super.closeOptionsMenu();
}
}
}
@@ -18,12 +18,11 @@ package com.hippo.app;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.R;
public class CheckBoxDialogBuilder extends AlertDialog.Builder {
@@ -19,15 +19,14 @@ package com.hippo.app;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import com.google.android.material.textfield.TextInputLayout;
import com.hippo.ehviewer.R;
public class EditTextDialogBuilder extends AlertDialog.Builder implements EditText.OnEditorActionListener {
@@ -18,14 +18,13 @@ package com.hippo.app;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.R;
import com.hippo.yorozuya.ViewUtils;
@@ -18,7 +18,6 @@ package com.hippo.app;
import android.content.Context;
import android.preference.PreferenceActivity;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
@@ -27,6 +26,7 @@ import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.hippo.ehviewer.R;
import java.util.ArrayList;
import java.util.List;
@@ -21,7 +21,6 @@ import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
@@ -29,9 +28,8 @@ import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.R;
import java.text.NumberFormat;
/**
@@ -16,6 +16,9 @@
package com.hippo.content;
import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.START_TAG;
import android.content.ClipData;
import android.content.ContentProvider;
import android.content.ContentValues;
@@ -31,20 +34,15 @@ import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import org.xmlpull.v1.XmlPullParserException;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.START_TAG;
import org.xmlpull.v1.XmlPullParserException;
/**
* FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing
@@ -331,7 +329,7 @@ public class FileProvider extends ContentProvider {
};
private static final String
META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS";
META_DATA_FILE_PROVIDER_PATHS = "com.hippo.content.FILE_PROVIDER_PATHS";
private static final String TAG_ROOT_PATH = "root-path";
private static final String TAG_FILES_PATH = "files-path";
@@ -17,9 +17,8 @@
package com.hippo.drawable;
import android.graphics.Bitmap;
import android.support.annotation.Nullable;
import android.util.Log;
import androidx.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedHashSet;
@@ -23,8 +23,8 @@ import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.graphics.drawable.DrawableCompat;
import androidx.annotation.NonNull;
import androidx.core.graphics.drawable.DrawableCompat;
public class DrawableWrapper extends Drawable implements Drawable.Callback {
private Drawable mDrawable;
@@ -27,8 +27,7 @@ import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import androidx.annotation.ColorInt;
import com.hippo.ehviewer.R;
import com.hippo.yorozuya.MathUtils;
@@ -27,10 +27,10 @@ import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class TextDrawable extends Drawable {
@@ -17,9 +17,8 @@
package com.hippo.drawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.util.Log;
import androidx.annotation.NonNull;
import com.hippo.conaco.Conaco;
import com.hippo.conaco.ConacoTask;
import com.hippo.conaco.Unikery;
@@ -18,12 +18,15 @@ package com.hippo.ehviewer;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.hippo.scene.SceneFragment;
import java.util.Locale;
public final class Analytics {
private static final String DEVICE_LANGUAGE = "device_language";
private static FirebaseAnalytics analytics;
private Analytics() {}
@@ -31,6 +34,18 @@ public final class Analytics {
public static void start(Context context) {
analytics = FirebaseAnalytics.getInstance(context);
analytics.setUserId(Settings.getUserID());
Locale locale = Locale.getDefault();
String language = locale.getLanguage();
if (TextUtils.isEmpty(language)) {
language = "none";
}
String country = locale.getCountry();
if (!TextUtils.isEmpty(country)) {
language = language + "-" + country;
}
language = language.toLowerCase();
analytics.setUserProperty(DEVICE_LANGUAGE, language);
}
public static boolean isEnabled() {
@@ -18,13 +18,11 @@ package com.hippo.ehviewer;
import android.content.Context;
import android.os.Environment;
import android.support.annotation.Nullable;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -40,6 +38,7 @@ public class AppConfig {
private static final String PARSE_ERROR = "parse_error";
private static final String LOGCAT = "logcat";
private static final String DATA = "data";
private static final String CRASH = "crash";
private static Context sContext;
@@ -109,6 +108,11 @@ public class AppConfig {
return getDirInExternalAppDir(DATA);
}
@Nullable
public static File getExternalCrashDir() {
return getDirInExternalAppDir(CRASH);
}
@Nullable
public static File createExternalTempFile() {
return FileUtils.createTempFile(getExternalTempDir(), null);
@@ -156,4 +160,19 @@ public class AppConfig {
IOUtils.closeQuietly(os);
}
}
@Nullable
public static File getFilesDir(String name) {
File dir = sContext.getFilesDir();
if (dir == null) {
return null;
}
dir = new File(dir, name);
if (dir.isDirectory() || dir.mkdirs()) {
return dir;
} else {
return null;
}
}
}
@@ -0,0 +1,156 @@
/*
* Copyright 2019 Hippo Seven
*
* 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.
*/
package com.hippo.ehviewer;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Debug;
import androidx.annotation.NonNull;
import com.hippo.scene.StageActivity;
import com.hippo.util.PackageUtils;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.OSUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public final class Crash {
private Crash() {}
@NonNull
private static String avoidNull(String str) {
return null != str ? str : "null";
}
private static void collectInfo(Context context, FileWriter fw) throws IOException {
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = String.valueOf(pi.versionCode);
fw.write("======== PackageInfo ========\r\n");
fw.write("PackageName=");fw.write(pi.packageName);fw.write("\r\n");
fw.write("VersionName=");fw.write(versionName);fw.write("\r\n");
fw.write("VersionCode=");fw.write(versionCode);fw.write("\r\n");
String signature = PackageUtils.getSignature(context, pi.packageName);
fw.write("Signature=");fw.write(null != signature ? signature : "null");fw.write("\r\n");
fw.write("\r\n");
}
} catch (PackageManager.NameNotFoundException e) {
fw.write("======== PackageInfo ========\r\n");
fw.write("Can't get package information\r\n");
fw.write("\r\n");
}
// Runtime
String topActivityClazzName = "null";
String topSceneClazzName = "null";
try {
Activity topActivity = ((EhApplication) context.getApplicationContext()).getTopActivity();
if (null != topActivity) {
topActivityClazzName = topActivity.getClass().getName();
if (topActivity instanceof StageActivity) {
Class<?> clazz = ((StageActivity) topActivity).getTopSceneClass();
if (clazz != null) {
topSceneClazzName = clazz.getName();
}
}
}
} catch (Throwable e) {
// Ignore
}
fw.write("======== Runtime ========\r\n");
fw.write("TopActivity=");fw.write(avoidNull(topActivityClazzName));fw.write("\r\n");
fw.write("TopScene=");fw.write(avoidNull(topSceneClazzName));fw.write("\r\n");
fw.write("\r\n");
// Device info
fw.write("======== DeviceInfo ========\r\n");
fw.write("BOARD=");fw.write(Build.BOARD);fw.write("\r\n");
fw.write("BOOTLOADER=");fw.write(Build.BOOTLOADER);fw.write("\r\n");
fw.write("CPU_ABI=");fw.write(Build.CPU_ABI);fw.write("\r\n");
fw.write("CPU_ABI2=");fw.write(Build.CPU_ABI2);fw.write("\r\n");
fw.write("DEVICE=");fw.write(Build.DEVICE);fw.write("\r\n");
fw.write("DISPLAY=");fw.write(Build.DISPLAY);fw.write("\r\n");
fw.write("FINGERPRINT=");fw.write(Build.FINGERPRINT);fw.write("\r\n");
fw.write("HARDWARE=");fw.write(Build.HARDWARE);fw.write("\r\n");
fw.write("HOST=");fw.write(Build.HOST);fw.write("\r\n");
fw.write("ID=");fw.write(Build.ID);fw.write("\r\n");
fw.write("MANUFACTURER=");fw.write(Build.MANUFACTURER);fw.write("\r\n");
fw.write("MODEL=");fw.write(Build.MODEL);fw.write("\r\n");
fw.write("PRODUCT=");fw.write(Build.PRODUCT);fw.write("\r\n");
fw.write("RADIO=");fw.write(Build.getRadioVersion());fw.write("\r\n");
fw.write("SERIAL=");fw.write(Build.SERIAL);fw.write("\r\n");
fw.write("TAGS=");fw.write(Build.TAGS);fw.write("\r\n");
fw.write("TYPE=");fw.write(Build.TYPE);fw.write("\r\n");
fw.write("USER=");fw.write(Build.USER);fw.write("\r\n");
fw.write("CODENAME=");fw.write(Build.VERSION.CODENAME);fw.write("\r\n");
fw.write("INCREMENTAL=");fw.write(Build.VERSION.INCREMENTAL);fw.write("\r\n");
fw.write("RELEASE=");fw.write(Build.VERSION.RELEASE);fw.write("\r\n");
fw.write("SDK=");fw.write(Integer.toString(Build.VERSION.SDK_INT));fw.write("\r\n");
fw.write("MEMORY=");fw.write(
FileUtils.humanReadableByteCount(OSUtils.getAppAllocatedMemory(), false));fw.write("\r\n");
fw.write("MEMORY_NATIVE=");fw.write(FileUtils.humanReadableByteCount(Debug.getNativeHeapAllocatedSize(), false));fw.write("\r\n");
fw.write("MEMORY_MAX=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getAppMaxMemory(), false));fw.write("\r\n");
fw.write("MEMORY_TOTAL=");fw.write(FileUtils.humanReadableByteCount(OSUtils.getTotalMemory(), false));fw.write("\r\n");
fw.write("\r\n");
}
private static void getThrowableInfo(Throwable t, FileWriter fw) {
PrintWriter printWriter = new PrintWriter(fw);
t.printStackTrace(printWriter);
Throwable cause = t.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
}
public static void saveCrashLog(Context context, Throwable t) {
File dir = AppConfig.getExternalCrashDir();
if (dir == null) {
return;
}
String nowString = ReadableTime.getFilenamableTime(System.currentTimeMillis());
String fileName = "crash-" + nowString + ".log";
File file = new File(dir, fileName);
FileWriter fw = null;
try {
fw = new FileWriter(file);
fw.write("TIME=");fw.write(nowString);fw.write("\r\n");
fw.write("\r\n");
collectInfo(context, fw);
fw.write("======== CrashInfo ========\r\n");
getThrowableInfo(t, fw);
fw.write("\r\n");
fw.flush();
} catch (Exception e) {
file.delete();
} finally {
IOUtils.closeQuietly(fw);
}
}
}
@@ -27,11 +27,13 @@ import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Debug;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.LruCache;
import com.getkeepsafe.relinker.ReLinker;
import com.hippo.a7zip.A7Zip;
import com.hippo.a7zip.A7ZipExtractLite;
import com.hippo.beerbelly.SimpleDiskCache;
import com.hippo.conaco.Conaco;
import com.hippo.content.RecordingApplication;
@@ -50,6 +52,7 @@ import com.hippo.text.Html;
import com.hippo.unifile.UniFile;
import com.hippo.util.BitmapUtils;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IntIdGenerator;
@@ -75,10 +78,13 @@ public class EhApplication extends RecordingApplication {
private static final boolean DEBUG_PRINT_IMAGE_COUNT = false;
private static final long DEBUG_PRINT_INTERVAL = 3000L;
private static EhApplication instance;
private final IntIdGenerator mIdGenerator = new IntIdGenerator();
private final HashMap<Integer, Object> mGlobalStuffMap = new HashMap<>();
private EhCookieStore mEhCookieStore;
private EhClient mEhClient;
private EhProxySelector mEhProxySelector;
private OkHttpClient mOkHttpClient;
private ImageBitmapHelper mImageBitmapHelper;
private Conaco<ImageBitmap> mConaco;
@@ -86,12 +92,35 @@ public class EhApplication extends RecordingApplication {
private SimpleDiskCache mSpiderInfoCache;
private DownloadManager mDownloadManager;
private Hosts mHosts;
private FavouriteStatusRouter mFavouriteStatusRouter;
private final List<Activity> mActivityList = new ArrayList<>();
private boolean initialized = false;
public static EhApplication getInstance() {
return instance;
}
@SuppressLint("StaticFieldLeak")
@Override
public void onCreate() {
instance = this;
Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
try {
// Always save crash file if onCreate() is not done
if (!initialized || Settings.getSaveCrashLog()) {
Crash.saveCrashLog(instance, e);
}
} catch (Throwable ignored) { }
if (handler != null) {
handler.uncaughtException(t, e);
}
});
super.onCreate();
GetText.initialize(this);
@@ -105,7 +134,7 @@ public class EhApplication extends RecordingApplication {
EhEngine.initialize();
BitmapUtils.initialize(this);
Image.initialize(this);
A7Zip.initialize(this);
A7Zip.loadLibrary(A7ZipExtractLite.LIBRARY, libname -> ReLinker.loadLibrary(EhApplication.this, libname));
if (EhDB.needMerge()) {
EhDB.mergeOldDB(this);
@@ -140,7 +169,7 @@ public class EhApplication extends RecordingApplication {
return null;
}
}.doInBackground();
}.executeOnExecutor(IoThreadPoolExecutor.getInstance());
// Check app update
update();
@@ -158,6 +187,8 @@ public class EhApplication extends RecordingApplication {
if (DEBUG_PRINT_NATIVE_MEMORY || DEBUG_PRINT_IMAGE_COUNT) {
debugPrint();
}
initialized = true;
}
private void clearTempDir() {
@@ -255,6 +286,15 @@ public class EhApplication extends RecordingApplication {
return application.mEhClient;
}
@NonNull
public static EhProxySelector getEhProxySelector(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mEhProxySelector == null) {
application.mEhProxySelector = new EhProxySelector();
}
return application.mEhProxySelector;
}
@NonNull
public static OkHttpClient getOkHttpClient(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
@@ -265,6 +305,7 @@ public class EhApplication extends RecordingApplication {
.writeTimeout(10, TimeUnit.SECONDS)
.cookieJar(getEhCookieStore(application))
.dns(new EhDns(application))
.proxySelector(getEhProxySelector(application))
.build();
}
return application.mOkHttpClient;
@@ -307,6 +348,12 @@ public class EhApplication extends RecordingApplication {
if (application.mGalleryDetailCache == null) {
// Max size 25, 3 min timeout
application.mGalleryDetailCache = new LruCache<>(25);
getFavouriteStatusRouter().addListener((gid, slot) -> {
GalleryDetail gd = application.mGalleryDetailCache.get(gid);
if (gd != null) {
gd.favoriteSlot = slot;
}
});
}
return application.mGalleryDetailCache;
}
@@ -321,6 +368,11 @@ public class EhApplication extends RecordingApplication {
return application.mSpiderInfoCache;
}
@NonNull
public static DownloadManager getDownloadManager() {
return getDownloadManager(instance);
}
@NonNull
public static DownloadManager getDownloadManager(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
@@ -339,6 +391,20 @@ public class EhApplication extends RecordingApplication {
return application.mHosts;
}
@NonNull
public static FavouriteStatusRouter getFavouriteStatusRouter() {
return getFavouriteStatusRouter(getInstance());
}
@NonNull
public static FavouriteStatusRouter getFavouriteStatusRouter(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mFavouriteStatusRouter == null) {
application.mFavouriteStatusRouter = new FavouriteStatusRouter();
}
return application.mFavouriteStatusRouter;
}
@NonNull
public static String getDeveloperEmail() {
return "ehviewersu$gmail.com".replace('$', '@');
@@ -382,4 +448,14 @@ public class EhApplication extends RecordingApplication {
return false;
}
}
// Avoid crash on some "energy saving" devices
@Override
public void unbindService(ServiceConnection conn) {
try {
super.unbindService(conn);
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
}
}
}
+23 -11
View File
@@ -20,10 +20,9 @@ import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.ListUrlBuilder;
import com.hippo.ehviewer.dao.DaoMaster;
@@ -49,7 +48,7 @@ import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.collect.SparseJLArray;
import de.greenrobot.dao.query.LazyList;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -59,8 +58,6 @@ import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.dao.query.LazyList;
public class EhDB {
private static final String TAG = EhDB.class.getSimpleName();
@@ -92,10 +89,9 @@ public class EhDB {
private static void upgradeDB(SQLiteDatabase db, int oldVersion) {
switch (oldVersion) {
case 1: // 1 to 2
case 1: // 1 to 2, add FILTER
FilterDao.createTable(db, true);
break;
case 2: // add ENABLE column to table FILTER
case 2: // 2 to 3, add ENABLE column to table FILTER
db.execSQL("CREATE TABLE " + "\"FILTER2\" (" +
"\"_id\" INTEGER PRIMARY KEY ," +
"\"MODE\" INTEGER NOT NULL ," +
@@ -105,8 +101,24 @@ public class EhDB {
"_id, MODE, TEXT, ENABLE)" +
"SELECT _id, MODE, TEXT, 1 FROM FILTER;");
db.execSQL("DROP TABLE FILTER");
db.execSQL("ALTER TABLE FILTER2 RENAME TO FILTER");
break;
db.execSQL("ALTER TABLE FILTER2 RENAME TO FILTER");
case 3: // 3 to 4, add PAGE_FROM and PAGE_TO column to QUICK_SEARCH
db.execSQL("CREATE TABLE " + "\"QUICK_SEARCH2\" (" +
"\"_id\" INTEGER PRIMARY KEY ," +
"\"NAME\" TEXT," +
"\"MODE\" INTEGER NOT NULL ," +
"\"CATEGORY\" INTEGER NOT NULL ," +
"\"KEYWORD\" TEXT," +
"\"ADVANCE_SEARCH\" INTEGER NOT NULL ," +
"\"MIN_RATING\" INTEGER NOT NULL ," +
"\"PAGE_FROM\" INTEGER NOT NULL ," +
"\"PAGE_TO\" INTEGER NOT NULL ," +
"\"TIME\" INTEGER NOT NULL );");
db.execSQL("INSERT INTO \"QUICK_SEARCH2\" (" +
"_id, NAME, MODE, CATEGORY, KEYWORD, ADVANCE_SEARCH, MIN_RATING, PAGE_FROM, PAGE_TO, TIME)" +
"SELECT _id, NAME, MODE, CATEGORY, KEYWORD, ADVANCE_SEARCH, MIN_RATING, -1, -1, TIME FROM QUICK_SEARCH;");
db.execSQL("DROP TABLE QUICK_SEARCH");
db.execSQL("ALTER TABLE QUICK_SEARCH2 RENAME TO QUICK_SEARCH");
}
}
@@ -0,0 +1,106 @@
/*
* Copyright 2019 Hippo Seven
*
* 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.
*/
package com.hippo.ehviewer;
import android.text.TextUtils;
import com.hippo.network.InetValidator;
import com.hippo.util.ExceptionUtils;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.Collections;
import java.util.List;
public class EhProxySelector extends ProxySelector {
public static final int TYPE_DIRECT = 0;
public static final int TYPE_SYSTEM = 1;
public static final int TYPE_HTTP = 2;
public static final int TYPE_SOCKS = 3;
private ProxySelector delegation;
private ProxySelector alternative;
EhProxySelector() {
alternative = ProxySelector.getDefault();
if (alternative == null) {
alternative = new NullProxySelector();
}
updateProxy();
}
public void updateProxy() {
switch (Settings.getProxyType()) {
case TYPE_DIRECT:
delegation = new NullProxySelector();
break;
default:
case TYPE_SYSTEM:
delegation = alternative;
break;
case TYPE_HTTP:
case TYPE_SOCKS:
delegation = null;
break;
}
}
@Override
public List<Proxy> select(URI uri) {
int type = Settings.getProxyType();
if (type == TYPE_HTTP || type == TYPE_SOCKS) {
try {
String ip = Settings.getProxyIp();
int port = Settings.getProxyPort();
if (!TextUtils.isEmpty(ip) && InetValidator.isValidInetPort(port)) {
InetAddress inetAddress = InetAddress.getByName(ip);
SocketAddress socketAddress = new InetSocketAddress(inetAddress, port);
return Collections.singletonList(new Proxy(type == TYPE_HTTP ? Proxy.Type.HTTP : Proxy.Type.SOCKS, socketAddress));
}
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
}
}
if (delegation != null) {
return delegation.select(uri);
}
return alternative.select(uri);
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
if (delegation != null) {
delegation.select(uri);
}
}
private static class NullProxySelector extends ProxySelector {
@Override
public List<Proxy> select(URI uri) {
return Collections.singletonList(Proxy.NO_PROXY);
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { }
}
}
@@ -0,0 +1,72 @@
/*
* Copyright 2019 Hippo Seven
*
* 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.
*/
package com.hippo.ehviewer;
import android.annotation.SuppressLint;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.yorozuya.IntIdGenerator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FavouriteStatusRouter {
private static final String KEY_DATA_MAP_NEXT_ID = "data_map_next_id";
private final IntIdGenerator idGenerator = new IntIdGenerator(Settings.getInt(KEY_DATA_MAP_NEXT_ID, 0));
@SuppressLint("UseSparseArrays")
private final HashMap<Integer, Map<Long, GalleryInfo>> maps = new HashMap<>();
private List<Listener> listeners = new ArrayList<>();
public int saveDataMap(Map<Long, GalleryInfo> map) {
int id = idGenerator.nextId();
maps.put(id, map);
Settings.putInt(KEY_DATA_MAP_NEXT_ID, idGenerator.nextId());
return id;
}
public Map<Long, GalleryInfo> restoreDataMap(int id) {
return maps.remove(id);
}
public void modifyFavourites(long gid, int slot) {
for (Map<Long, GalleryInfo> map : maps.values()) {
GalleryInfo info = map.get(gid);
if (info != null) {
info.favoriteSlot = slot;
}
}
for (Listener listener : listeners) {
listener.onModifyFavourites(gid, slot);
}
}
public void addListener(Listener listener) {
listeners.add(listener);
}
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public interface Listener {
void onModifyFavourites(long gid, int slot);
}
}
@@ -18,8 +18,8 @@ package com.hippo.ehviewer;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
public class GetText {
@@ -25,8 +25,8 @@ import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;
import android.util.Pair;
import androidx.annotation.Nullable;
import com.hippo.database.MSQLiteBuilder;
import com.hippo.util.SqlUtils;
import java.net.InetAddress;
@@ -16,13 +16,11 @@
package com.hippo.ehviewer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.conaco.ValueHelper;
import com.hippo.image.ImageBitmap;
import com.hippo.streampipe.InputStreamPipe;
import java.io.IOException;
public class ImageBitmapHelper implements ValueHelper<ImageBitmap> {
@@ -20,14 +20,15 @@ import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import androidx.annotation.DimenRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.client.EhConfig;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.FavListUrlBuilder;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.ehviewer.ui.scene.GalleryListScene;
import com.hippo.glgallery.GalleryView;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
@@ -36,6 +37,7 @@ import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.NumberUtils;
import java.io.File;
import java.util.Locale;
public class Settings {
@@ -49,6 +51,16 @@ public class Settings {
sContext = context.getApplicationContext();
sSettingsPre = PreferenceManager.getDefaultSharedPreferences(sContext);
sEhConfig = loadEhConfig();
fixDefaultValue(context);
}
private static void fixDefaultValue(Context context) {
// Enable builtin hosts if the country is CN
if (!sSettingsPre.contains(KEY_BUILT_IN_HOSTS)) {
if ("CN".equals(Locale.getDefault().getCountry())) {
putBuiltInHosts(true);
}
}
}
private static EhConfig loadEhConfig() {
@@ -267,6 +279,22 @@ public class Settings {
putIntToStr(KEY_GALLERY_SITE, value);
}
private static final String KEY_LAUNCH_PAGE = "launch_page";
private static final int DEFAULT_LAUNCH_PAGE = 0;
public static String getLaunchPageGalleryListSceneAction() {
int value = getIntFromStr(KEY_LAUNCH_PAGE, DEFAULT_LAUNCH_PAGE);
switch (value) {
default:
case 0:
return GalleryListScene.ACTION_HOMEPAGE;
case 1:
return GalleryListScene.ACTION_SUBSCRIPTION;
case 2:
return GalleryListScene.ACTION_WHATS_HOT;
}
}
public static final String KEY_LIST_MODE = "list_mode";
private static final int DEFAULT_LIST_MODE = 0;
@@ -340,6 +368,13 @@ public class Settings {
return getBoolean(KEY_SHOW_GALLERY_PAGES, DEFAULT_SHOW_GALLERY_PAGES);
}
public static final String KEY_SHOW_TAG_TRANSLATIONS = "show_tag_translations";
private static final boolean DEFAULT_SHOW_TAG_TRANSLATIONS = false;
public static boolean getShowTagTranslations() {
return getBoolean(KEY_SHOW_TAG_TRANSLATIONS, DEFAULT_SHOW_TAG_TRANSLATIONS);
}
public static final String KEY_DEFAULT_CATEGORIES = "default_categories";
public static final int DEFAULT_DEFAULT_CATEGORIES = EhUtils.ALL_CATEGORY;
@@ -379,72 +414,6 @@ public class Settings {
putString(KEY_EXCLUDED_LANGUAGES, value);
}
private static final String KEY_HATH_PROXY = "hath_proxy";
private static final boolean DEFAULT_HATH_PROXY = false;
public static boolean getHathProxy() {
return getBoolean(KEY_HATH_PROXY, DEFAULT_HATH_PROXY);
}
public static void putHathProxy(boolean value) {
if (value) {
sEhConfig.hahClientIp = Settings.getHathIp();
sEhConfig.hahClientPort = Settings.getHathPort();
sEhConfig.hahClientPasskey = Settings.getHathPasskey();
} else {
sEhConfig.hahClientIp = DEFAULT_HATH_IP;
sEhConfig.hahClientPort = DEFAULT_HATH_PORT;
sEhConfig.hahClientPasskey = DEFAULT_HATH_PASSKEY;
}
sEhConfig.setDirty();
putBoolean(KEY_HATH_PROXY, value);
}
private static final String KEY_HATH_IP = "hath_ip";
private static final String DEFAULT_HATH_IP = null;
public static String getHathIp() {
return getString(KEY_HATH_IP, DEFAULT_HATH_IP);
}
public static void putHathIp(String value) {
if (Settings.getHathProxy()) {
sEhConfig.hahClientIp = value;
sEhConfig.setDirty();
}
putString(KEY_HATH_IP, value);
}
private static final String KEY_HATH_PORT = "hath_port";
private static final int DEFAULT_HATH_PORT = -1;
public static int getHathPort() {
return getInt(KEY_HATH_PORT, DEFAULT_HATH_PORT);
}
public static void putHathPort(int value) {
if (Settings.getHathProxy()) {
sEhConfig.hahClientPort = value;
sEhConfig.setDirty();
}
putInt(KEY_HATH_PORT, value);
}
private static final String KEY_HATH_PASSKEY = "hath_passkey";
private static final String DEFAULT_HATH_PASSKEY = null;
public static String getHathPasskey() {
return getString(KEY_HATH_PASSKEY, DEFAULT_HATH_PASSKEY);
}
public static void putHathPasskey(String value) {
if (Settings.getHathProxy()) {
sEhConfig.hahClientPasskey = value;
sEhConfig.setDirty();
}
putString(KEY_HATH_PASSKEY, value);
}
private static final String KEY_CELLULAR_NETWORK_WARNING = "cellular_network_warning";
private static final boolean DEFAULT_CELLULAR_NETWORK_WARNING = false;
@@ -1009,6 +978,13 @@ public class Settings {
putBoolean(KEY_SAVE_PARSE_ERROR_BODY, value);
}
private static final String KEY_SAVE_CRASH_LOG = "save_crash_log";
private static final boolean DEFAULT_SAVE_CRASH_LOG = false;
public static boolean getSaveCrashLog() {
return getBoolean(KEY_SAVE_CRASH_LOG, DEFAULT_SAVE_CRASH_LOG);
}
public static final String KEY_SECURITY = "security";
public static final String DEFAULT_SECURITY = "";
@@ -1059,6 +1035,39 @@ public class Settings {
putString(KEY_APP_LANGUAGE, value);
}
private static final String KEY_PROXY_TYPE = "proxy_type";
private static final int DEFAULT_PROXY_TYPE = EhProxySelector.TYPE_SYSTEM;
public static int getProxyType() {
return getInt(KEY_PROXY_TYPE, DEFAULT_PROXY_TYPE);
}
public static void putProxyType(int value) {
putInt(KEY_PROXY_TYPE, value);
}
private static final String KEY_PROXY_IP = "proxy_ip";
private static final String DEFAULT_PROXY_IP = null;
public static String getProxyIp() {
return getString(KEY_PROXY_IP, DEFAULT_PROXY_IP);
}
public static void putProxyIp(String value) {
putString(KEY_PROXY_IP, value);
}
private static final String KEY_PROXY_PORT = "proxy_port";
private static final int DEFAULT_PROXY_PORT = -1;
public static int getProxyPort() {
return getInt(KEY_PROXY_PORT, DEFAULT_PROXY_PORT);
}
public static void putProxyPort(int value) {
putInt(KEY_PROXY_PORT, value);
}
/********************
****** Guide
********************/
@@ -20,9 +20,9 @@ import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Browser;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.hippo.ehviewer.client.EhUrlOpener;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.scene.Announcer;
@@ -19,18 +19,12 @@ package com.hippo.ehviewer.client;
import android.content.Context;
import android.os.AsyncTask;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.CancelledException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.io.File;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
@@ -42,7 +36,6 @@ public class EhClient {
public static final int METHOD_SIGN_IN = 0;
public static final int METHOD_GET_GALLERY_LIST = 1;
public static final int METHOD_FILL_GALLERY_LIST_BY_API = 2;
public static final int METHOD_GET_GALLERY_DETAIL = 3;
public static final int METHOD_GET_PREVIEW_SET = 4;
public static final int METHOD_GET_RATE_GALLERY = 5;
@@ -53,7 +46,6 @@ public class EhClient {
public static final int METHOD_ADD_FAVORITES_RANGE = 10;
public static final int METHOD_MODIFY_FAVORITES = 11;
public static final int METHOD_GET_TORRENT_LIST = 12;
public static final int METHOD_GET_WHATS_HOT = 13;
public static final int METHOD_GET_PROFILE = 14;
public static final int METHOD_VOTE_COMMENT = 15;
public static final int METHOD_IMAGE_SEARCH = 16;
@@ -64,12 +56,7 @@ public class EhClient {
private final OkHttpClient mOkHttpClient;
public EhClient(Context context) {
int poolSize = 3;
BlockingQueue<Runnable> requestWorkQueue = new LinkedBlockingQueue<>();
ThreadFactory threadFactory = new PriorityThreadFactory(TAG,
android.os.Process.THREAD_PRIORITY_BACKGROUND);
mRequestThreadPool = new ThreadPoolExecutor(poolSize, poolSize,
1L, TimeUnit.SECONDS, requestWorkQueue, threadFactory);
mRequestThreadPool = IoThreadPoolExecutor.getInstance();
mOkHttpClient = EhApplication.getOkHttpClient(context);
}
@@ -154,8 +141,6 @@ public class EhClient {
return EhEngine.signIn(this, mOkHttpClient, (String) params[0], (String) params[1], (String) params[2], (String) params[3]);
case METHOD_GET_GALLERY_LIST:
return EhEngine.getGalleryList(this, mOkHttpClient, (String) params[0]);
case METHOD_FILL_GALLERY_LIST_BY_API:
return EhEngine.fillGalleryListByApi(this, mOkHttpClient, (List<GalleryInfo>) params[0]);
case METHOD_GET_GALLERY_DETAIL:
return EhEngine.getGalleryDetail(this, mOkHttpClient, (String) params[0]);
case METHOD_GET_PREVIEW_SET:
@@ -163,7 +148,7 @@ public class EhClient {
case METHOD_GET_RATE_GALLERY:
return EhEngine.rateGallery(this, mOkHttpClient, (Long) params[0], (String) params[1], (Long) params[2], (String) params[3], (Float) params[4]);
case METHOD_GET_COMMENT_GALLERY:
return EhEngine.commentGallery(this, mOkHttpClient, (String) params[0], (String) params[1]);
return EhEngine.commentGallery(this, mOkHttpClient, (String) params[0], (String) params[1], (String) params[2]);
case METHOD_GET_GALLERY_TOKEN:
return EhEngine.getGalleryToken(this, mOkHttpClient, (Long) params[0], (String) params[1], (Integer) params[2]);
case METHOD_GET_FAVORITES:
@@ -175,9 +160,7 @@ public class EhClient {
case METHOD_MODIFY_FAVORITES:
return EhEngine.modifyFavorites(this, mOkHttpClient, (String) params[0], (long[]) params[1], (Integer) params[2], (Boolean) params[3]);
case METHOD_GET_TORRENT_LIST:
return EhEngine.getTorrentList(this, mOkHttpClient, (String) params[0]);
case METHOD_GET_WHATS_HOT:
return EhEngine.getWhatsHot(this, mOkHttpClient);
return EhEngine.getTorrentList(this, mOkHttpClient, (String) params[0], (Long) params[1], (String) params[2]);
case METHOD_GET_PROFILE:
return EhEngine.getProfile(this, mOkHttpClient);
case METHOD_VOTE_COMMENT:
@@ -185,7 +168,7 @@ public class EhClient {
case METHOD_IMAGE_SEARCH:
return EhEngine.imageSearch(this, mOkHttpClient, (File) params[0], (Boolean) params[1], (Boolean) params[2], (Boolean) params[3]);
case METHOD_ARCHIVE_LIST:
return EhEngine.getArchiveList(this, mOkHttpClient, (String) params[0]);
return EhEngine.getArchiveList(this, mOkHttpClient, (String) params[0], (Long) params[1], (String) params[2]);
case METHOD_DOWNLOAD_ARCHIVE:
return EhEngine.downloadArchive(this, mOkHttpClient, (Long) params[0], (String) params[1], (String) params[2], (String) params[3]);
default:
@@ -289,6 +289,7 @@ public class EhConfig implements Cloneable {
public static final int ASIAN_PORN = 0x80;
public static final int NON_H = 0x100;
public static final int WESTERN = 0x200;
public static final int ALL_CATEGORY = 0x3ff;
public static final int NAMESPACES_RECLASS = 0x1;
public static final int NAMESPACES_LANGUAGE = 0x2;
@@ -39,11 +39,13 @@ public class EhDns implements Dns {
static {
Map<String, InetAddress> map = new HashMap<>();
put(map, "e-hentai.org", "104.24.255.11");
put(map, "e-hentai.org", "104.20.26.25");
put(map, "repo.e-hentai.org", "94.100.29.73");
put(map, "forums.e-hentai.org", "94.100.18.243");
put(map, "ehgt.org", "81.171.14.118");
put(map, "ul.ehgt.org", "94.100.24.82");
put(map, "github.com", "192.30.255.112");
put(map, "raw.githubusercontent.com", "151.101.0.133");
builtInHosts = map;
}
@@ -16,15 +16,15 @@
package com.hippo.ehviewer.client;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.data.GalleryComment;
import com.hippo.ehviewer.client.data.GalleryCommentList;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.PreviewSet;
@@ -38,6 +38,7 @@ import com.hippo.ehviewer.client.parser.ForumsParser;
import com.hippo.ehviewer.client.parser.GalleryApiParser;
import com.hippo.ehviewer.client.parser.GalleryDetailParser;
import com.hippo.ehviewer.client.parser.GalleryListParser;
import com.hippo.ehviewer.client.parser.GalleryPageApiParser;
import com.hippo.ehviewer.client.parser.GalleryPageParser;
import com.hippo.ehviewer.client.parser.GalleryTokenApiParser;
import com.hippo.ehviewer.client.parser.ProfileParser;
@@ -45,7 +46,6 @@ import com.hippo.ehviewer.client.parser.RateGalleryParser;
import com.hippo.ehviewer.client.parser.SignInParser;
import com.hippo.ehviewer.client.parser.TorrentParser;
import com.hippo.ehviewer.client.parser.VoteCommentParser;
import com.hippo.ehviewer.client.parser.WhatsHotParser;
import com.hippo.network.StatusCodeException;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.AssertUtils;
@@ -102,8 +102,10 @@ public class EhEngine {
}
if (e instanceof ParseException) {
if (body != null && !body.contains("<")){
if (body != null && !body.contains("<")) {
throw new EhException(body);
} else if (TextUtils.isEmpty(body)) {
throw new EhException(GetText.getString(R.string.error_empty_html));
} else {
if (Settings.getSaveParseErrorBody()) {
AppConfig.saveParseErrorBody((ParseException) e);
@@ -144,8 +146,10 @@ public class EhEngine {
builder.add("recaptcha_response_field", recaptchaResponse);
}
String url = EhUrl.API_SIGN_IN;
String referer = "https://forums.e-hentai.org/index.php?act=Login&CODE=00";
String origin = "https://forums.e-hentai.org";
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
Request request = new EhRequestBuilder(url, referer, origin)
.post(builder.build())
.build();
Call call = okHttpClient.newCall(request);
@@ -171,10 +175,63 @@ public class EhEngine {
}
}
private static void fillGalleryList(@Nullable EhClient.Task task, OkHttpClient okHttpClient, List<GalleryInfo> list, String url, boolean filter) throws Throwable {
// Filter title and uploader
if (filter) {
for (int i = 0, n = list.size(); i < n; i++) {
GalleryInfo info = list.get(i);
if (!sEhFilter.filterTitle(info) || !sEhFilter.filterUploader(info)) {
list.remove(i);
i--;
n--;
}
}
}
boolean hasTags = false;
boolean hasPages = false;
boolean hasRated = false;
for (GalleryInfo gi : list) {
if (gi.simpleTags != null) {
hasTags = true;
}
if (gi.pages != 0) {
hasPages = true;
}
if (gi.rated) {
hasRated = true;
}
}
boolean needApi = (filter && sEhFilter.needTags() && !hasTags) ||
(Settings.getShowGalleryPages() && !hasPages) ||
hasRated;
if (needApi) {
fillGalleryListByApi(task, okHttpClient, list, url);
}
// Filter tag
if (filter) {
for (int i = 0, n = list.size(); i < n; i++) {
GalleryInfo info = list.get(i);
if (!sEhFilter.filterTag(info) || !sEhFilter.filterTagNamespace(info)) {
list.remove(i);
i--;
n--;
}
}
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
}
public static GalleryListParser.Result getGalleryList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Throwable {
String referer = EhUrl.getReferer();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Request request = new EhRequestBuilder(url, referer).build();
Call call = okHttpClient.newCall(request);
// Put call
@@ -198,49 +255,21 @@ public class EhEngine {
throw e;
}
// Filter title and uploader
List<GalleryInfo> list = result.galleryInfoList;
for (int i = 0, n = list.size(); i < n; i++) {
GalleryInfo info = list.get(i);
if (!sEhFilter.filterTitle(info) || !sEhFilter.filterUploader(info)) {
list.remove(i);
i--;
n--;
}
}
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages() || sEhFilter.needCallApi())) {
// Fill by api
fillGalleryListByApi(task, okHttpClient, list);
// Filter tag
for (int i = 0, n = list.size(); i < n; i++) {
GalleryInfo info = list.get(i);
if (!sEhFilter.filterTag(info) || !sEhFilter.filterTagNamespace(info)) {
list.remove(i);
i--;
n--;
}
}
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
fillGalleryList(task, okHttpClient, result.galleryInfoList, url, true);
return result;
}
// At least, GalleryInfo contain valid gid and token
public static List<GalleryInfo> fillGalleryListByApi(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
List<GalleryInfo> galleryInfoList) throws Throwable {
List<GalleryInfo> galleryInfoList, String referer) throws Throwable {
// We can only request 25 items one time at most
final int MAX_REQUEST_SIZE = 25;
List<GalleryInfo> requestItems = new ArrayList<>(MAX_REQUEST_SIZE);
for (int i = 0, size = galleryInfoList.size(); i < size; i++) {
requestItems.add(galleryInfoList.get(i));
if (requestItems.size() == MAX_REQUEST_SIZE || i == size - 1) {
doFillGalleryListByApi(task, okHttpClient, requestItems);
doFillGalleryListByApi(task, okHttpClient, requestItems, referer);
requestItems.clear();
}
}
@@ -248,7 +277,7 @@ public class EhEngine {
}
private static void doFillGalleryListByApi(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
List<GalleryInfo> galleryInfoList) throws Throwable {
List<GalleryInfo> galleryInfoList, String referer) throws Throwable {
JSONObject json = new JSONObject();
json.put("method", "gdata");
JSONArray ja = new JSONArray();
@@ -262,8 +291,9 @@ public class EhEngine {
json.put("gidlist", ja);
json.put("namespace", 1);
String url = EhUrl.getApiUrl();
String origin = EhUrl.getOrigin();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url)
Request request = new EhRequestBuilder(url, referer, origin)
.post(RequestBody.create(MEDIA_TYPE_JSON, json.toString()))
.build();
Call call = okHttpClient.newCall(request);
@@ -291,8 +321,9 @@ public class EhEngine {
public static GalleryDetail getGalleryDetail(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Throwable {
String referer = EhUrl.getReferer();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Request request = new EhRequestBuilder(url, referer).build();
Call call = okHttpClient.newCall(request);
// Put call
@@ -319,8 +350,9 @@ public class EhEngine {
public static Pair<PreviewSet, Integer> getPreviewSet(
@Nullable EhClient.Task task, OkHttpClient okHttpClient, String url) throws Throwable {
String referer = EhUrl.getReferer();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Request request = new EhRequestBuilder(url, referer).build();
Call call = okHttpClient.newCall(request);
// Put call
@@ -357,8 +389,10 @@ public class EhEngine {
json.put("rating", (int) Math.ceil(rating * 2));
final RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json.toString());
String url = EhUrl.getApiUrl();
String referer = EhUrl.getGalleryDetailUrl(gid, token);
String origin = EhUrl.getOrigin();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
Request request = new EhRequestBuilder(url, referer, origin)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
@@ -384,12 +418,18 @@ public class EhEngine {
}
}
public static GalleryComment[] commentGallery(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url, String comment) throws Throwable {
FormBody.Builder builder = new FormBody.Builder()
.add("commenttext_new", comment);
public static GalleryCommentList commentGallery(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url, String comment, String id) throws Throwable {
FormBody.Builder builder = new FormBody.Builder();
if (id == null) {
builder.add("commenttext_new", comment);
} else {
builder.add("commenttext_edit", comment);
builder.add("edit_comment", id);
}
String origin = EhUrl.getOrigin();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
Request request = new EhRequestBuilder(url, url, origin)
.post(builder.build())
.build();
Call call = okHttpClient.newCall(request);
@@ -430,8 +470,10 @@ public class EhEngine {
new JSONArray().put(gid).put(gtoken).put(page + 1)));
final RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json.toString());
String url = EhUrl.getApiUrl();
String referer = EhUrl.getReferer();
String origin = EhUrl.getOrigin();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
Request request = new EhRequestBuilder(url, referer, origin)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
@@ -459,8 +501,9 @@ public class EhEngine {
public static FavoritesParser.Result getFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url, boolean callApi) throws Throwable {
String referer = EhUrl.getReferer();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Request request = new EhRequestBuilder(url, referer).build();
Call call = okHttpClient.newCall(request);
// Put call
@@ -484,15 +527,7 @@ public class EhEngine {
throw e;
}
List<GalleryInfo> list = result.galleryInfoList;
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages())) {
fillGalleryListByApi(task, okHttpClient, list);
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
fillGalleryList(task, okHttpClient, result.galleryInfoList, url, false);
return result;
}
@@ -518,8 +553,9 @@ public class EhEngine {
builder.add("submit", "Apply Changes");
builder.add("update", "1");
String url = EhUrl.getAddFavorites(gid, token);
String origin = EhUrl.getOrigin();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
Request request = new EhRequestBuilder(url, url, origin)
.post(builder.build())
.build();
Call call = okHttpClient.newCall(request);
@@ -572,8 +608,9 @@ public class EhEngine {
builder.add("modifygids[]", Long.toString(gid));
}
builder.add("apply", "Apply");
String origin = EhUrl.getOrigin();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
Request request = new EhRequestBuilder(url, url, origin)
.post(builder.build())
.build();
Call call = okHttpClient.newCall(request);
@@ -599,22 +636,16 @@ public class EhEngine {
throw e;
}
List<GalleryInfo> list = result.galleryInfoList;
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages())) {
fillGalleryListByApi(task, okHttpClient, list);
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
fillGalleryList(task, okHttpClient, result.galleryInfoList, url, false);
return result;
}
public static Pair<String, String>[] getTorrentList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Throwable {
String url, long gid, String token) throws Throwable {
String referer = EhUrl.getGalleryDetailUrl(gid, token);
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Request request = new EhRequestBuilder(url, referer).build();
Call call = okHttpClient.newCall(request);
// Put call
@@ -642,9 +673,10 @@ public class EhEngine {
}
public static Pair<String, Pair<String, String>[]> getArchiveList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Throwable {
String url, long gid, String token) throws Throwable {
String referer = EhUrl.getGalleryDetailUrl(gid, token);
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Request request = new EhRequestBuilder(url, referer).build();
Call call = okHttpClient.newCall(request);
// Put call
@@ -682,8 +714,10 @@ public class EhEngine {
FormBody.Builder builder = new FormBody.Builder();
builder.add("hathdl_xres", res);
String url = EhUrl.getDownloadArchive(gid, token, or);
String referer = EhUrl.getGalleryDetailUrl(gid, token);
String origin = EhUrl.getOrigin();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
Request request = new EhRequestBuilder(url, referer, origin)
.post(builder.build())
.build();
Call call = okHttpClient.newCall(request);
@@ -716,50 +750,10 @@ public class EhEngine {
return null;
}
public static List<GalleryInfo> getWhatsHot(@Nullable EhClient.Task task,
OkHttpClient okHttpClient) throws Throwable {
String url = EhUrl.HOST_E;
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Call call = okHttpClient.newCall(request);
// Put call
if (null != task) {
task.setCall(call);
}
String body = null;
Headers headers = null;
List<GalleryInfo> list;
int code = -1;
try {
Response response = call.execute();
code = response.code();
headers = response.headers();
body = response.body().string();
list = WhatsHotParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
if (list.size() > 0) {
// Fill by api
fillGalleryListByApi(task, okHttpClient, list);
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
return list;
}
private static ProfileParser.Result getProfileInternal(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url) throws Throwable {
OkHttpClient okHttpClient, String url, String referer) throws Throwable {
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Request request = new EhRequestBuilder(url, referer).build();
Call call = okHttpClient.newCall(request);
// Put call
@@ -787,7 +781,7 @@ public class EhEngine {
OkHttpClient okHttpClient) throws Throwable {
String url = EhUrl.URL_FORUMS;
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Request request = new EhRequestBuilder(url, null).build();
Call call = okHttpClient.newCall(request);
// Put call
@@ -803,7 +797,7 @@ public class EhEngine {
code = response.code();
headers = response.headers();
body = response.body().string();
return getProfileInternal(task, okHttpClient, ForumsParser.parse(body));
return getProfileInternal(task, okHttpClient, ForumsParser.parse(body), url);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
@@ -823,8 +817,10 @@ public class EhEngine {
json.put("comment_vote", commentVote);
final RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json.toString());
String url = EhUrl.getApiUrl();
String referer = EhUrl.getReferer();
String origin = EhUrl.getOrigin();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
Request request = new EhRequestBuilder(url, referer, origin)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
@@ -884,8 +880,10 @@ public class EhEngine {
RequestBody.create(null, "File Search")
);
String url = EhUrl.getImageSearchUrl();
String referer = EhUrl.getReferer();
String origin = EhUrl.getOrigin();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig())
Request request = new EhRequestBuilder(url, referer, origin)
.post(builder.build())
.build();
Call call = okHttpClient.newCall(request);
@@ -914,43 +912,16 @@ public class EhEngine {
throw e;
}
// Filter title and uploader
List<GalleryInfo> list = result.galleryInfoList;
for (int i = 0, n = list.size(); i < n; i++) {
GalleryInfo info = list.get(i);
if (!sEhFilter.filterTitle(info) || !sEhFilter.filterUploader(info)) {
list.remove(i);
i--;
n--;
}
}
if (list.size() > 0 && (TextUtils.isEmpty(list.get(0).uploader) || Settings.getShowJpnTitle() || Settings.getShowGalleryPages() || sEhFilter.needCallApi())) {
// Fill by api
fillGalleryListByApi(task, okHttpClient, list);
// Filter tag
for (int i = 0, n = list.size(); i < n; i++) {
GalleryInfo info = list.get(i);
if (!sEhFilter.filterTag(info) || !sEhFilter.filterTagNamespace(info)) {
list.remove(i);
i--;
n--;
}
}
}
for (GalleryInfo info : list) {
info.thumb = EhUrl.getFixedPreviewThumbUrl(info.thumb);
}
fillGalleryList(task, okHttpClient, result.galleryInfoList, url, true);
return result;
}
public static GalleryPageParser.Result getGalleryPage(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url) throws Throwable {
OkHttpClient okHttpClient, String url, long gid, String token) throws Throwable {
String referer = EhUrl.getGalleryDetailUrl(gid, token);
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, null != task ? task.getEhConfig() : Settings.getEhConfig()).build();
Request request = new EhRequestBuilder(url, referer).build();
Call call = okHttpClient.newCall(request);
// Put call
@@ -973,4 +944,46 @@ public class EhEngine {
throw e;
}
}
public static GalleryPageApiParser.Result getGalleryPageApi(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, long gid, int index, String pToken, String showKey, String previousPToken) throws Throwable {
final JSONObject json = new JSONObject();
json.put("method", "showpage");
json.put("gid", gid);
json.put("page", index + 1);
json.put("imgkey", pToken);
json.put("showkey", showKey);
final RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json.toString());
String url = EhUrl.getApiUrl();
String referer = null;
if (index > 0 && previousPToken != null) {
referer = EhUrl.getPageUrl(gid, index - 1, previousPToken);
}
String origin = EhUrl.getOrigin();
Log.d(TAG, url);
Request request = new EhRequestBuilder(url, referer, origin)
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
// Put call
if (null != task) {
task.setCall(call);
}
String body = null;
Headers headers = null;
int code = -1;
try {
Response response = call.execute();
code = response.code();
headers = response.headers();
body = response.body().string();
return GalleryPageApiParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
}
@@ -144,7 +144,7 @@ public final class EhFilter {
}
}
public synchronized boolean needCallApi() {
public synchronized boolean needTags() {
return 0 != mTagFilterList.size() || 0 != mTagNamespaceFilterList.size();
}
@@ -157,7 +157,6 @@ public final class EhFilter {
String title = info.title;
List<Filter> filters = mTitleFilterList;
if (null != title && filters.size() > 0) {
title = title.toLowerCase();
for (int i = 0, n = filters.size(); i < n; i++) {
if (filters.get(i).enable && title.contains(filters.get(i).text)) {
return false;
@@ -16,19 +16,21 @@
package com.hippo.ehviewer.client;
import com.hippo.ehviewer.Settings;
import com.hippo.okhttp.ChromeRequestBuilder;
import java.net.MalformedURLException;
public class EhRequestBuilder extends ChromeRequestBuilder {
public EhRequestBuilder(String url) throws MalformedURLException {
this(url, Settings.getEhConfig());
public EhRequestBuilder(String url, String referer) {
this(url, referer, null);
}
public EhRequestBuilder(String url, EhConfig ehConfig) throws MalformedURLException {
public EhRequestBuilder(String url, String referer, String origin) {
super(url);
tag(ehConfig);
if (referer != null) {
addHeader("Referer", referer);
}
if (origin != null) {
addHeader("Origin", origin);
}
}
}
@@ -0,0 +1,357 @@
/*
* Copyright 2019 Hippo Seven
*
* 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.
*/
package com.hippo.ehviewer.client;
import android.content.Context;
import android.util.Base64;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.util.TextUrl;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.Okio;
public class EhTagDatabase {
private final String name;
private final byte[] tags;
public EhTagDatabase(String name, BufferedSource source) throws IOException {
this.name = name;
int totalBytes = source.readInt();
tags = new byte[totalBytes];
source.readFully(tags);
}
public String getTranslation(String tag) {
return search(tags, tag.getBytes(TextUrl.UTF_8));
}
@Nullable
private String search(byte[] tags, byte[] tag) {
int low = 0;
int high = tags.length;
while (low < high) {
int start = (low + high) / 2;
// Look for the starting '\n'
while (start > -1 && tags[start] != '\n') {
start--;
}
start++;
// Look for the middle '\r'.
int middle = 1;
while (tags[start + middle] != '\r') {
middle++;
}
// Look for the ending '\n'
int end = middle + 1;
while (tags[start + end] != '\n') {
end++;
}
int compare;
int tagIndex = 0;
int curIndex = start;
for (;;) {
int tagByte = tag[tagIndex] & 0xff;
int curByte = tags[curIndex] & 0xff;
compare = tagByte - curByte;
if (compare != 0) {
break;
}
tagIndex++;
curIndex++;
if (tagIndex == tag.length && curIndex == start + middle) {
break;
}
if (tagIndex == tag.length) {
compare = -1;
break;
}
if (curIndex == start + middle) {
compare = 1;
break;
}
}
if (compare < 0) {
high = start - 1;
} else if (compare > 0) {
low = start + end + 1;
} else {
byte[] bytes = Base64.decode(tags, start + middle + 1, end - middle - 1, Base64.DEFAULT);
return new String(bytes, TextUrl.UTF_8);
}
}
return null;
}
private static final Map<String, String> NAMESPACE_TO_PREFIX = new HashMap<>();
static {
NAMESPACE_TO_PREFIX.put("artist", "a:");
NAMESPACE_TO_PREFIX.put("character", "c:");
NAMESPACE_TO_PREFIX.put("female", "f:");
NAMESPACE_TO_PREFIX.put("group", "g:");
NAMESPACE_TO_PREFIX.put("language", "l:");
NAMESPACE_TO_PREFIX.put("male", "m:");
NAMESPACE_TO_PREFIX.put("misc", "");
NAMESPACE_TO_PREFIX.put("parody", "p:");
NAMESPACE_TO_PREFIX.put("reclass", "r:");
}
private static volatile EhTagDatabase instance;
// TODO more lock for different language
private static Lock lock = new ReentrantLock();
@Nullable
public static EhTagDatabase getInstance(Context context) {
if (isPossible(context)) {
return instance;
} else {
instance = null;
return null;
}
}
@Nullable
public static String namespaceToPrefix(String namespace) {
return NAMESPACE_TO_PREFIX.get(namespace);
}
private static String[] getMetadata(Context context) {
String[] metadata = context.getResources().getStringArray(R.array.tag_translation_metadata);
if (metadata.length == 4) {
return metadata;
} else {
return null;
}
}
public static boolean isPossible(Context context) {
return getMetadata(context) != null;
}
@Nullable
private static byte[] getFileContent(File file, int length) {
try (BufferedSource source = Okio.buffer(Okio.source(file))) {
byte[] content = new byte[length];
source.readFully(content);
return content;
} catch (IOException e) {
return null;
}
}
@Nullable
private static byte[] getFileSha1(File file) {
try (InputStream is = new FileInputStream(file)) {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
int n;
byte[] buffer = new byte[4 * 1024];
while ((n = is.read(buffer)) != -1) {
digest.update(buffer, 0, n);
}
return digest.digest();
} catch (IOException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
}
}
private static boolean equals(byte[] b1, byte[] b2) {
if (b1 == null && b2 == null) {
return true;
}
if (b1 == null || b2 == null) {
return false;
}
if (b1.length != b2.length) {
return false;
}
for (int i = 0; i < b1.length; i++) {
if (b1[i] != b2[i]) {
return false;
}
}
return true;
}
private static boolean checkData(File sha1File, File dataFile) {
byte[] s1 = getFileContent(sha1File, 20);
if (s1 == null) {
return false;
}
byte[] s2 = getFileSha1(dataFile);
if (s2 == null) {
return false;
}
return equals(s1, s2);
}
private static boolean save(OkHttpClient client, String url, File file) {
Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
try (Response response = call.execute()) {
if (!response.isSuccessful()) {
return false;
}
ResponseBody body = response.body();
if (body == null) {
return false;
}
try (InputStream is = body.byteStream(); OutputStream os = new FileOutputStream(file)) {
IOUtils.copy(is, os);
}
return true;
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
return false;
}
}
public static void update(Context context) {
String[] urls = getMetadata(context);
if (urls == null || urls.length != 4) {
// Clear tags if it's not possible
instance = null;
return;
}
String sha1Name = urls[0];
String sha1Url = urls[1];
String dataName = urls[2];
String dataUrl = urls[3];
// Clear tags if name if different
EhTagDatabase tmp = instance;
if (tmp != null && !tmp.name.equals(dataName)) {
instance = null;
}
IoThreadPoolExecutor.getInstance().execute(() -> {
if (!lock.tryLock()) {
return;
}
try {
File dir = AppConfig.getFilesDir("tag-translations");
if (dir == null) {
return;
}
// Check current sha1 and current data
File sha1File = new File(dir, sha1Name);
File dataFile = new File(dir, dataName);
if (!checkData(sha1File, dataFile)) {
FileUtils.delete(sha1File);
FileUtils.delete(dataFile);
}
// Read current EhTagDatabase
if (instance == null && dataFile.exists()) {
try (BufferedSource source = Okio.buffer(Okio.source(dataFile))) {
instance = new EhTagDatabase(dataName, source);
} catch (IOException e) {
FileUtils.delete(sha1File);
FileUtils.delete(dataFile);
}
}
OkHttpClient client = EhApplication.getOkHttpClient(EhApplication.getInstance());
// Save new sha1
File tempSha1File = new File(dir, sha1Name + ".tmp");
if (!save(client, sha1Url, tempSha1File)) {
FileUtils.delete(tempSha1File);
return;
}
// Check new sha1 and current data
if (checkData(tempSha1File, dataFile)) {
// The data is the same
FileUtils.delete(tempSha1File);
return;
}
// Save new data
File tempDataFile = new File(dir, dataName + ".tmp");
if (!save(client, dataUrl, tempDataFile)) {
FileUtils.delete(tempDataFile);
return;
}
// Check new sha1 and new data
if (!checkData(tempSha1File, tempDataFile)) {
FileUtils.delete(tempSha1File);
FileUtils.delete(tempDataFile);
return;
}
// Replace current sha1 and current data with new sha1 and new data
FileUtils.delete(sha1File);
FileUtils.delete(dataFile);
tempSha1File.renameTo(sha1File);
tempDataFile.renameTo(dataFile);
// Read new EhTagDatabase
try (BufferedSource source = Okio.buffer(Okio.source(dataFile))) {
instance = new EhTagDatabase(dataName, source);
} catch (IOException e) {
// Ignore
}
} finally {
lock.unlock();
}
});
}
}
@@ -16,7 +16,7 @@
package com.hippo.ehviewer.client;
import android.support.annotation.NonNull;
import androidx.annotation.NonNull;
import com.hippo.ehviewer.Settings;
import com.hippo.network.UrlBuilder;
import java.util.List;
@@ -40,6 +40,9 @@ public class EhUrl {
public static final String API_E = HOST_E + "api.php";
public static final String API_EX = HOST_EX + "api.php";
public static final String URL_POPULAR_E = "https://e-hentai.org/popular";
public static final String URL_POPULAR_EX = "https://exhentai.org/popular";
public static final String URL_IMAGE_SEARCH_E = "https://upload.e-hentai.org/image_lookup.php";
public static final String URL_IMAGE_SEARCH_EX = "https://exhentai.org/upload/image_lookup.php";
@@ -49,10 +52,22 @@ public class EhUrl {
public static final String URL_FAVORITES_EX = HOST_EX + "favorites.php";
public static final String URL_FORUMS = "https://forums.e-hentai.org/";
public static final String UCONFIG_E = HOST_E + "uconfig.php";
public static final String UCONFIG_EX = HOST_EX + "uconfig.php";
public static final String REFERER_EX = "https://" + DOMAIN_EX;
public static final String REFERER_E = "https://" + DOMAIN_E;
private static final String URL_PREFIX_THUMB_E = "https://ul.ehgt.org/";
public static final String ORIGIN_EX = REFERER_EX;
public static final String ORIGIN_E = REFERER_E;
public static final String URL_UCONFIG_E = HOST_E + "uconfig.php";
public static final String URL_UCONFIG_EX = HOST_EX + "uconfig.php";
public static final String URL_MY_TAGS_E = HOST_E + "mytags";
public static final String URL_MY_TAGS_EX = HOST_EX + "mytags";
public static final String URL_WATCHED_E = HOST_E + "watched";
public static final String URL_WATCHED_EX = HOST_EX + "watched";
private static final String URL_PREFIX_THUMB_E = "https://ehgt.org/";
private static final String URL_PREFIX_THUMB_EX = "https://exhentai.org/t/";
public static String getGalleryDetailUrl(long gid, String token) {
@@ -89,13 +104,43 @@ public class EhUrl {
}
}
public static String getReferer() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return REFERER_E;
case SITE_EX:
return REFERER_EX;
}
}
public static String getOrigin() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return ORIGIN_E;
case SITE_EX:
return ORIGIN_EX;
}
}
public static String getUConfigUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return UCONFIG_E;
return URL_UCONFIG_E;
case SITE_EX:
return UCONFIG_EX;
return URL_UCONFIG_EX;
}
}
public static String getMyTagsUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return URL_MY_TAGS_E;
case SITE_EX:
return URL_MY_TAGS_EX;
}
}
@@ -126,6 +171,17 @@ public class EhUrl {
return "https://ehwiki.org/wiki/" + tag.replace(' ', '_');
}
@NonNull
public static String getPopularUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return URL_POPULAR_E;
case SITE_EX:
return URL_POPULAR_EX;
}
}
@NonNull
public static String getImageSearchUrl() {
switch (Settings.getGallerySite()) {
@@ -137,6 +193,17 @@ public class EhUrl {
}
}
@NonNull
public static String getWatchedUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_E:
return URL_WATCHED_E;
case SITE_EX:
return URL_WATCHED_EX;
}
}
public static String getThumbUrlPrefix() {
switch (Settings.getGallerySite()) {
default:
@@ -17,10 +17,9 @@
package com.hippo.ehviewer.client;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.client.data.ListUrlBuilder;
import com.hippo.ehviewer.client.parser.GalleryDetailUrlParser;
import com.hippo.ehviewer.client.parser.GalleryListUrlParser;
@@ -18,13 +18,11 @@ package com.hippo.ehviewer.client;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.data.GalleryInfo;
import java.util.regex.Pattern;
public class EhUtils {
@@ -72,9 +70,9 @@ public class EhUtils {
new String[] { "misc" },
new String[] { "doujinshi" },
new String[] { "manga" },
new String[] { "artistcg", "Artist CG Sets" },
new String[] { "gamecg", "Game CG Sets" },
new String[] { "imageset", "Image Sets" },
new String[] { "artistcg", "Artist CG Sets", "Artist CG" },
new String[] { "gamecg", "Game CG Sets", "Game CG" },
new String[] { "imageset", "Image Sets", "Image Set" },
new String[] { "cosplay" },
new String[] { "asianporn", "Asian Porn" },
new String[] { "non-h" },
@@ -69,11 +69,18 @@ public class FavListUrlBuilder implements Parcelable {
UrlBuilder ub = new UrlBuilder(EhUrl.getFavoritesUrl());
if (isValidFavCat(mFavCat)) {
ub.addQuery("favcat", Integer.toString(mFavCat));
} else if (mFavCat == FAV_CAT_ALL) {
ub.addQuery("favcat", "all");
}
if (!TextUtils.isEmpty(mKeyword)) {
try {
ub.addQuery("f_search", URLEncoder.encode(mKeyword, "UTF-8"));
ub.addQuery("f_apply", "Search+Favorites");
// Name
ub.addQuery("sn", "on");
// Tags
ub.addQuery("st", "on");
// Note
ub.addQuery("sf", "on");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Can't URLEncoder.encode " + mKeyword);
}
@@ -18,7 +18,7 @@ package com.hippo.ehviewer.client.data;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import androidx.annotation.Nullable;
public class GalleryApiInfo implements Parcelable {
@@ -24,8 +24,11 @@ public class GalleryComment implements Parcelable {
// 0 for uploader comment. can't vote
public long id;
public int score;
public boolean voteUp;
public boolean voteDown;
public boolean editable;
public boolean voteUpAble;
public boolean voteUpEd;
public boolean voteDownAble;
public boolean voteDownEd;
public String voteState;
public long time;
public String user;
@@ -40,8 +43,11 @@ public class GalleryComment implements Parcelable {
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeInt(this.score);
dest.writeByte(voteUp ? (byte) 1 : (byte) 0);
dest.writeByte(voteDown ? (byte) 1 : (byte) 0);
dest.writeByte(editable ? (byte) 1 : (byte) 0);
dest.writeByte(voteUpAble ? (byte) 1 : (byte) 0);
dest.writeByte(voteUpEd ? (byte) 1 : (byte) 0);
dest.writeByte(voteDownAble ? (byte) 1 : (byte) 0);
dest.writeByte(voteDownEd ? (byte) 1 : (byte) 0);
dest.writeString(this.voteState);
dest.writeLong(this.time);
dest.writeString(this.user);
@@ -54,8 +60,11 @@ public class GalleryComment implements Parcelable {
protected GalleryComment(Parcel in) {
this.id = in.readLong();
this.score = in.readInt();
this.voteUp = in.readByte() != 0;
this.voteDown = in.readByte() != 0;
this.editable = in.readByte() != 0;
this.voteUpAble = in.readByte() != 0;
this.voteUpEd = in.readByte() != 0;
this.voteDownAble = in.readByte() != 0;
this.voteDownEd = in.readByte() != 0;
this.voteState = in.readString();
this.time = in.readLong();
this.user = in.readString();
@@ -0,0 +1,65 @@
/*
* Copyright 2019 Hippo Seven
*
* 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.
*/
package com.hippo.ehviewer.client.data;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Arrays;
public class GalleryCommentList implements Parcelable {
public GalleryComment[] comments;
public boolean hasMore;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelableArray(comments, flags);
dest.writeByte(hasMore ? (byte) 1 : (byte) 0);
}
public GalleryCommentList(GalleryComment[] comments, boolean hasMore) {
this.comments = comments;
this.hasMore = hasMore;
}
protected GalleryCommentList(Parcel in) {
Parcelable[] array = in.readParcelableArray(getClass().getClassLoader());
if (array != null) {
comments = Arrays.copyOf(array, array.length, GalleryComment[].class);
} else {
comments = null;
}
hasMore = in.readByte() != 0;
}
public static final Creator<GalleryCommentList> CREATOR = new Creator<GalleryCommentList>() {
@Override
public GalleryCommentList createFromParcel(Parcel in) {
return new GalleryCommentList(in);
}
@Override
public GalleryCommentList[] newArray(int size) {
return new GalleryCommentList[size];
}
};
}
@@ -37,10 +37,9 @@ public class GalleryDetail extends GalleryInfo {
public boolean isFavorited;
public int ratingCount;
public GalleryTagGroup[] tags;
public GalleryComment[] comments;
public GalleryCommentList comments;
public int previewPages;
public PreviewSet previewSet;
public String favoriteName;
@Override
public int describeContents() {
@@ -61,11 +60,10 @@ public class GalleryDetail extends GalleryInfo {
dest.writeInt(this.favoriteCount);
dest.writeByte(isFavorited ? (byte) 1 : (byte) 0);
dest.writeInt(this.ratingCount);
dest.writeParcelableArray(this.tags, 0);
dest.writeParcelableArray(this.comments, 0);
dest.writeParcelableArray(this.tags, flags);
dest.writeParcelable(this.comments, flags);
dest.writeInt(this.previewPages);
dest.writeParcelable(previewSet, flags);
dest.writeString(this.favoriteName);
}
public GalleryDetail() {
@@ -90,15 +88,9 @@ public class GalleryDetail extends GalleryInfo {
} else {
this.tags = null;
}
array = in.readParcelableArray(GalleryComment.class.getClassLoader());
if (array != null) {
this.comments = Arrays.copyOf(array, array.length, GalleryComment[].class);
} else {
this.comments = null;
}
this.comments = in.readParcelable(getClass().getClassLoader());
this.previewPages = in.readInt();
this.previewSet = in.readParcelable(PreviewSet.class.getClassLoader());
this.favoriteName = in.readString();
}
public static final Creator<GalleryDetail> CREATOR = new Creator<GalleryDetail>() {
@@ -18,8 +18,7 @@ package com.hippo.ehviewer.client.data;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import androidx.annotation.Nullable;
import java.util.regex.Pattern;
public class GalleryInfo implements Parcelable {
@@ -62,21 +61,21 @@ public class GalleryInfo implements Parcelable {
};
public static final Pattern[] S_LANG_PATTERNS = {
Pattern.compile("[(\\[]eng(?:lish)?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]eng(?:lish)?[)\\]]|英訳", Pattern.CASE_INSENSITIVE),
// [((\[]ch(?:inese)?[))\]]|[汉漢]化|中[国國][语語]|中文|中国翻訳
Pattern.compile("[(\uFF08\\[]ch(?:inese)?[)\uFF09\\]]|[汉漢]化|中[国國][语語]|中文|中国翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]spanish[)\\]]|[(\\[]Español[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]korean?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]rus(?:sian)?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]fr(?:ench)?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]portuguese", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]thai(?: ภาษาไทย)?[)\\]]|แปลไทย", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]german[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]italiano?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]vietnamese(?: Tiếng Việt)?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]polish[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]hun(?:garian)?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]dutch[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]spanish[)\\]]|[(\\[]Español[)\\]]|スペイン翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]korean?[)\\]]|韓国翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]rus(?:sian)?[)\\]]|ロシア翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]fr(?:ench)?[)\\]]|フランス翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]portuguese|ポルトガル翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]thai(?: ภาษาไทย)?[)\\]]|แปลไทย|タイ翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]german[)\\]]|ドイツ翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]italiano?[)\\]]|イタリア翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]vietnamese(?: Tiếng Việt)?[)\\]]|ベトナム翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]polish[)\\]]|ポーランド翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]hun(?:garian)?[)\\]]|ハンガリー翻訳", Pattern.CASE_INSENSITIVE),
Pattern.compile("[(\\[]dutch[)\\]]|オランダ翻訳", Pattern.CASE_INSENSITIVE),
};
public static final String[] S_LANG_TAGS = {
@@ -105,6 +104,7 @@ public class GalleryInfo implements Parcelable {
public String posted;
public String uploader;
public float rating;
public boolean rated;
@Nullable
public String[] simpleTags;
public int pages;
@@ -121,6 +121,9 @@ public class GalleryInfo implements Parcelable {
*/
public String simpleLanguage;
public int favoriteSlot = -2;
public String favoriteName;
public final void generateSLang() {
if (simpleTags != null) {
generateSLangFromTags();
@@ -167,6 +170,7 @@ public class GalleryInfo implements Parcelable {
dest.writeString(this.posted);
dest.writeString(this.uploader);
dest.writeFloat(this.rating);
dest.writeByte(this.rated ? (byte) 1 : (byte) 0);
dest.writeString(this.simpleLanguage);
dest.writeStringArray(this.simpleTags);
dest.writeInt(this.thumbWidth);
@@ -174,6 +178,8 @@ public class GalleryInfo implements Parcelable {
dest.writeInt(this.spanSize);
dest.writeInt(this.spanIndex);
dest.writeInt(this.spanGroupIndex);
dest.writeInt(this.favoriteSlot);
dest.writeString(this.favoriteName);
}
public GalleryInfo() {}
@@ -188,6 +194,7 @@ public class GalleryInfo implements Parcelable {
this.posted = in.readString();
this.uploader = in.readString();
this.rating = in.readFloat();
this.rated = in.readByte() != 0;
this.simpleLanguage = in.readString();
this.simpleTags = in.createStringArray();
this.thumbWidth = in.readInt();
@@ -195,6 +202,8 @@ public class GalleryInfo implements Parcelable {
this.spanSize = in.readInt();
this.spanIndex = in.readInt();
this.spanGroupIndex = in.readInt();
this.favoriteSlot = in.readInt();
this.favoriteName = in.readString();
}
public static final Parcelable.Creator<GalleryInfo> CREATOR = new Parcelable.Creator<GalleryInfo>() {
@@ -18,18 +18,17 @@ package com.hippo.ehviewer.client.data;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.client.EhConfig;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.dao.QuickSearch;
import com.hippo.ehviewer.widget.AdvanceSearchTable;
import com.hippo.network.UrlBuilder;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -38,7 +37,7 @@ import java.net.URLEncoder;
public class ListUrlBuilder implements Cloneable, Parcelable {
@IntDef({MODE_NORMAL, MODE_UPLOADER, MODE_TAG, MODE_WHATS_HOT, MODE_IMAGE_SEARCH})
@IntDef({MODE_NORMAL, MODE_UPLOADER, MODE_TAG, MODE_WHATS_HOT, MODE_IMAGE_SEARCH, MODE_SUBSCRIPTION})
@Retention(RetentionPolicy.SOURCE)
private @interface Mode {}
@@ -48,6 +47,7 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
public static final int MODE_TAG = 0x2;
public static final int MODE_WHATS_HOT = 0x3;
public static final int MODE_IMAGE_SEARCH = 0x4;
public static final int MODE_SUBSCRIPTION = 0x5;
public static final int DEFAULT_ADVANCE = AdvanceSearchTable.SNAME | AdvanceSearchTable.STAGS;
public static final int DEFAULT_MIN_RATING = 2;
@@ -62,6 +62,8 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
private int mAdvanceSearch = -1;
private int mMinRating = -1;
private int mPageFrom = -1;
private int mPageTo = -1;
private String mImagePath;
private boolean mUseSimilarityScan;
@@ -78,6 +80,8 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
mKeyword = null;
mAdvanceSearch = -1;
mMinRating = -1;
mPageFrom = -1;
mPageTo = -1;
mImagePath = null;
mUseSimilarityScan = false;
mOnlySearchCovers = false;
@@ -142,6 +146,22 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
mMinRating = minRating;
}
public int getPageFrom() {
return mPageFrom;
}
public void setPageFrom(int pageFrom) {
mPageFrom = pageFrom;
}
public int getPageTo() {
return mPageTo;
}
public void setPageTo(int pageTo) {
mPageTo = pageTo;
}
@Nullable
public String getImagePath() {
return mImagePath;
@@ -186,6 +206,8 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
mKeyword = lub.mKeyword;
mAdvanceSearch = lub.mAdvanceSearch;
mMinRating = lub.mMinRating;
mPageFrom = lub.mPageFrom;
mPageTo = lub.mPageTo;
mImagePath = lub.mImagePath;
mUseSimilarityScan = lub.mUseSimilarityScan;
mOnlySearchCovers = lub.mOnlySearchCovers;
@@ -198,6 +220,8 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
mKeyword = q.keyword;
mAdvanceSearch = q.advanceSearch;
mMinRating = q.minRating;
mPageFrom = q.pageFrom;
mPageTo = q.pageTo;
mImagePath = null;
mUseSimilarityScan = false;
mOnlySearchCovers = false;
@@ -211,6 +235,8 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
q.keyword = mKeyword;
q.advanceSearch = mAdvanceSearch;
q.minRating = mMinRating;
q.pageFrom = mPageFrom;
q.pageTo = mPageTo;
return q;
}
@@ -234,6 +260,12 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
if (q.minRating != mMinRating) {
return false;
}
if (q.pageFrom != mPageFrom) {
return false;
}
if (q.pageTo != mPageTo) {
return false;
}
return true;
}
@@ -250,124 +282,166 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
}
String[] querys = StringUtils.split(query, '&');
boolean apply = false;
int category = 0;
String keyword = null;
boolean enableAdvanceSearch = false;
int advanceSearch = 0;
boolean enableMinRating = false;
int minRating = 0;
for (int i = 0, size = querys.length; i < size; i++) {
String str = querys[i];
int minRating = -1;
boolean enablePage = false;
int pageFrom = -1;
int pageTo = -1;
for (String str : querys) {
int index = str.indexOf('=');
if (index < 0) {
continue;
}
String key = str.substring(0, index);
String value = str.substring(index + 1);
if ("f_doujinshi".equals(key)) {
if ("1".equals(value)) {
category |= EhConfig.DOUJINSHI;
}
} else if ("f_manga".equals(key)) {
if ("1".equals(value)) {
category |= EhConfig.MANGA;
}
} else if ("f_artistcg".equals(key)) {
if ("1".equals(value)) {
category |= EhConfig.ARTIST_CG;
}
} else if ("f_gamecg".equals(key)) {
if ("1".equals(value)) {
category |= EhConfig.GAME_CG;
}
} else if ("f_western".equals(key)) {
if ("1".equals(value)) {
category |= EhConfig.WESTERN;
}
} else if ("f_non-h".equals(key)) {
if ("1".equals(value)) {
category |= EhConfig.NON_H;
}
} else if ("f_imageset".equals(key)) {
if ("1".equals(value)) {
category |= EhConfig.IMAGE_SET;
}
} else if ("f_cosplay".equals(key)) {
if ("1".equals(value)) {
category |= EhConfig.COSPLAY;
}
} else if ("f_asianporn".equals(key)) {
if ("1".equals(value)) {
category |= EhConfig.ASIAN_PORN;
}
} else if ("f_misc".equals(key)) {
if ("1".equals(value)) {
category |= EhConfig.MISC;
}
} else if ("f_search".equals(key)) {
try {
keyword = URLDecoder.decode(value, "utf-8");
} catch (UnsupportedEncodingException e) {
// Ignore
}
} else if ("advsearch".equals(key)) {
if ("1".equals(value)) {
enableAdvanceSearch = true;
}
} else if ("f_sname".equals(key)) {
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SNAME;
}
} else if ("f_stags".equals(key)) {
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.STAGS;
}
} else if ("f_sdesc".equals(key)) {
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SDESC;
}
} else if ("f_storr".equals(key)) {
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.STORR;
}
} else if ("f_sto".equals(key)) {
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.STO;
}
} else if ("f_sdt1".equals(key)) {
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SDT1;
}
} else if ("f_sdt2".equals(key)) {
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SDT2;
}
} else if ("f_sh".equals(key)) {
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SH;
}
} else if ("f_sr".equals(key)) {
if ("on".equals(value)) {
enableMinRating = true;
}
} else if ("f_srdd".equals(key)) {
try {
minRating = Integer.parseInt(value);
} catch (NumberFormatException e) {
// Ignore
}
} else if ("f_apply".equals(key)) {
if ("Apply+Filter".equals(value)) {
apply = true;
}
switch (key) {
case "f_cats":
int cats = NumberUtils.parseIntSafely(value, EhConfig.ALL_CATEGORY);
category |= (~cats) & EhConfig.ALL_CATEGORY;
break;
case "f_doujinshi":
if ("1".equals(value)) {
category |= EhConfig.DOUJINSHI;
}
break;
case "f_manga":
if ("1".equals(value)) {
category |= EhConfig.MANGA;
}
break;
case "f_artistcg":
if ("1".equals(value)) {
category |= EhConfig.ARTIST_CG;
}
break;
case "f_gamecg":
if ("1".equals(value)) {
category |= EhConfig.GAME_CG;
}
break;
case "f_western":
if ("1".equals(value)) {
category |= EhConfig.WESTERN;
}
break;
case "f_non-h":
if ("1".equals(value)) {
category |= EhConfig.NON_H;
}
break;
case "f_imageset":
if ("1".equals(value)) {
category |= EhConfig.IMAGE_SET;
}
break;
case "f_cosplay":
if ("1".equals(value)) {
category |= EhConfig.COSPLAY;
}
break;
case "f_asianporn":
if ("1".equals(value)) {
category |= EhConfig.ASIAN_PORN;
}
break;
case "f_misc":
if ("1".equals(value)) {
category |= EhConfig.MISC;
}
break;
case "f_search":
try {
keyword = URLDecoder.decode(value, "utf-8");
} catch (UnsupportedEncodingException | IllegalArgumentException e) {
// Ignore
}
break;
case "advsearch":
if ("1".equals(value)) {
enableAdvanceSearch = true;
}
break;
case "f_sname":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SNAME;
}
break;
case "f_stags":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.STAGS;
}
break;
case "f_sdesc":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SDESC;
}
break;
case "f_storr":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.STORR;
}
break;
case "f_sto":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.STO;
}
break;
case "f_sdt1":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SDT1;
}
break;
case "f_sdt2":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SDT2;
}
break;
case "f_sh":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SH;
}
break;
case "f_sfl":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SFL;
}
break;
case "f_sfu":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SFU;
}
break;
case "f_sft":
if ("on".equals(value)) {
advanceSearch |= AdvanceSearchTable.SFT;
}
break;
case "f_sr":
if ("on".equals(value)) {
enableMinRating = true;
}
break;
case "f_srdd":
minRating = NumberUtils.parseIntSafely(value, -1);
break;
case "f_sp":
if ("on".equals(value)) {
enablePage = true;
}
break;
case "f_spf":
pageFrom = NumberUtils.parseIntSafely(value, -1);
break;
case "f_spt":
pageTo = NumberUtils.parseIntSafely(value, -1);
break;
}
}
if (!apply) {
return;
}
mCategory = category;
mKeyword = keyword;
if (enableAdvanceSearch) {
@@ -377,6 +451,13 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
} else {
mMinRating = -1;
}
if (enablePage) {
mPageFrom = pageFrom;
mPageTo = pageTo;
} else {
mPageFrom = -1;
mPageTo = -1;
}
} else {
mAdvanceSearch = -1;
}
@@ -385,29 +466,28 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
public String build() {
switch (mMode) {
default:
case MODE_NORMAL: {
boolean filter = false;
UrlBuilder ub = new UrlBuilder(EhUrl.getHost());
case MODE_NORMAL:
case MODE_SUBSCRIPTION: {
String url;
if (mMode == MODE_NORMAL) {
url = EhUrl.getHost();
} else {
url = EhUrl.getWatchedUrl();
}
UrlBuilder ub = new UrlBuilder(url);
if (mCategory != EhUtils.NONE) {
ub.addQuery("f_doujinshi", ((mCategory & EhConfig.DOUJINSHI) == 0) ? "0" : "1");
ub.addQuery("f_manga", ((mCategory & EhConfig.MANGA) == 0) ? "0" : "1");
ub.addQuery("f_artistcg", ((mCategory & EhConfig.ARTIST_CG) == 0) ? "0" : "1");
ub.addQuery("f_gamecg", ((mCategory & EhConfig.GAME_CG) == 0) ? "0" : "1");
ub.addQuery("f_western", ((mCategory & EhConfig.WESTERN) == 0) ? "0" : "1");
ub.addQuery("f_non-h", ((mCategory & EhConfig.NON_H) == 0) ? "0" : "1");
ub.addQuery("f_imageset", ((mCategory & EhConfig.IMAGE_SET) == 0) ? "0" : "1");
ub.addQuery("f_cosplay", ((mCategory & EhConfig.COSPLAY) == 0) ? "0" : "1");
ub.addQuery("f_asianporn", ((mCategory & EhConfig.ASIAN_PORN) == 0) ? "0" : "1");
ub.addQuery("f_misc", ((mCategory & EhConfig.MISC) == 0) ? "0" : "1");
filter = true;
ub.addQuery("f_cats", (~mCategory) & EhConfig.ALL_CATEGORY);
}
// Search key
if (mKeyword != null) {
try {
ub.addQuery("f_search", URLEncoder.encode(mKeyword, "UTF-8"));
filter = true;
} catch (UnsupportedEncodingException e) {
// Empty
String keyword = mKeyword.trim();
if (!keyword.isEmpty()) {
try {
ub.addQuery("f_search", URLEncoder.encode(mKeyword, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// Empty
}
}
}
// Page index
@@ -425,16 +505,20 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
if((mAdvanceSearch & AdvanceSearchTable.SDT1) != 0) ub.addQuery("f_sdt1", "on");
if((mAdvanceSearch & AdvanceSearchTable.SDT2) != 0) ub.addQuery("f_sdt2", "on");
if((mAdvanceSearch & AdvanceSearchTable.SH) != 0) ub.addQuery("f_sh", "on");
if((mAdvanceSearch & AdvanceSearchTable.SFL) != 0) ub.addQuery("f_sfl", "on");
if((mAdvanceSearch & AdvanceSearchTable.SFU) != 0) ub.addQuery("f_sfu", "on");
if((mAdvanceSearch & AdvanceSearchTable.SFT) != 0) ub.addQuery("f_sft", "on");
// Set min star
if (mMinRating != -1) {
ub.addQuery("f_sr", "on");
ub.addQuery("f_srdd", mMinRating);
}
filter = true;
}
// Add filter foot
if (filter) {
ub.addQuery("f_apply", "Apply+Filter");
// Pages
if (mPageFrom != -1 || mPageTo != -1) {
ub.addQuery("f_sp", "on");
ub.addQuery("f_spf", mPageFrom != -1 ? Integer.toString(mPageFrom) : "");
ub.addQuery("f_spt", mPageTo != -1 ? Integer.toString(mPageTo) : "");
}
}
return ub.build();
}
@@ -464,6 +548,8 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
}
return sb.toString();
}
case MODE_WHATS_HOT:
return EhUrl.getPopularUrl();
case MODE_IMAGE_SEARCH:
return EhUrl.getImageSearchUrl();
}
@@ -482,6 +568,8 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
dest.writeString(this.mKeyword);
dest.writeInt(this.mAdvanceSearch);
dest.writeInt(this.mMinRating);
dest.writeInt(this.mPageFrom);
dest.writeInt(this.mPageTo);
dest.writeString(this.mImagePath);
dest.writeByte(mUseSimilarityScan ? (byte) 1 : (byte) 0);
dest.writeByte(mOnlySearchCovers ? (byte) 1 : (byte) 0);
@@ -499,6 +587,8 @@ public class ListUrlBuilder implements Cloneable, Parcelable {
this.mKeyword = in.readString();
this.mAdvanceSearch = in.readInt();
this.mMinRating = in.readInt();
this.mPageFrom = in.readInt();
this.mPageTo = in.readInt();
this.mImagePath = in.readString();
this.mUseSimilarityScan = in.readByte() != 0;
this.mOnlySearchCovers = in.readByte() != 0;
@@ -21,4 +21,8 @@ public class EhException extends Exception {
public EhException(String detailMessage) {
super(detailMessage);
}
public EhException(String detailMessage, Throwable cause) {
super(detailMessage, cause);
}
}
@@ -25,6 +25,11 @@ public class ParseException extends EhException {
mBody = body;
}
public ParseException(String detailMessage, String body, Throwable cause) {
super(detailMessage, cause);
mBody = body;
}
public String getBody() {
return mBody;
}
@@ -36,6 +36,7 @@ public class FavoritesParser {
public String[] catArray; // Size 10
public int[] countArray; // Size 10
public int pages;
public int nextPage;
public List<GalleryInfo> galleryInfoList;
}
@@ -56,7 +57,7 @@ public class FavoritesParser {
for (int i = 0; i < 10; i++) {
Element fp = fps.get(i);
countArray[i] = ParserUtils.parseInt(fp.child(0).text());
countArray[i] = ParserUtils.parseInt(fp.child(0).text(), 0);
catArray[i] = ParserUtils.trim(fp.child(2).text());
}
} catch (Throwable e) {
@@ -71,6 +72,7 @@ public class FavoritesParser {
re.catArray = catArray;
re.countArray = countArray;
re.pages = result.pages;
re.nextPage = result.nextPage;
re.galleryInfoList = result.galleryInfoList;
return re;
@@ -19,6 +19,7 @@ package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.yorozuya.NumberUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@@ -43,8 +44,8 @@ public class GalleryApiParser {
gi.category = EhUtils.getCategory(g.getString("category"));
gi.thumb = EhUtils.handleThumbUrlResolution(g.getString("thumb"));
gi.uploader = g.getString("uploader");
gi.posted = ParserUtils.formatDate(ParserUtils.parseLong(g.getString("posted")) * 1000);
gi.rating = Float.parseFloat(g.getString("rating"));
gi.posted = ParserUtils.formatDate(ParserUtils.parseLong(g.getString("posted"), 0) * 1000);
gi.rating = NumberUtils.parseFloatSafely(g.getString("rating"), 0.0f);
// tags
JSONArray tagJa = g.getJSONArray("tags");
int tagLength = tagJa.length();
@@ -53,7 +54,7 @@ public class GalleryApiParser {
tags[j] = tagJa.getString(j);
}
gi.simpleTags = tags;
gi.pages = Integer.parseInt(g.getString("filecount"));
gi.pages = NumberUtils.parseIntSafely(g.getString("filecount"), 0);
gi.generateSLang();
}
}
@@ -16,13 +16,13 @@
package com.hippo.ehviewer.client.parser;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryComment;
import com.hippo.ehviewer.client.data.GalleryCommentList;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ehviewer.client.data.GalleryTagGroup;
import com.hippo.ehviewer.client.data.LargePreviewSet;
@@ -34,6 +34,7 @@ import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.exception.PiningException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import com.hippo.util.MutableBoolean;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import java.text.DateFormat;
@@ -49,7 +50,10 @@ import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
public class GalleryDetailParser {
@@ -67,7 +71,7 @@ public class GalleryDetailParser {
private static final Pattern PATTERN_LARGE_PREVIEW = Pattern.compile("<div class=\"gdtl\".+?<a href=\"(.+?)\"><img alt=\"([\\d,]+)\".+?src=\"(.+?)\"");
private static final GalleryTagGroup[] EMPTY_GALLERY_TAG_GROUP_ARRAY = new GalleryTagGroup[0];
private static final GalleryComment[] EMPTY_GALLERY_COMMENT_ARRAY = new GalleryComment[0];
private static final GalleryCommentList EMPTY_GALLERY_COMMENT_ARRAY = new GalleryCommentList(new GalleryComment[0], false);
private static final DateFormat WEB_COMMENT_DATE_FORMAT = new SimpleDateFormat("dd MMMMM yyyy, HH:mm z", Locale.US);
@@ -109,13 +113,16 @@ public class GalleryDetailParser {
private static void parseDetail(GalleryDetail gd, Document d, String body) throws ParseException {
Matcher matcher = PATTERN_DETAIL.matcher(body);
if (matcher.find()) {
gd.gid = Long.parseLong(matcher.group(1));
gd.gid = NumberUtils.parseLongSafely(matcher.group(1), -1L);
gd.token = matcher.group(2);
gd.apiUid = NumberUtils.parseLongSafely(matcher.group(3), -1L);
gd.apiKey = matcher.group(4);
} else {
throw new ParseException("Can't parse gallery detail", body);
}
if (gd.gid == -1L) {
throw new ParseException("Can't parse gallery detail", body);
}
matcher = PATTERN_TORRENT.matcher(body);
if (matcher.find()) {
@@ -164,9 +171,11 @@ public class GalleryDetailParser {
// Category
Element gdc = gm.getElementById("gdc");
try {
String href = gdc.child(0).attr("href");
String category = href.substring(href.lastIndexOf('/') + 1);
gd.category = EhUtils.getCategory(category);
Element ce = JsoupUtils.getElementByClass(gdc, "cn");
if (ce == null) {
ce = JsoupUtils.getElementByClass(gdc, "cs");
}
gd.category = EhUtils.getCategory(ce.text());
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
gd.category = EhUtils.UNKNOWN;
@@ -334,10 +343,20 @@ public class GalleryDetailParser {
try {
Element taglist = document.getElementById("taglist");
Elements tagGroups = taglist.child(0).child(0).children();
return parseTagGroups(tagGroups);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
return EMPTY_GALLERY_TAG_GROUP_ARRAY;
}
}
List<GalleryTagGroup> list = new ArrayList<>(tagGroups.size());
for (int i = 0, n = tagGroups.size(); i < n; i++) {
GalleryTagGroup group = parseTagGroup(tagGroups.get(i));
@NonNull
public static GalleryTagGroup[] parseTagGroups(Elements trs) {
try {
List<GalleryTagGroup> list = new ArrayList<>(trs.size());
for (int i = 0, n = trs.size(); i < n; i++) {
GalleryTagGroup group = parseTagGroup(trs.get(i));
if (null != group) {
list.add(group);
}
@@ -384,13 +403,23 @@ public class GalleryDetailParser {
Element a = element.previousElementSibling();
String name = a.attr("name");
comment.id = Integer.parseInt(StringUtils.trim(name).substring(1));
// Vote up and vote down
// Editable, vote up and vote down
Element c4 = JsoupUtils.getElementByClass(element, "c4");
if (null != c4) {
Elements es = c4.children();
if (2 == es.size()) {
comment.voteUp = !TextUtils.isEmpty(StringUtils.trim(es.get(0).attr("style")));
comment.voteDown = !TextUtils.isEmpty(StringUtils.trim(es.get(1).attr("style")));
for (Element e : c4.children()) {
switch (e.text()) {
case "Vote+":
comment.voteUpAble = true;
comment.voteUpEd = !StringUtils.trim(e.attr("style")).isEmpty();
break;
case "Vote-":
comment.voteDownAble = true;
comment.voteDownEd = !StringUtils.trim(e.attr("style")).isEmpty();
break;
case "Edit":
comment.editable = true;
break;
}
}
}
// Vote state
@@ -427,7 +456,7 @@ public class GalleryDetailParser {
* Parse comments with html parser
*/
@NonNull
public static GalleryComment[] parseComments(Document document) {
public static GalleryCommentList parseComments(Document document) {
try {
Element cdiv = document.getElementById("cdiv");
Elements c1s = cdiv.getElementsByClass("c1");
@@ -439,7 +468,22 @@ public class GalleryDetailParser {
list.add(comment);
}
}
return list.toArray(new GalleryComment[list.size()]);
Element chd = cdiv.getElementById("chd");
MutableBoolean hasMore = new MutableBoolean(false);
NodeTraversor.traverse(new NodeVisitor() {
@Override
public void head(Node node, int depth) {
if (node instanceof Element && ((Element) node).text().equals("click to show all")) {
hasMore.value = true;
}
}
@Override
public void tail(Node node, int depth) { }
}, chd);
return new GalleryCommentList(list.toArray(new GalleryComment[list.size()]), hasMore.value);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
@@ -494,7 +538,7 @@ public class GalleryDetailParser {
Matcher m = PATTERN_PREVIEW_PAGES.matcher(body);
int previewPages = -1;
if (m.find()) {
previewPages = ParserUtils.parseInt(m.group(1));
previewPages = ParserUtils.parseInt(m.group(1), -1);
}
if (previewPages <= 0) {
@@ -508,12 +552,18 @@ public class GalleryDetailParser {
* Parse pages with regular expressions
*/
public static int parsePages(String body) throws ParseException {
int pages = -1;
Matcher m = PATTERN_PAGES.matcher(body);
if (m.find()) {
return ParserUtils.parseInt(m.group(1));
} else {
pages = ParserUtils.parseInt(m.group(1), -1);
}
if (pages < 0) {
throw new ParseException("Parse pages error", body);
}
return pages;
}
public static PreviewSet parsePreviewSet(Document d, String body) throws ParseException {
@@ -571,7 +621,10 @@ public class GalleryDetailParser {
LargePreviewSet largePreviewSet = new LargePreviewSet();
while (m.find()) {
int index = ParserUtils.parseInt(m.group(2)) - 1;
int index = ParserUtils.parseInt(m.group(2), 0) - 1;
if (index < 0) {
continue;
}
String imageUrl = ParserUtils.trim(m.group(3));
String pageUrl = ParserUtils.trim(m.group(1));
if (Settings.getFixThumbUrl()) {
@@ -594,10 +647,23 @@ public class GalleryDetailParser {
Matcher m = PATTERN_NORMAL_PREVIEW.matcher(body);
NormalPreviewSet normalPreviewSet = new NormalPreviewSet();
while (m.find()) {
normalPreviewSet.addItem(ParserUtils.parseInt(m.group(6)) - 1,
ParserUtils.trim(m.group(3)), ParserUtils.parseInt((m.group(4))), 0,
ParserUtils.parseInt(m.group(1)), ParserUtils.parseInt(m.group(2)),
ParserUtils.trim(m.group(5)));
int position = ParserUtils.parseInt(m.group(6), 0) - 1;
if (position < 0) {
continue;
}
String imageUrl = ParserUtils.trim(m.group(3));
int xOffset = ParserUtils.parseInt(m.group(4), 0);
int yOffset = 0;
int width = ParserUtils.parseInt(m.group(1), 0);
if (width <= 0) {
continue;
}
int height = ParserUtils.parseInt(m.group(2), 0);
if (height <= 0) {
continue;
}
String pageUrl = ParserUtils.trim(m.group(5));
normalPreviewSet.addItem(position, imageUrl, xOffset, yOffset, width, height, pageUrl);
}
if (normalPreviewSet.size() == 0) {
@@ -16,10 +16,9 @@
package com.hippo.ehviewer.client.parser;
import android.support.annotation.Nullable;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.yorozuya.NumberUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -33,7 +32,7 @@ public final class GalleryDetailUrlParser {
"https?://(?:" + EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/(?:g|mpv)/(\\d+)/([0-9a-f]{10})");
private static final Pattern URL_PATTERN = Pattern.compile(
"(\\d+)/([0-9a-f]{10})");
"(\\d+)/([0-9a-f]{10})(?:[^0-9a-f]|$)");
@Nullable
public static Result parse(String url) {
@@ -50,8 +49,11 @@ public final class GalleryDetailUrlParser {
Matcher m = pattern.matcher(url);
if (m.find()) {
Result result = new Result();
result.gid = Long.parseLong(m.group(1));
result.gid = NumberUtils.parseLongSafely(m.group(1), -1L);
result.token = m.group(2);
if (result.gid < 0) {
return null;
}
return result;
} else {
return null;
@@ -16,16 +16,17 @@
package com.hippo.ehviewer.client.parser;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.GalleryTagGroup;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -41,10 +42,28 @@ public class GalleryListParser {
private static final String TAG = GalleryListParser.class.getSimpleName();
private static final Pattern PATTERN_RATING = Pattern.compile("\\d+px");
private static final Pattern PATTERN_THUMB_SIZE = Pattern.compile("height:(\\d+)px; width:(\\d+)px");
private static final Pattern PATTERN_THUMB_SIZE = Pattern.compile("height:(\\d+)px;width:(\\d+)px");
private static final Pattern PATTERN_FAVORITE_SLOT = Pattern.compile("background-color:rgba\\((\\d+),(\\d+),(\\d+),");
private static final Pattern PATTERN_PAGES = Pattern.compile("(\\d+) page");
private static final Pattern PATTERN_NEXT_PAGE = Pattern.compile("page=(\\d+)");
private static final String[][] FAVORITE_SLOT_RGB = new String[][] {
new String[] { "0", "0", "0"},
new String[] { "240", "0", "0"},
new String[] { "240", "160", "0"},
new String[] { "208", "208", "0"},
new String[] { "0", "128", "0"},
new String[] { "144", "240", "64"},
new String[] { "64", "176", "240"},
new String[] { "0", "0", "240"},
new String[] { "80", "0", "128"},
new String[] { "224", "128", "224"},
};
public static class Result {
public int pages;
public int nextPage;
public boolean noWatchedTags;
public List<GalleryInfo> galleryInfoList;
}
@@ -60,18 +79,17 @@ public class GalleryListParser {
private static String parseRating(String ratingStyle) {
Matcher m = PATTERN_RATING.matcher(ratingStyle);
int num1;
int num2;
int num1 = Integer.MIN_VALUE;
int num2 = Integer.MIN_VALUE;
int rate = 5;
String re;
if (m.find()) {
num1 = ParserUtils.parseInt(m.group().replace("px", ""));
} else {
return null;
num1 = ParserUtils.parseInt(m.group().replace("px", ""), Integer.MIN_VALUE);
}
if (m.find()) {
num2 = ParserUtils.parseInt(m.group().replace("px", ""));
} else {
num2 = ParserUtils.parseInt(m.group().replace("px", ""), Integer.MIN_VALUE);
}
if (num1 == Integer.MIN_VALUE || num2 == Integer.MIN_VALUE) {
return null;
}
rate = rate - num1 / 16;
@@ -84,152 +102,191 @@ public class GalleryListParser {
return re;
}
@Nullable
private static GalleryInfo parseGalleryInfo(Element e) {
GalleryInfo gi = new GalleryInfo();
// Get category
Element ic = JsoupUtils.getElementByClass(e, "ic");
if (null != ic) {
gi.category = EhUtils.getCategory(ic.attr("alt").trim());
} else {
Log.w(TAG, "Can't parse gallery info category");
gi.category = EhUtils.UNKNOWN;
}
// Posted
Element itd = JsoupUtils.getElementByClass(e, "itd");
if (null != itd) {
gi.posted = itd.text().trim();
} else {
Log.w(TAG, "Can't parse gallery info posted");
gi.posted = "";
}
// Thumb
Element it2 = JsoupUtils.getElementByClass(e, "it2");
if (null != it2) {
// Thumb size
Matcher m = PATTERN_THUMB_SIZE.matcher(it2.attr("style"));
if (m.find()) {
gi.thumbWidth = NumberUtils.parseIntSafely(m.group(2), 0);
gi.thumbHeight = NumberUtils.parseIntSafely(m.group(1), 0);
} else {
Log.w(TAG, "Can't parse gallery info thumb size");
gi.thumbWidth = 0;
gi.thumbHeight = 0;
}
// Thumb url
Elements es = it2.children();
if (null != es && es.size() >= 1) {
gi.thumb = EhUtils.handleThumbUrlResolution(es.get(0).attr("src"));
} else {
String html = it2.html();
int index1 = html.indexOf('~');
int index2 = StringUtils.ordinalIndexOf(html, '~', 2);
if (index1 < index2) {
gi.thumb = EhUtils.handleThumbUrlResolution(
"http://" +StringUtils.replace(html.substring(index1 + 1, index2), "~", "/"));
} else {
Log.w(TAG, "Can't parse gallery info thumb url");
gi.thumb = "";
private static int parseFavoriteSlot(String style) {
Matcher m = PATTERN_FAVORITE_SLOT.matcher(style);
if (m.find()) {
String r = m.group(1);
String g = m.group(2);
String b = m.group(3);
int slot = 0;
for (String[] rgb : FAVORITE_SLOT_RGB) {
if (r.equals(rgb[0]) && g.equals(rgb[1]) && b.equals(rgb[2])) {
return slot;
}
slot++;
}
} else {
Log.w(TAG, "Can't parse gallery info thumb");
gi.thumbWidth = 0;
gi.thumbHeight = 0;
gi.thumb = "";
}
// Title (required)
Element it5 = JsoupUtils.getElementByClass(e, "it5");
if (null == it5) {
Log.e(TAG, "Can't parse gallery info title, step 1");
return null;
}
Elements es = it5.children();
if (null == es || es.size() <= 0) {
Log.e(TAG, "Can't parse gallery info title, step 2");
return null;
}
Element a = es.get(0);
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parse(a.attr("href"));
if (null == result) {
Log.e(TAG, "Can't parse gallery info title, step 3");
return null;
}
gi.gid = result.gid;
gi.token = result.token;
gi.title = a.text().trim();
// Rating
Element it4r = JsoupUtils.getElementByClass(e, "it4r");
if (null != it4r) {
gi.rating = NumberUtils.parseFloatSafely(parseRating(it4r.attr("style")), -1.0f);
} else {
Log.w(TAG, "Can't parse gallery info rating");
gi.rating = -1.0f;
}
// Uploader
Element itu = JsoupUtils.getElementByClass(e, "itu");
if (null != itu) {
gi.uploader = itu.text().trim();
} else {
Log.w(TAG, "Can't parse gallery info uploader");
gi.uploader = "";
}
gi.generateSLang();
return gi;
return -2;
}
@Nullable
private static GalleryInfo parseGalleryInfoThumbVersion(Element e) {
private static GalleryInfo parseGalleryInfo(Element e) {
GalleryInfo gi = new GalleryInfo();
// Title (required)
Element id2 = JsoupUtils.getElementByClass(e, "id2");
if (id2 == null) {
return null;
}
gi.title = id2.text().trim();
// gid, token (required)
Element a = id2.children().first();
if (a == null) {
return null;
}
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parse(a.attr("href"));
if (result == null) {
return null;
}
gi.gid = result.gid;
gi.token = result.token;
// Thumbnail
Element id3 = JsoupUtils.getElementByClass(e, "id3");
if (id3 != null) {
a = id3.children().first();
// Title, gid, token (required), tags
Element glname = JsoupUtils.getElementByClass(e, "glname");
if (glname != null) {
Element a = JsoupUtils.getElementByTag(glname, "a");
if (a == null) {
Element parent = glname.parent();
if (parent != null && "a".equals(parent.tagName())) {
a = parent;
}
}
if (a != null) {
Element img = a.children().first();
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parse(a.attr("href"));
if (result != null) {
gi.gid = result.gid;
gi.token = result.token;
}
}
Element child = glname;
Elements children = glname.children();
while (children.size() != 0) {
child = children.get(0);
children = child.children();
}
gi.title = child.text().trim();
Element tbody = JsoupUtils.getElementByTag(glname, "tbody");
if (tbody != null) {
ArrayList<String> tags = new ArrayList<>();
GalleryTagGroup[] groups = GalleryDetailParser.parseTagGroups(tbody.children());
for (GalleryTagGroup group : groups) {
for (int j = 0; j < group.size(); j++) {
tags.add(group.groupName + ":" + group.getTagAt(j));
}
}
gi.simpleTags = tags.toArray(new String[tags.size()]);
}
}
if (gi.title == null) {
return null;
}
// Category
gi.category = EhUtils.UNKNOWN;
Element ce = JsoupUtils.getElementByClass(e, "cn");
if (ce == null) {
ce = JsoupUtils.getElementByClass(e, "cs");
}
if (ce != null) {
gi.category = EhUtils.getCategory(ce.text());
}
// Thumb
Element glthumb = JsoupUtils.getElementByClass(e, "glthumb");
if (glthumb != null) {
Element img = glthumb.select("div:nth-child(1)>img").first();
if (img != null) {
// Thumb size
Matcher m = PATTERN_THUMB_SIZE.matcher(img.attr("style"));
if (m.find()) {
gi.thumbWidth = NumberUtils.parseIntSafely(m.group(2), 0);
gi.thumbHeight = NumberUtils.parseIntSafely(m.group(1), 0);
} else {
Log.w(TAG, "Can't parse gallery info thumb size");
gi.thumbWidth = 0;
gi.thumbHeight = 0;
}
// Thumb url
String url = img.attr("data-src");
if (TextUtils.isEmpty(url)) {
url = img.attr("src");
}
if (TextUtils.isEmpty(url)) {
url = null;
}
gi.thumb = EhUtils.handleThumbUrlResolution(url);
}
// Pages
Element div = glthumb.select("div:nth-child(2)>div:nth-child(2)>div:nth-child(2)").first();
if (div != null) {
Matcher matcher = PATTERN_PAGES.matcher(div.text());
if (matcher.find()) {
gi.pages = NumberUtils.parseIntSafely(matcher.group(1), 0);
}
}
}
// Try extended and thumbnail version
if (gi.thumb == null) {
Element gl = JsoupUtils.getElementByClass(e, "gl1e");
if (gl == null) {
gl = JsoupUtils.getElementByClass(e, "gl3t");
}
if (gl != null) {
Element img = JsoupUtils.getElementByTag(gl, "img");
if (img != null) {
// Thumb size
Matcher m = PATTERN_THUMB_SIZE.matcher(img.attr("style"));
if (m.find()) {
gi.thumbWidth = NumberUtils.parseIntSafely(m.group(2), 0);
gi.thumbHeight = NumberUtils.parseIntSafely(m.group(1), 0);
} else {
Log.w(TAG, "Can't parse gallery info thumb size");
gi.thumbWidth = 0;
gi.thumbHeight = 0;
}
gi.thumb = EhUtils.handleThumbUrlResolution(img.attr("src"));
}
}
}
// Category
Element id41 = JsoupUtils.getElementByClass(e, "id41");
if (id41 != null) {
gi.category = EhUtils.getCategory(id41.attr("title").trim());
} else {
gi.category = EhUtils.UNKNOWN;
// Posted
gi.favoriteSlot = -2;
Element posted = e.getElementById("posted_" + gi.gid);
if (posted != null) {
gi.posted = posted.text().trim();
gi.favoriteSlot = parseFavoriteSlot(posted.attr("style"));
}
if (gi.favoriteSlot == -2) {
gi.favoriteSlot = EhDB.containLocalFavorites(gi.gid) ? -1 : -2;
}
// Rating
Element id43 = JsoupUtils.getElementByClass(e, "id43");
if (id43 != null) {
gi.rating = NumberUtils.parseFloatSafely(parseRating(id43.attr("style")), -1.0f);
} else {
gi.rating = -1.0f;
Element ir = JsoupUtils.getElementByClass(e, "ir");
if (ir != null) {
gi.rating = NumberUtils.parseFloatSafely(parseRating(ir.attr("style")), -1.0f);
// TODO The gallery may be rated even if it doesn't has one of these classes
gi.rated = ir.hasClass("irr") || ir.hasClass("irg") || ir.hasClass("irb");
}
// Uploader and pages
Element gl = JsoupUtils.getElementByClass(e, "glhide");
int uploaderIndex = 0;
int pagesIndex = 1;
if (gl == null) {
// For extended
gl = JsoupUtils.getElementByClass(e, "gl3e");
uploaderIndex = 3;
pagesIndex = 4;
}
if (gl != null) {
Elements children = gl.children();
if (children.size() > uploaderIndex) {
Element a = children.get(uploaderIndex).children().first();
if (a != null) {
gi.uploader = a.text().trim();
}
}
if (children.size() > pagesIndex) {
Matcher matcher = PATTERN_PAGES.matcher(children.get(pagesIndex).text());
if (matcher.find()) {
gi.pages = NumberUtils.parseIntSafely(matcher.group(1), 0);
}
}
}
// For thumbnail
Element gl5t = JsoupUtils.getElementByClass(e, "gl5t");
if (gl5t != null) {
Element div = gl5t.select("div:nth-child(2)>div:nth-child(2)").first();
if (div != null) {
Matcher matcher = PATTERN_PAGES.matcher(div.text());
if (matcher.find()) {
gi.pages = NumberUtils.parseIntSafely(matcher.group(1), 0);
}
}
}
gi.generateSLang();
@@ -242,51 +299,62 @@ public class GalleryListParser {
Document d = Jsoup.parse(body);
try {
result.pages = parsePages(d, body);
} catch (ParseException e) {
Element ptt = d.getElementsByClass("ptt").first();
Elements es = ptt.child(0).child(0).children();
result.pages = Integer.parseInt(es.get(es.size() - 2).text().trim());
Element e = es.get(es.size() - 1);
if (e != null) {
e = e.children().first();
if (e != null) {
String href = e.attr("href");
Matcher matcher = PATTERN_NEXT_PAGE.matcher(href);
if (matcher.find()) {
result.nextPage = NumberUtils.parseIntSafely(matcher.group(1), 0);
}
}
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
result.noWatchedTags = body.contains("<p>You do not have any watched tags");
if (body.contains("No hits found</p>")) {
result.pages = 0;
//noinspection unchecked
result.galleryInfoList = Collections.EMPTY_LIST;
return result;
} else if (d.getElementsByClass("ptt").isEmpty()) {
result.pages = 1;
} else {
throw e;
result.pages = Integer.MAX_VALUE;
}
}
try {
Elements es = d.getElementsByClass("itg").first().child(0).children();
List<GalleryInfo> list = new ArrayList<>(es.size() - 1);
for (int i = 1; i < es.size(); i++) { // First one is table header, skip it
Element itg = d.getElementsByClass("itg").first();
Elements es;
if ("table".equalsIgnoreCase(itg.tagName())) {
es = itg.child(0).children();
} else {
es = itg.children();
}
List<GalleryInfo> list = new ArrayList<>(es.size());
// First one is table header, skip it
for (int i = 0; i < es.size(); i++) {
GalleryInfo gi = parseGalleryInfo(es.get(i));
if (null != gi) {
list.add(gi);
}
}
if (list.isEmpty()) {
throw new ParseException("No gallery", body);
}
result.galleryInfoList = list;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
throw new ParseException("Can't parse gallery list", body);
}
// Maybe it's thumbnail version
if (result.galleryInfoList.isEmpty()) {
try {
Elements es = d.getElementsByClass("itg").first().children();
List<GalleryInfo> list = new ArrayList<>(es.size() - 1);
for (int i = 0; i < es.size(); i++) {
GalleryInfo gi = parseGalleryInfoThumbVersion(es.get(i));
if (null != gi) {
list.add(gi);
}
}
result.galleryInfoList = list;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Can't parse gallery list", body);
}
}
return result;
}
}
@@ -0,0 +1,74 @@
/*
* Copyright 2019 Hippo Seven
*
* 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.
*/
package com.hippo.ehviewer.client.parser;
import android.text.TextUtils;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.yorozuya.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONException;
import org.json.JSONObject;
public class GalleryPageApiParser {
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<img[^>]*src=\"([^\"]+)\" style");
private static final Pattern PATTERN_SKIP_HATH_KEY = Pattern.compile("onclick=\"return nl\\('([^\\)]+)'\\)");
private static final Pattern PATTERN_ORIGIN_IMAGE_URL = Pattern.compile("<a href=\"([^\"]+)fullimg.php([^\"]+)\">");
public static Result parse(String body) throws ParseException {
try {
Matcher m;
Result result = new Result();
JSONObject jo = new JSONObject(body);
if (jo.has("error")) {
throw new ParseException(jo.getString("error"), body);
}
String i3 = jo.getString("i3");
m = PATTERN_IMAGE_URL.matcher(i3);
if (m.find()) {
result.imageUrl = StringUtils.unescapeXml(StringUtils.trim(m.group(1)));
}
String i6 = jo.getString("i6");
m = PATTERN_SKIP_HATH_KEY.matcher(i6);
if (m.find()) {
result.skipHathKey = StringUtils.unescapeXml(StringUtils.trim(m.group(1)));
}
String i7 = jo.getString("i7");
m = PATTERN_ORIGIN_IMAGE_URL.matcher(i7);
if (m.find()) {
result.originImageUrl = StringUtils.unescapeXml(m.group(1)) + "fullimg.php" + StringUtils.unescapeXml(m.group(2));
}
if (!TextUtils.isEmpty(result.imageUrl)) {
return result;
} else {
throw new ParseException("Parse image url and skip hath key error", body);
}
} catch (JSONException e) {
throw new ParseException("Can't parse json", body, e);
}
}
public static class Result {
public String imageUrl;
public String skipHathKey;
public String originImageUrl;
}
}
@@ -17,10 +17,8 @@
package com.hippo.ehviewer.client.parser;
import android.text.TextUtils;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.yorozuya.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -29,6 +27,8 @@ public class GalleryPageParser {
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<img[^>]*src=\"([^\"]+)\" style");
private static final Pattern PATTERN_SKIP_HATH_KEY = Pattern.compile("onclick=\"return nl\\('([^\\)]+)'\\)");
private static final Pattern PATTERN_ORIGIN_IMAGE_URL = Pattern.compile("<a href=\"([^\"]+)fullimg.php([^\"]+)\">");
// TODO Not sure about the size of show keys
private static final Pattern PATTERN_SHOW_KEY = Pattern.compile("var showkey=\"([0-9a-z]+)\";");
public static Result parse(String body) throws ParseException {
Matcher m;
@@ -45,11 +45,15 @@ public class GalleryPageParser {
if (m.find()) {
result.originImageUrl = StringUtils.unescapeXml(m.group(1)) + "fullimg.php" + StringUtils.unescapeXml(m.group(2));
}
m = PATTERN_SHOW_KEY.matcher(body);
if (m.find()) {
result.showKey = m.group(1);
}
if (!TextUtils.isEmpty(result.imageUrl)) {
if (!TextUtils.isEmpty(result.imageUrl) && !TextUtils.isEmpty(result.showKey)) {
return result;
} else {
throw new ParseException("Parse image url and skip hath key error", body);
throw new ParseException("Parse image url and show error", body);
}
}
@@ -57,5 +61,6 @@ public class GalleryPageParser {
public String imageUrl;
public String skipHathKey;
public String originImageUrl;
public String showKey;
}
}
@@ -16,8 +16,9 @@
package com.hippo.ehviewer.client.parser;
import android.support.annotation.Nullable;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.yorozuya.NumberUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -47,9 +48,12 @@ public final class GalleryPageUrlParser {
Matcher m = pattern.matcher(url);
if (m.find()) {
Result result = new Result();
result.gid = Long.parseLong(m.group(2));
result.gid = NumberUtils.parseLongSafely(m.group(2), -1L);
result.pToken = m.group(1);
result.page = Integer.parseInt(m.group(3)) - 1;
result.page = NumberUtils.parseIntSafely(m.group(3), 0) - 1;
if (result.gid < 0 || result.page < 0) {
return null;
}
return result;
} else {
return null;
@@ -16,6 +16,7 @@
package com.hippo.ehviewer.client.parser;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import java.text.DateFormat;
@@ -39,11 +40,15 @@ public class ParserUtils {
return StringUtils.unescapeXml(str).trim();
}
public static int parseInt(String str) {
return Integer.parseInt(trim(str).replace(",", ""));
public static int parseInt(String str, int defValue) {
return NumberUtils.parseIntSafely(trim(str).replace(",", ""), defValue);
}
public static long parseLong(String str) {
return Long.parseLong(trim(str).replace(",", ""));
public static long parseLong(String str, long defValue) {
return NumberUtils.parseLongSafely(trim(str).replace(",", ""), defValue);
}
public static float parseFloat(String str, float defValue) {
return NumberUtils.parseFloatSafely(trim(str).replace(",", ""), defValue);
}
}
@@ -1,61 +0,0 @@
/*
* Copyright 2016 Hippo Seven
*
* 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.
*/
package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class WhatsHotParser {
@SuppressWarnings("ConstantConditions")
public static List<GalleryInfo> parse(String body) throws ParseException {
try {
List<GalleryInfo> galleryInfoList = new ArrayList<>(15);
Document d = Jsoup.parse(body);
Element pp = d.getElementById("pp");
Elements id1List = pp.getElementsByClass("id1");
for (int i = 0, n = id1List.size(); i < n; i++) {
GalleryInfo galleryInfo = new GalleryInfo();
Element id1 = id1List.get(i);
Element id3 = JsoupUtils.getElementByClass(id1, "id3");
Element temp = JsoupUtils.getElementByTag(id3, "a");
String url = temp.attr("href");
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parse(url);
galleryInfo.gid = result.gid;
galleryInfo.token = result.token;
temp = JsoupUtils.getElementByTag(temp, "img");
galleryInfo.thumb = EhUtils.handleThumbUrlResolution(temp.attr("src"));
galleryInfo.title = temp.attr("title");
galleryInfo.generateSLang();
galleryInfoList.add(galleryInfo);
}
return galleryInfoList;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Parse whats hot error", body);
}
}
}
@@ -19,10 +19,9 @@ package com.hippo.ehviewer.download;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.dao.DownloadInfo;
@@ -32,6 +31,7 @@ import com.hippo.ehviewer.spider.SpiderInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.ObjectUtils;
@@ -39,7 +39,6 @@ import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.collect.LongList;
import com.hippo.yorozuya.collect.SparseIJArray;
import com.hippo.yorozuya.collect.SparseJLArray;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@@ -295,6 +294,9 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
}
// Make sure download is running
ensureDownload();
// Add it to history
EhDB.putHistoryInfo(info);
}
}
@@ -611,7 +613,7 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
}
return null;
}
}.execute();
}.executeOnExecutor(IoThreadPoolExecutor.getInstance());
}
// Update in DB
@@ -27,11 +27,10 @@ import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhUtils;
@@ -46,7 +45,6 @@ import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.collect.LongList;
import com.hippo.yorozuya.collect.SparseJBArray;
import com.hippo.yorozuya.collect.SparseJLArray;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -18,15 +18,16 @@ package com.hippo.ehviewer.gallery;
import com.hippo.a7zip.ArchiveException;
import com.hippo.a7zip.InArchive;
import com.hippo.a7zip.InStream;
import com.hippo.a7zip.PropID;
import com.hippo.a7zip.PropType;
import com.hippo.a7zip.SequentialOutStream;
import com.hippo.unifile.UniRandomAccessFile;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import okio.Store;
import okio.UniRandomAccessFileStore;
class A7ZipArchive implements Closeable {
@@ -69,8 +70,8 @@ class A7ZipArchive implements Closeable {
}
static A7ZipArchive create(UniRandomAccessFile file) throws ArchiveException {
Store store = new UniRandomAccessFileStore(file);
InArchive archive = InArchive.create(store);
InStream store = new UniRandomAccessFileInStream(file);
InArchive archive = InArchive.open(store);
if ((archive.getArchivePropertyType(PropID.ENCRYPTED) == PropType.BOOL && archive.getArchiveBooleanProperty(PropID.ENCRYPTED))
|| (archive.getArchivePropertyType(PropID.SOLID) == PropType.BOOL && archive.getArchiveBooleanProperty(PropID.SOLID))
|| (archive.getArchivePropertyType(PropID.IS_VOLUME) == PropType.BOOL && archive.getArchiveBooleanProperty(PropID.IS_VOLUME))) {
@@ -96,7 +97,60 @@ class A7ZipArchive implements Closeable {
}
void extract(OutputStream os) throws ArchiveException {
archive.extractEntry(index, os);
archive.extractEntry(index, new OutputStreamSequentialOutStream(os));
}
}
private static class UniRandomAccessFileInStream implements InStream {
private UniRandomAccessFile file;
public UniRandomAccessFileInStream(UniRandomAccessFile file) {
this.file = file;
}
@Override
public void seek(long pos) throws IOException {
file.seek(pos);
}
@Override
public long tell() throws IOException {
return file.getFilePointer();
}
@Override
public long size() throws IOException {
return file.length();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return file.read(b, off, len);
}
@Override
public void close() throws IOException {
file.close();
}
}
private static class OutputStreamSequentialOutStream implements SequentialOutStream {
private OutputStream stream;
public OutputStreamSequentialOutStream(OutputStream stream) {
this.stream = stream;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
stream.write(b, off, len);
}
@Override
public void close() throws IOException {
stream.close();
}
}
}
@@ -19,8 +19,8 @@ package com.hippo.ehviewer.gallery;
import android.content.Context;
import android.net.Uri;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.a7zip.ArchiveException;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
@@ -17,9 +17,9 @@
package com.hippo.ehviewer.gallery;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.glgallery.GalleryPageView;
@@ -17,16 +17,14 @@
package com.hippo.ehviewer.gallery;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.spider.SpiderQueen;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.SimpleHandler;
import java.util.Locale;
public class EhGalleryProvider extends GalleryProvider2 implements SpiderQueen.OnSpiderListener {
@@ -16,9 +16,8 @@
package com.hippo.ehviewer.gallery;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.unifile.UniFile;
@@ -16,7 +16,7 @@
package com.hippo.ehviewer.gallery;
import android.support.annotation.NonNull;
import androidx.annotation.NonNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -88,6 +88,7 @@ class Pipe {
public void close() {
synchronized (Pipe.this) {
inClosed = true;
Pipe.this.notifyAll();
}
}
};
@@ -141,6 +142,7 @@ class Pipe {
public void close() {
synchronized (Pipe.this) {
outClosed = true;
Pipe.this.notifyAll();
}
}
};
@@ -17,10 +17,9 @@
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
@@ -17,9 +17,8 @@
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
import com.hippo.preference.MessagePreference;
@@ -17,10 +17,9 @@
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.widget.CategoryTable;
@@ -17,11 +17,10 @@
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CheckBox;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.preference.DialogPreference;
@@ -19,9 +19,9 @@ package com.hippo.ehviewer.preference;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
@@ -20,64 +20,71 @@ import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import androidx.appcompat.app.AlertDialog;
import com.google.android.material.textfield.TextInputLayout;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhProxySelector;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.network.InetValidator;
import com.hippo.preference.DialogPreference;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.ViewUtils;
public class HatHProxyPreference extends DialogPreference implements View.OnClickListener {
public class ProxyPreference extends DialogPreference implements View.OnClickListener {
@Nullable
private SwitchCompat mEnable;
@Nullable
private Spinner mType;
private TextInputLayout mIpInputLayout;
@Nullable
private EditText mIp;
@Nullable
private TextInputLayout mPortInputLayout;
@Nullable
private EditText mPort;
@Nullable
private TextInputLayout mPasskeyInputLayout;
@Nullable
private EditText mPasskey;
public HatHProxyPreference(Context context) {
public ProxyPreference(Context context) {
super(context);
init();
}
public HatHProxyPreference(Context context, AttributeSet attrs) {
public ProxyPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public HatHProxyPreference(Context context, AttributeSet attrs, int defStyleAttr) {
public ProxyPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setDialogLayoutResource(R.layout.preference_dialog_hath_proxy);
updateSummary(Settings.getHathProxy(), Settings.getHathIp(), Settings.getHathPort());
setDialogLayoutResource(R.layout.preference_dialog_proxy);
updateSummary(Settings.getProxyType(), Settings.getProxyIp(), Settings.getProxyPort());
}
private void updateSummary(boolean hathProxy, String hathIp, int hathPort) {
if (InetValidator.isValidInet4Address(hathIp) && InetValidator.isValidInetPort(hathPort)) {
private String getProxyTypeText(Context context, int type) {
String[] array = context.getResources().getStringArray(R.array.proxy_types);
return array[MathUtils.clamp(type, 0, array.length - 1)];
}
private void updateSummary(int type, String ip, int port) {
if ((type == EhProxySelector.TYPE_HTTP || type == EhProxySelector.TYPE_SOCKS)
&& (TextUtils.isEmpty(ip) || !InetValidator.isValidInetPort(port)) ) {
type = EhProxySelector.TYPE_SYSTEM;
}
if (type == EhProxySelector.TYPE_HTTP || type == EhProxySelector.TYPE_SOCKS) {
Context context = getContext();
setSummary(context.getString(R.string.settings_eh_hath_proxy_summary_1,
context.getString(hathProxy ? R.string.enabled : R.string.disabled), hathIp, hathPort));
setSummary(context.getString(R.string.settings_advanced_proxy_summary_1,
getProxyTypeText(context, type),
ip,
port));
} else {
setSummary(R.string.settings_eh_hath_proxy_summary_2);
Context context = getContext();
setSummary(context.getString(R.string.settings_advanced_proxy_summary_2,
getProxyTypeText(context, type)));
}
}
@@ -94,73 +101,63 @@ public class HatHProxyPreference extends DialogPreference implements View.OnClic
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(this);
mEnable = (SwitchCompat) ViewUtils.$$(dialog, R.id.enable);
mType = (Spinner) ViewUtils.$$(dialog, R.id.type);
mIpInputLayout = (TextInputLayout) ViewUtils.$$(dialog, R.id.ip_input_layout);
mIp = (EditText) ViewUtils.$$(dialog, R.id.ip);
mPortInputLayout = (TextInputLayout) ViewUtils.$$(dialog, R.id.port_input_layout);
mPort = (EditText) ViewUtils.$$(dialog, R.id.port);
mPasskeyInputLayout = (TextInputLayout) ViewUtils.$$(dialog, R.id.passkey_input_layout);
mPasskey = (EditText) ViewUtils.$$(dialog, R.id.passkey);
mEnable.setChecked(Settings.getHathProxy());
String ip = Settings.getHathIp();
if (!InetValidator.isValidInet4Address(ip)) {
ip = null;
}
int type = Settings.getProxyType();
String[] array = getContext().getResources().getStringArray(R.array.proxy_types);
mType.setSelection(MathUtils.clamp(type, 0, array.length));
mIp.setText(Settings.getProxyIp());
String portString;
int port = Settings.getHathPort();
int port = Settings.getProxyPort();
if (!InetValidator.isValidInetPort(port)) {
portString = null;
} else {
portString = Integer.toString(Settings.getHathPort());
portString = Integer.toString(port);
}
mIp.setText(ip);
mPort.setText(portString);
mPasskey.setText(Settings.getHathPasskey());
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
mEnable = null;
mType = null;
mIpInputLayout = null;
mIp = null;
mPortInputLayout = null;
mPort = null;
mPasskeyInputLayout = null;
mPasskey = null;
}
@Override
public void onClick(View v) {
Dialog dialog = getDialog();
Context context = getContext();
if (null == dialog || null == context || null == mEnable ||
if (null == dialog || null == context || null == mType ||
null == mIpInputLayout || null == mIp ||
null == mPortInputLayout || null == mPort ||
null == mPasskeyInputLayout || null == mPasskey) {
null == mPortInputLayout || null == mPort) {
return;
}
boolean enable = mEnable.isChecked();
int type = mType.getSelectedItemPosition();
String ip = mIp.getText().toString().trim();
if (ip.isEmpty()) {
if (enable) {
if (type == EhProxySelector.TYPE_HTTP || type == EhProxySelector.TYPE_SOCKS) {
mIpInputLayout.setError(context.getString(R.string.text_is_empty));
return;
}
} else if (!InetValidator.isValidInet4Address(ip)) {
mIpInputLayout.setError(context.getString(R.string.domain_not_supported));
return;
} else {
mIpInputLayout.setError(null);
}
mIpInputLayout.setError(null);
int port;
String portString = mPort.getText().toString().trim();
if (portString.isEmpty()) {
if (enable) {
if (type == EhProxySelector.TYPE_HTTP || type == EhProxySelector.TYPE_SOCKS) {
mPortInputLayout.setError(context.getString(R.string.text_is_empty));
return;
} else {
@@ -173,19 +170,19 @@ public class HatHProxyPreference extends DialogPreference implements View.OnClic
port = -1;
}
if (!InetValidator.isValidInetPort(port)) {
mPortInputLayout.setError(context.getString(R.string.invalid_port));
mPortInputLayout.setError(context.getString(R.string.proxy_invalid_port));
return;
}
}
mPortInputLayout.setError(null);
String passkey = mPasskey.getText().toString();
Settings.putProxyType(type);
Settings.putProxyIp(ip);
Settings.putProxyPort(port);
Settings.putHathProxy(enable);
Settings.putHathIp(ip);
Settings.putHathPort(port);
Settings.putHathPasskey(passkey);
updateSummary(type, ip, port);
updateSummary(enable, ip, port);
EhApplication.getEhProxySelector(getContext()).updateProxy();
dialog.dismiss();
}
@@ -20,14 +20,15 @@ import android.app.Activity;
import android.content.Context;
import android.os.Parcel;
import android.preference.Preference;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.ehviewer.spider.SpiderInfo;
@@ -134,7 +135,7 @@ public class RestoreDownloadPreference extends TaskPreference {
}
try {
return EhEngine.fillGalleryListByApi(null, mHttpClient, new ArrayList<GalleryInfo>(restoreItemList));
return EhEngine.fillGalleryListByApi(null, mHttpClient, new ArrayList<GalleryInfo>(restoreItemList), EhUrl.getReferer());
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
@@ -0,0 +1,72 @@
/*
* Copyright 2019 Hippo Seven
*
* 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.
*/
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.material.snackbar.Snackbar;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.preference.ActivityPreference;
import okhttp3.HttpUrl;
public class SignInRequiredActivityPreference extends ActivityPreference {
private View view;
public SignInRequiredActivityPreference(Context context) {
super(context);
}
public SignInRequiredActivityPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SignInRequiredActivityPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected View onCreateView(ViewGroup parent) {
return view = super.onCreateView(parent);
}
@Override
protected void onClick() {
EhCookieStore store = EhApplication.getEhCookieStore(getContext());
HttpUrl e = HttpUrl.get(EhUrl.HOST_E);
HttpUrl ex = HttpUrl.get(EhUrl.HOST_EX);
if (store.contains(e, EhCookieStore.KEY_IPD_MEMBER_ID) ||
store.contains(e, EhCookieStore.KEY_IPD_PASS_HASH) ||
store.contains(ex, EhCookieStore.KEY_IPD_MEMBER_ID) ||
store.contains(ex, EhCookieStore.KEY_IPD_PASS_HASH)) {
super.onClick();
} else {
if (view != null) {
Snackbar.make(view, R.string.error_please_login_first, 3000).show();
} else {
Toast.makeText(getContext(), R.string.error_please_login_first, Toast.LENGTH_LONG).show();
}
}
}
}
@@ -17,10 +17,9 @@
package com.hippo.ehviewer.preference;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.preference.MessagePreference;
@@ -21,15 +21,16 @@ import android.content.Context;
import android.os.AsyncTask;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.customview.view.AbsSavedState;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.preference.DialogPreference;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.IntIdGenerator;
public abstract class TaskPreference extends DialogPreference {
@@ -62,7 +63,7 @@ public abstract class TaskPreference extends DialogPreference {
mTask = onCreateTask();
mTask.setPreference(this);
mTaskId = ((EhApplication) getContext().getApplicationContext()).putGlobalStuff(mTask);
mTask.execute();
mTask.executeOnExecutor(IoThreadPoolExecutor.getInstance());
}
}
@@ -123,11 +124,11 @@ public abstract class TaskPreference extends DialogPreference {
super.onRestoreInstanceState(myState.getSuperState());
}
private static class SavedState extends BaseSavedState {
private static class SavedState extends AbsSavedState {
int asyncTaskId;
public SavedState(Parcel source) {
super(source);
super(source, SavedState.class.getClassLoader());
asyncTaskId = source.readInt();
}
@@ -18,9 +18,8 @@ package com.hippo.ehviewer.spider;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.support.annotation.Nullable;
import android.webkit.MimeTypeMap;
import androidx.annotation.Nullable;
import com.hippo.beerbelly.SimpleDiskCache;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.Settings;
@@ -38,7 +37,6 @@ import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.Utilities;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
@@ -16,16 +16,14 @@
package com.hippo.ehviewer.spider;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.NumberUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -20,21 +20,19 @@ import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Process;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.webkit.MimeTypeMap;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import com.hippo.beerbelly.SimpleDiskCache;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhConfig;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.EhRequestBuilder;
import com.hippo.ehviewer.client.EhUrl;
@@ -43,6 +41,7 @@ import com.hippo.ehviewer.client.data.PreviewSet;
import com.hippo.ehviewer.client.exception.Image509Exception;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.GalleryDetailParser;
import com.hippo.ehviewer.client.parser.GalleryPageApiParser;
import com.hippo.ehviewer.client.parser.GalleryPageParser;
import com.hippo.ehviewer.client.parser.GalleryPageUrlParser;
import com.hippo.ehviewer.gallery.GalleryProvider2;
@@ -53,6 +52,7 @@ import com.hippo.streampipe.InputStreamPipe;
import com.hippo.streampipe.OutputStreamPipe;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.OSUtils;
@@ -61,7 +61,6 @@ import com.hippo.yorozuya.Utilities;
import com.hippo.yorozuya.collect.SparseJLArray;
import com.hippo.yorozuya.thread.PriorityThread;
import com.hippo.yorozuya.thread.PriorityThreadFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -78,7 +77,6 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
@@ -164,6 +162,9 @@ public final class SpiderQueen implements Runnable {
private final AtomicInteger mDownloadedPages = new AtomicInteger(0);
private final AtomicInteger mFinishedPages = new AtomicInteger(0);
private AtomicReference<String> showKey = new AtomicReference<>();
private final Object showKeyLock = new Object();
// Store page error
private final ConcurrentHashMap<Integer, String> mPageErrorMap = new ConcurrentHashMap<>();
// Store page download percent
@@ -669,7 +670,7 @@ public final class SpiderQueen implements Runnable {
writeSpiderInfoToLocal(spiderInfo);
return null;
}
}.execute();
}.executeOnExecutor(IoThreadPoolExecutor.getInstance());
}
}
@@ -734,14 +735,14 @@ public final class SpiderQueen implements Runnable {
}
}
private SpiderInfo readSpiderInfoFromInternet(EhConfig config) {
private SpiderInfo readSpiderInfoFromInternet() {
try {
SpiderInfo spiderInfo = new SpiderInfo();
spiderInfo.gid = mGalleryInfo.gid;
spiderInfo.token = mGalleryInfo.token;
Request request = new EhRequestBuilder(EhUrl.getGalleryDetailUrl(
mGalleryInfo.gid, mGalleryInfo.token, 0, false), config).build();
mGalleryInfo.gid, mGalleryInfo.token, 0, false), EhUrl.getReferer()).build();
Response response = mHttpClient.newCall(request).execute();
String body = response.body().string();
@@ -755,7 +756,7 @@ public final class SpiderQueen implements Runnable {
}
}
private String getPTokenFromInternet(int index, EhConfig config) {
private String getPTokenFromInternet(int index) {
SpiderInfo spiderInfo = mSpiderInfo.get();
if (spiderInfo == null) {
return null;
@@ -775,11 +776,12 @@ public final class SpiderQueen implements Runnable {
try {
String url = EhUrl.getGalleryDetailUrl(
mGalleryInfo.gid, mGalleryInfo.token, previewIndex, false);
String referer = EhUrl.getReferer();
if (DEBUG_PTOKEN) {
Log.d(TAG, "index " + index + ", previewIndex " + previewIndex +
", previewPerPage " + spiderInfo.previewPerPage+ ", url " + url);
}
Request request = new EhRequestBuilder(url, config).build();
Request request = new EhRequestBuilder(url, referer).build();
Response response = mHttpClient.newCall(request).execute();
String body = response.body().string();
readPreviews(body, previewIndex, spiderInfo);
@@ -825,11 +827,6 @@ public final class SpiderQueen implements Runnable {
}
private void runInternal() {
// Get EhConfig
EhConfig config = Settings.getEhConfig().clone();
config.previewSize = EhConfig.PREVIEW_SIZE_NORMAL;
config.setDirty();
// Read spider info
SpiderInfo spiderInfo = readSpiderInfoFromLocal();
@@ -840,7 +837,7 @@ public final class SpiderQueen implements Runnable {
// Spider info from internet
if (spiderInfo == null) {
spiderInfo = readSpiderInfoFromInternet(config);
spiderInfo = readSpiderInfoFromInternet();
}
// Error! Can't get spiderInfo
@@ -911,10 +908,10 @@ public final class SpiderQueen implements Runnable {
}
// Get pToken from internet
pToken = getPTokenFromInternet(index, config);
pToken = getPTokenFromInternet(index);
if (null == pToken) {
// Preview size may changed, so try to get pToken twice
pToken = getPTokenFromInternet(index, config);
pToken = getPTokenFromInternet(index);
}
if (null == pToken) {
@@ -1037,8 +1034,20 @@ public final class SpiderQueen implements Runnable {
return pageUrl;
}
private GalleryPageParser.Result getImageUrl(int index, String pageUrl) throws Throwable {
GalleryPageParser.Result result = EhEngine.getGalleryPage(null, mHttpClient, pageUrl);
private GalleryPageParser.Result fetchPageResultFromHtml(int index, String pageUrl) throws Throwable {
GalleryPageParser.Result result = EhEngine.getGalleryPage(null, mHttpClient, pageUrl, mGalleryInfo.gid, mGalleryInfo.token);
if (StringUtils.endsWith(result.imageUrl, URL_509_SUFFIX_ARRAY)) {
// Get 509
// Notify listeners
notifyGet509(index);
throw new Image509Exception();
}
return result;
}
private GalleryPageApiParser.Result fetchPageResultFromApi(long gid, int index, String pToken, String showKey, String previousPToken) throws Throwable {
GalleryPageApiParser.Result result = EhEngine.getGalleryPageApi(null, mHttpClient, gid, index, pToken, showKey, previousPToken);
if (StringUtils.endsWith(result.imageUrl, URL_509_SUFFIX_ARRAY)) {
// Get 509
// Notify listeners
@@ -1050,70 +1059,116 @@ public final class SpiderQueen implements Runnable {
}
// false for stop
private boolean downloadImage(long gid, int index, String pToken, boolean force) {
List<String> skipHathKeys = new ArrayList<>(5);
private boolean downloadImage(long gid, int index, String pToken, String previousPToken, boolean force) {
String skipHathKey = null;
String imageUrl;
String error = null;
List<String> skipHathKeys = new ArrayList<>(5);
String originImageUrl = null;
String pageUrl = null;
String error = null;
boolean forceHtml = false;
boolean interrupt = false;
boolean leakSkipHathKey = false;
Log.d("TAG", "index = " + index);
// Try twice
for (int i = 0; i < 5; i++) {
if (leakSkipHathKey) {
break;
}
String imageUrl = null;
String localShowKey;
pageUrl = getPageUrl(gid, index, pToken, pageUrl, skipHathKey);
// Check show key
synchronized (showKeyLock) {
localShowKey = showKey.get();
if (localShowKey == null || forceHtml) {
if (leakSkipHathKey) {
break;
}
GalleryPageParser.Result result = null;
try {
result = getImageUrl(index, pageUrl);
} catch (Image509Exception e) {
error = GetText.getString(R.string.error_509);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
error = ExceptionUtils.getReadableString(e);
}
if (result == null) {
// Get image url failed
break;
}
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
error = "Interrupted";
interrupt = true;
break;
}
// Try to get show key
pageUrl = getPageUrl(gid, index, pToken, pageUrl, skipHathKey);
try {
GalleryPageParser.Result result = fetchPageResultFromHtml(index, pageUrl);
imageUrl = result.imageUrl;
skipHathKey = result.skipHathKey;
originImageUrl = result.originImageUrl;
localShowKey = result.showKey;
if (Settings.getDownloadOriginImage() && !TextUtils.isEmpty(result.originImageUrl)) {
imageUrl = result.originImageUrl;
} else {
imageUrl = result.imageUrl;
}
skipHathKey = result.skipHathKey;
if (!TextUtils.isEmpty(skipHathKey)) {
if (skipHathKeys.contains(skipHathKey)) {
// Duplicate skip hath key, don't run next turn
leakSkipHathKey = true;
} else {
skipHathKeys.add(skipHathKey);
if (!TextUtils.isEmpty(skipHathKey)) {
if (skipHathKeys.contains(skipHathKey)) {
// Duplicate skip hath key
leakSkipHathKey = true;
} else {
skipHathKeys.add(skipHathKey);
}
} else {
leakSkipHathKey = true;
}
showKey.lazySet(result.showKey);
} catch (Image509Exception e) {
error = GetText.getString(R.string.error_509);
break;
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
error = ExceptionUtils.getReadableString(e);
break;
}
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
error = "Interrupted";
interrupt = true;
break;
}
}
} else {
// No skip hath key, don't run next turn
leakSkipHathKey = true;
}
// If it is force request, skip first image
//if (force && i == 0) {
// continue;
//}
if (imageUrl == null) {
if (localShowKey == null) {
error = "ShowKey error";
break;
}
try {
GalleryPageApiParser.Result result = fetchPageResultFromApi(gid, index, pToken, localShowKey, previousPToken);
imageUrl = result.imageUrl;
skipHathKey = result.skipHathKey;
originImageUrl = result.originImageUrl;
} catch (Image509Exception e) {
error = GetText.getString(R.string.error_509);
break;
} catch (Throwable e) {
if (e instanceof ParseException && "Key mismatch".equals(e.getMessage())) {
// Show key is wrong, enter a new loop to get the new show key
showKey.compareAndSet(localShowKey, null);
continue;
} else {
ExceptionUtils.throwIfFatal(e);
error = ExceptionUtils.getReadableString(e);
break;
}
}
// Check interrupted
if (Thread.currentThread().isInterrupted()) {
error = "Interrupted";
interrupt = true;
break;
}
}
String targetImageUrl;
String referer;
if (Settings.getDownloadOriginImage() && !TextUtils.isEmpty(originImageUrl)) {
targetImageUrl = originImageUrl;
referer = EhUrl.getPageUrl(gid, index, pToken);
} else {
targetImageUrl = imageUrl;
referer = null;
}
if (targetImageUrl == null) {
error = "TargetImageUrl error";
break;
}
if (DEBUG_LOG) {
Log.d(TAG, imageUrl);
Log.d(TAG, targetImageUrl);
}
// Download image
@@ -1124,7 +1179,7 @@ public final class SpiderQueen implements Runnable {
Log.d(TAG, "Start download image " + index);
}
Call call = mHttpClient.newCall(new EhRequestBuilder(imageUrl).build());
Call call = mHttpClient.newCall(new EhRequestBuilder(targetImageUrl, referer).build());
Response response = call.execute();
ResponseBody responseBody = response.body();
@@ -1132,11 +1187,13 @@ public final class SpiderQueen implements Runnable {
// Maybe 404
response.close();
error = "Bad code: " + response.code();
forceHtml = true;
continue;
}
if (responseBody == null) {
error = "Empty response body";
forceHtml = true;
continue;
}
@@ -1190,6 +1247,7 @@ public final class SpiderQueen implements Runnable {
if (receivedSize < contentLength) {
Log.e(TAG, "Can't download all of image data");
error = "Incomplete";
forceHtml = true;
continue;
} else if (receivedSize > contentLength) {
Log.w(TAG, "Received data is more than contentLength");
@@ -1213,6 +1271,7 @@ public final class SpiderQueen implements Runnable {
} catch (IOException e) {
e.printStackTrace();
error = GetText.getString(R.string.error_socket);
forceHtml = true;
} finally {
IOUtils.closeQuietly(is);
if (null != pipe) {
@@ -1335,6 +1394,36 @@ public final class SpiderQueen implements Runnable {
return false;
}
String previousPToken = null;
int previousIndex = index - 1;
// Get token
while (previousIndex >= 0 && !Thread.currentThread().isInterrupted()) {
synchronized (mPTokenLock) {
previousPToken = spiderInfo.pTokenMap.get(previousIndex);
}
if (previousPToken == null) {
mRequestPTokenQueue.add(previousIndex);
// Notify Queen
synchronized (mQueenLock) {
mQueenLock.notify();
}
// Wait
synchronized (mWorkerLock) {
try {
mWorkerLock.wait();
} catch (InterruptedException e) {
// Interrupted
if (DEBUG_LOG) {
Log.d(TAG, Thread.currentThread().getName() + " Interrupted");
}
break;
}
}
} else {
break;
}
}
if (SpiderInfo.TOKEN_FAILED.equals(pToken)) {
// Get token failed
updatePageState(index, STATE_FAILED, GetText.getString(R.string.error_get_ptoken_error));
@@ -1342,7 +1431,7 @@ public final class SpiderQueen implements Runnable {
}
// Get image url
return downloadImage(mGid, index, pToken, force);
return downloadImage(mGid, index, pToken, previousPToken, force);
}
@Override
@@ -22,9 +22,8 @@ import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import androidx.appcompat.app.AlertDialog;
import com.hippo.app.ListCheckBoxDialogBuilder;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhDB;
@@ -33,7 +32,6 @@ import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.UrlOpener;
import com.hippo.ehviewer.client.EhClient;
import com.hippo.ehviewer.client.EhRequest;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.dao.DownloadLabel;
import com.hippo.ehviewer.download.DownloadManager;
@@ -42,19 +40,20 @@ import com.hippo.ehviewer.ui.scene.BaseScene;
import com.hippo.text.Html;
import com.hippo.unifile.UniFile;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import com.hippo.yorozuya.collect.LongList;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;
public final class CommonOperations {
@@ -65,7 +64,7 @@ public final class CommonOperations {
public static void checkUpdate(Activity activity, boolean feedback) {
if (!UPDATING) {
UPDATING = true;
new UpdateTask(activity, feedback).execute();
new UpdateTask(activity, feedback).executeOnExecutor(IoThreadPoolExecutor.getInstance());
}
}
@@ -216,17 +215,13 @@ public final class CommonOperations {
System.arraycopy(favCat, 0, items, 1, 10);
if (slot >= -1 && slot <= 9) {
String newFavoriteName = slot >= 0 ? items[slot + 1] : null;
doAddToFavorites(activity, galleryInfo, slot, galleryInfo instanceof GalleryDetail
? new UpdateFavoriteNameCallback(listener, (GalleryDetail) galleryInfo, newFavoriteName)
: listener);
doAddToFavorites(activity, galleryInfo, slot, new DelegateFavoriteCallback(listener, galleryInfo, newFavoriteName, slot));
} else {
new ListCheckBoxDialogBuilder(activity, items,
(builder, dialog, position) -> {
int slot1 = position - 1;
String newFavoriteName = (slot1 >= 0 && slot1 <= 9) ? items[slot1+1] : null;
doAddToFavorites(activity, galleryInfo, slot1, galleryInfo instanceof GalleryDetail
? new UpdateFavoriteNameCallback(listener, (GalleryDetail) galleryInfo, newFavoriteName)
: listener);
doAddToFavorites(activity, galleryInfo, slot1, new DelegateFavoriteCallback(listener, galleryInfo, newFavoriteName, slot1));
if (builder.isChecked()) {
Settings.putDefaultFavSlot(slot1);
} else {
@@ -241,33 +236,36 @@ public final class CommonOperations {
public static void removeFromFavorites(Activity activity, GalleryInfo galleryInfo,
final EhClient.Callback<Void> listener) {
EhDB.removeLocalFavorites(galleryInfo.gid);
EhClient client = EhApplication.getEhClient(activity);
EhRequest request = new EhRequest();
request.setMethod(EhClient.METHOD_ADD_FAVORITES);
request.setArgs(galleryInfo.gid, galleryInfo.token, -1, "");
request.setCallback(galleryInfo instanceof GalleryDetail
? new UpdateFavoriteNameCallback(listener, (GalleryDetail) galleryInfo, null)
: listener);
request.setCallback(new DelegateFavoriteCallback(listener, galleryInfo, null, -2));
client.execute(request);
}
private static class UpdateFavoriteNameCallback implements EhClient.Callback<Void> {
private static class DelegateFavoriteCallback implements EhClient.Callback<Void> {
private final EhClient.Callback<Void> delegate;
private final GalleryDetail detail;
private final GalleryInfo info;
private final String newFavoriteName;
private final int slot;
UpdateFavoriteNameCallback(EhClient.Callback<Void> delegate, GalleryDetail detail,
String newFavoriteName) {
DelegateFavoriteCallback(EhClient.Callback<Void> delegate, GalleryInfo info,
String newFavoriteName, int slot) {
this.delegate = delegate;
this.detail = detail;
this.info = info;
this.newFavoriteName = newFavoriteName;
this.slot = slot;
}
@Override
public void onSuccess(Void result) {
detail.favoriteName = newFavoriteName;
info.favoriteName = newFavoriteName;
info.favoriteSlot = slot;
delegate.onSuccess(result);
EhApplication.getFavouriteStatusRouter().modifyFavourites(info.gid, slot);
}
@Override
@@ -281,11 +279,37 @@ public final class CommonOperations {
}
}
// TODO Add context if activity and context are different style
public static void startDownload(final MainActivity activity, final GalleryInfo galleryInfo, boolean forceDefault) {
startDownload(activity, Collections.singletonList(galleryInfo), forceDefault);
}
// TODO Add context if activity and context are different style
public static void startDownload(final MainActivity activity, final List<GalleryInfo> galleryInfos, boolean forceDefault) {
final DownloadManager dm = EhApplication.getDownloadManager(activity);
boolean justStart = forceDefault || dm.containDownloadInfo(galleryInfo.gid);
LongList toStart = new LongList();
List<GalleryInfo> toAdd = new ArrayList<>();
for (GalleryInfo gi : galleryInfos) {
if (dm.containDownloadInfo(gi.gid)) {
toStart.add(gi.gid);
} else {
toAdd.add(gi);
}
}
if (!toStart.isEmpty()) {
Intent intent = new Intent(activity, DownloadService.class);
intent.setAction(DownloadService.ACTION_START_RANGE);
intent.putExtra(DownloadService.KEY_GID_LIST, toStart);
activity.startService(intent);
}
if (toAdd.isEmpty()) {
activity.showTip(R.string.added_to_download_list, BaseScene.LENGTH_SHORT);
return;
}
boolean justStart = forceDefault;
String label = null;
// Get default download label
if (!justStart && Settings.getHasDefaultDownloadLabel()) {
@@ -299,12 +323,14 @@ public final class CommonOperations {
}
if (justStart) {
// Already in download list or get default label
Intent intent = new Intent(activity, DownloadService.class);
intent.setAction(DownloadService.ACTION_START);
intent.putExtra(DownloadService.KEY_LABEL, label);
intent.putExtra(DownloadService.KEY_GALLERY_INFO, galleryInfo);
activity.startService(intent);
// Got default label
for (GalleryInfo gi : toAdd) {
Intent intent = new Intent(activity, DownloadService.class);
intent.setAction(DownloadService.ACTION_START);
intent.putExtra(DownloadService.KEY_LABEL, label);
intent.putExtra(DownloadService.KEY_GALLERY_INFO, gi);
activity.startService(intent);
}
// Notify
activity.showTip(R.string.added_to_download_list, BaseScene.LENGTH_SHORT);
} else {
@@ -330,11 +356,13 @@ public final class CommonOperations {
}
}
// Start download
Intent intent = new Intent(activity, DownloadService.class);
intent.setAction(DownloadService.ACTION_START);
intent.putExtra(DownloadService.KEY_LABEL, label);
intent.putExtra(DownloadService.KEY_GALLERY_INFO, galleryInfo);
activity.startService(intent);
for (GalleryInfo gi : toAdd) {
Intent intent = new Intent(activity, DownloadService.class);
intent.setAction(DownloadService.ACTION_START);
intent.putExtra(DownloadService.KEY_LABEL, label);
intent.putExtra(DownloadService.KEY_GALLERY_INFO, gi);
activity.startService(intent);
}
// Save settings
if (builder.isChecked()) {
Settings.putHasDefaultDownloadLabel(true);
@@ -19,12 +19,12 @@ package com.hippo.ehviewer.ui;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.android.resource.AttrResources;
import com.hippo.ehviewer.R;
import com.hippo.ripple.Ripple;
@@ -19,10 +19,10 @@ package com.hippo.ehviewer.ui;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.hippo.android.resource.AttrResources;
import com.hippo.content.ContextLocalWrapper;
@@ -20,9 +20,9 @@ import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.view.WindowManager;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.hippo.android.resource.AttrResources;
import com.hippo.app.PrettyPreferenceActivity;
@@ -17,14 +17,14 @@
package com.hippo.ehviewer.ui;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.hippo.android.resource.AttrResources;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.ehviewer.R;
@@ -20,11 +20,6 @@ import android.content.DialogInterface;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
@@ -34,7 +29,11 @@ import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.textfield.TextInputLayout;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhFilter;
@@ -42,7 +41,6 @@ import com.hippo.ehviewer.dao.Filter;
import com.hippo.util.DrawableManager;
import com.hippo.view.ViewTransition;
import com.hippo.yorozuya.ViewUtils;
import java.util.List;
public class FilterActivity extends ToolbarActivity {
@@ -147,36 +145,18 @@ public class FilterActivity extends ToolbarActivity {
}
private void showDeleteFilterDialog(final Filter filter) {
int messageId;
switch (filter.mode) {
case EhFilter.MODE_TITLE:
messageId = R.string.delete_title_filter;
break;
case EhFilter.MODE_UPLOADER:
messageId = R.string.delete_uploader_filter;
break;
case EhFilter.MODE_TAG:
messageId = R.string.delete_tag_filter;
break;
default:
messageId = R.string.delete_filter;
}
String message = getString(messageId, filter.text);
String message = getString(R.string.delete_filter, filter.text);
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (DialogInterface.BUTTON_POSITIVE != which || null == mFilterList) {
return;
}
mFilterList.delete(filter);
if (null != mAdapter) {
mAdapter.notifyDataSetChanged();
}
updateView(true);
.setPositiveButton(R.string.delete, (dialog, which) -> {
if (DialogInterface.BUTTON_POSITIVE != which || null == mFilterList) {
return;
}
mFilterList.delete(filter);
if (null != mAdapter) {
mAdapter.notifyDataSetChanged();
}
updateView(true);
}).show();
}
@@ -244,7 +224,7 @@ public class FilterActivity extends ToolbarActivity {
public FilterHolder(View itemView) {
super(itemView);
text = (TextView) ViewUtils.$$(itemView, R.id.text);
icon = (ImageView) itemView.findViewById(R.id.icon);
icon = itemView.findViewById(R.id.icon);
if (null != icon) {
icon.setOnClickListener(this);
@@ -31,10 +31,6 @@ import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
@@ -48,6 +44,10 @@ import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;
import com.hippo.android.resource.AttrResources;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.BuildConfig;
@@ -375,6 +375,11 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
// Screen lightness
setScreenLightness(Settings.getCustomScreenLightness(), Settings.getScreenLightness());
// Cutout
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
}
if (Settings.getGuideGallery()) {
FrameLayout mainLayout = (FrameLayout) ViewUtils.$$(this, R.id.main);
mainLayout.addView(new GalleryGuideView(this));
@@ -1023,6 +1028,7 @@ public class GalleryActivity extends EhActivity implements SeekBar.OnSeekBarChan
switch (which) {
case 0: // Refresh
mGalleryProvider.removeCache(page);
mGalleryProvider.forceRequest(page);
break;
case 1: // Share
@@ -22,21 +22,23 @@ package com.hippo.ehviewer.ui;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputLayout;
import com.hippo.android.resource.AttrResources;
import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.LinearDividerItemDecoration;
@@ -79,14 +81,14 @@ public class HostsActivity extends ToolbarActivity
adapter = new HostsAdapter();
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
LinearDividerItemDecoration decoration = new LinearDividerItemDecoration(
LinearDividerItemDecoration.VERTICAL,
AttrResources.getAttrColor(this, R.attr.dividerColor),
LayoutUtils.dp2pix(this, 1));
decoration.setShowLastDivider(true);
recyclerView.addItemDecoration(decoration);
recyclerView.setSelector(Ripple.generateRippleDrawable(this, !AttrResources.getAttrBoolean(this, R.attr.isLightTheme)));
recyclerView.setSelector(Ripple.generateRippleDrawable(this, !AttrResources.getAttrBoolean(this, R.attr.isLightTheme), new ColorDrawable(Color.TRANSPARENT)));
recyclerView.setHasFixedSize(true);
recyclerView.setOnItemClickListener(this);
recyclerView.setPadding(
@@ -17,10 +17,9 @@
package com.hippo.ehviewer.ui;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.MenuItem;
import android.webkit.WebView;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.R;
public class LicenseActivity extends ToolbarActivity {
@@ -28,13 +28,6 @@ import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
@@ -43,11 +36,19 @@ import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AlertDialog;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.hippo.drawerlayout.DrawerLayout;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhTagDatabase;
import com.hippo.ehviewer.client.EhUrlOpener;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.ListUrlBuilder;
@@ -174,7 +175,7 @@ public final class MainActivity extends StageActivity
return new Announcer(SelectSiteScene.class);
} else {
Bundle args = new Bundle();
args.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_HOMEPAGE);
args.putString(GalleryListScene.KEY_ACTION, Settings.getLaunchPageGalleryListSceneAction());
return new Announcer(GalleryListScene.class).setArgs(args);
}
}
@@ -308,7 +309,7 @@ public final class MainActivity extends StageActivity
finish();
} else {
Bundle args = new Bundle();
args.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_HOMEPAGE);
args.putString(GalleryListScene.KEY_ACTION, Settings.getLaunchPageGalleryListSceneAction());
startScene(processAnnouncer(new Announcer(GalleryListScene.class).setArgs(args)));
}
}
@@ -362,6 +363,8 @@ public final class MainActivity extends StageActivity
} else {
onRestore(savedInstanceState);
}
EhTagDatabase.update(this);
}
private String getThemeText() {
@@ -626,6 +629,20 @@ public final class MainActivity extends StageActivity
}
}
public void setDrawerGestureBlocker(DrawerLayout.GestureBlocker gestureBlocker) {
if (mDrawerLayout != null) {
mDrawerLayout.setGestureBlocker(gestureBlocker);
}
}
public boolean isDrawersVisible() {
if (mDrawerLayout != null) {
return mDrawerLayout.isDrawersVisible();
} else {
return false;
}
}
public void setNavCheckedItem(@IdRes int resId) {
mNavCheckedItem = resId;
if (mNavView != null) {
@@ -647,7 +664,7 @@ public final class MainActivity extends StageActivity
public void showTip(CharSequence message, int length) {
if (null != mDrawerLayout) {
Snackbar.make(mDrawerLayout, message,
length == BaseScene.LENGTH_LONG ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT).show();
length == BaseScene.LENGTH_LONG ? 5000 : 3000).show();
} else {
Toast.makeText(this, message,
length == BaseScene.LENGTH_LONG ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
@@ -678,6 +695,11 @@ public final class MainActivity extends StageActivity
args.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_HOMEPAGE);
startSceneFirstly(new Announcer(GalleryListScene.class)
.setArgs(args));
} else if (id == R.id.nav_subscription) {
Bundle args = new Bundle();
args.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_SUBSCRIPTION);
startSceneFirstly(new Announcer(GalleryListScene.class)
.setArgs(args));
} else if (id == R.id.nav_whats_hot) {
Bundle args = new Bundle();
args.putString(GalleryListScene.KEY_ACTION, GalleryListScene.ACTION_WHATS_HOT);
@@ -0,0 +1,109 @@
/*
* Copyright 2019 Hippo Seven
*
* 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.
*/
package com.hippo.ehviewer.ui;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.widget.DialogWebChromeClient;
import com.hippo.widget.ProgressView;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
public class MyTagsActivity extends ToolbarActivity {
private WebView webView;
private ProgressView progress;
private String url;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// http://stackoverflow.com/questions/32284642/how-to-handle-an-uncatched-exception
CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.flush();
cookieManager.removeAllCookies(null);
cookieManager.removeSessionCookies(null);
} else {
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
cookieSyncManager.startSync();
cookieManager.removeAllCookie();
cookieManager.removeSessionCookie();
cookieSyncManager.stopSync();
}
// Copy cookies from okhttp cookie store to CookieManager
url = EhUrl.getMyTagsUrl();
EhCookieStore store = EhApplication.getEhCookieStore(this);
for (Cookie cookie : store.getCookies(HttpUrl.parse(url))) {
cookieManager.setCookie(url, cookie.toString());
}
setContentView(R.layout.activity_my_tags);
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyTagsWebViewClient());
webView.setWebChromeClient(new DialogWebChromeClient(this));
webView.loadUrl(url);
progress = findViewById(R.id.progress);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class MyTagsWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Never load other urls
return !url.equals(MyTagsActivity.this.url);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
}
}
}
@@ -19,13 +19,12 @@ package com.hippo.ehviewer.ui;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.widget.lockpattern.LockPatternUtils;
@@ -20,10 +20,10 @@ import android.app.Fragment;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.StringRes;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import androidx.annotation.StringRes;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.ui.fragment.AboutFragment;
@@ -17,13 +17,12 @@
package com.hippo.ehviewer.ui;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
@@ -21,30 +21,23 @@ package com.hippo.ehviewer.ui;
*/
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.google.android.material.snackbar.Snackbar;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.widget.DialogWebChromeClient;
import com.hippo.widget.ProgressView;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
@@ -87,7 +80,7 @@ public class UConfigActivity extends ToolbarActivity {
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new UConfigWebViewClient());
webView.setWebChromeClient(new UConfigWebChromeClient());
webView.setWebChromeClient(new DialogWebChromeClient(this));
webView.loadUrl(url);
progress = (ProgressView) findViewById(R.id.progress);
@@ -183,69 +176,4 @@ public class UConfigActivity extends ToolbarActivity {
loaded = true;
}
}
private class UConfigWebChromeClient extends WebChromeClient {
private Context context = UConfigActivity.this;
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
final JsPromptResult result) {
View promptView = UConfigActivity.this.getLayoutInflater()
.inflate(R.layout.dialog_js_prompt, null, false);
TextView messageView = (TextView) promptView.findViewById(R.id.message);
messageView.setText(message);
final EditText valueView = (EditText) promptView.findViewById(R.id.value);
valueView.setText(defaultValue);
new AlertDialog.Builder(context)
.setView(promptView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm(valueView.getText().toString());
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
result.cancel();
}
})
.show();
return true;
}
private void showMessageDialog(String message, final JsResult result) {
new AlertDialog.Builder(context)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
result.cancel();
}
})
.show();
}
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
showMessageDialog(message, result);
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
showMessageDialog(message, result);
return true;
}
}
}
@@ -24,10 +24,10 @@ import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.v7.app.AlertDialog;
import android.util.Base64;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.ui.CommonOperations;
@@ -17,7 +17,6 @@
package com.hippo.ehviewer.ui.fragment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
@@ -25,14 +24,13 @@ import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.AppConfig;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.EhDB;
import com.hippo.ehviewer.R;
import com.hippo.util.LogCat;
import com.hippo.util.ReadableTime;
import java.io.File;
import java.util.Arrays;
@@ -24,9 +24,9 @@ import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.ui.CommonOperations;
@@ -24,6 +24,7 @@ import android.preference.PreferenceFragment;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
import com.hippo.ehviewer.client.EhTagDatabase;
public class EhFragment extends PreferenceFragment
implements Preference.OnPreferenceChangeListener {
@@ -39,6 +40,8 @@ public class EhFragment extends PreferenceFragment
Preference listMode = findPreference(Settings.KEY_LIST_MODE);
Preference detailSize = findPreference(Settings.KEY_DETAIL_SIZE);
Preference thumbSize = findPreference(Settings.KEY_THUMB_SIZE);
Preference showTagTranslations = findPreference(Settings.KEY_SHOW_TAG_TRANSLATIONS);
Preference tagTranslationsSource = findPreference("tag_translations_source");
theme.setOnPreferenceChangeListener(this);
applyNavBarThemeColor.setOnPreferenceChangeListener(this);
@@ -46,10 +49,16 @@ public class EhFragment extends PreferenceFragment
listMode.setOnPreferenceChangeListener(this);
detailSize.setOnPreferenceChangeListener(this);
thumbSize.setOnPreferenceChangeListener(this);
showTagTranslations.setOnPreferenceChangeListener(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
getPreferenceScreen().removePreference(applyNavBarThemeColor);
}
if (!EhTagDatabase.isPossible(getActivity())) {
getPreferenceScreen().removePreference(showTagTranslations);
getPreferenceScreen().removePreference(tagTranslationsSource);
}
}
@Override
@@ -71,6 +80,10 @@ public class EhFragment extends PreferenceFragment
getActivity().setResult(Activity.RESULT_OK);
} else if (Settings.KEY_THUMB_SIZE.equals(key)) {
getActivity().setResult(Activity.RESULT_OK);
} else if (Settings.KEY_SHOW_TAG_TRANSLATIONS.equals(key)) {
if (Boolean.TRUE.equals(newValue)) {
EhTagDatabase.update(getActivity());
}
}
return true;
}
@@ -18,12 +18,11 @@ package com.hippo.ehviewer.ui.scene;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.hippo.ehviewer.Analytics;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.Settings;
@@ -20,19 +20,19 @@ import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.util.SparseArray;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.annotation.StyleRes;
import androidx.fragment.app.FragmentActivity;
import com.hippo.drawerlayout.DrawerLayout;
import com.hippo.ehviewer.Analytics;
import com.hippo.ehviewer.ui.MainActivity;
import com.hippo.scene.SceneFragment;
@@ -111,6 +111,22 @@ public abstract class BaseScene extends SceneFragment {
}
}
public void setDrawerGestureBlocker(DrawerLayout.GestureBlocker gestureBlocker) {
FragmentActivity activity = getActivity();
if (activity instanceof MainActivity) {
((MainActivity) activity).setDrawerGestureBlocker(gestureBlocker);
}
}
public boolean isDrawersVisible() {
FragmentActivity activity = getActivity();
if (activity instanceof MainActivity) {
return ((MainActivity) activity).isDrawersVisible();
} else {
return false;
}
}
/**
* @param resId 0 for clear
*/
@@ -20,9 +20,6 @@ import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
@@ -30,6 +27,9 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.google.android.material.textfield.TextInputLayout;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhCookieStore;
@@ -21,10 +21,6 @@ import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
@@ -32,12 +28,15 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.h6ah4i.android.widget.advrecyclerview.animator.GeneralItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.animator.SwipeDismissItemAnimator;
import com.h6ah4i.android.widget.advrecyclerview.draggable.DraggableItemAdapter;
import com.h6ah4i.android.widget.advrecyclerview.draggable.ItemDraggableRange;
import com.h6ah4i.android.widget.advrecyclerview.draggable.RecyclerViewDragDropManager;
import com.h6ah4i.android.widget.advrecyclerview.touchguard.RecyclerViewTouchActionGuardManager;
import com.h6ah4i.android.widget.advrecyclerview.utils.AbstractDraggableItemViewHolder;
import com.hippo.app.EditTextDialogBuilder;
import com.hippo.easyrecyclerview.EasyRecyclerView;
@@ -98,25 +97,21 @@ public class DownloadLabelsScene extends ToolbarScene {
tip.setCompoundDrawables(null, drawable, null, null);
tip.setText(R.string.no_download_label);
// touch guard manager (this class is required to suppress scrolling while swipe-dismiss animation is running)
RecyclerViewTouchActionGuardManager guardManager = new RecyclerViewTouchActionGuardManager();
guardManager.setInterceptVerticalScrollingWhileAnimationRunning(true);
guardManager.setEnabled(true);
// drag & drop manager
RecyclerViewDragDropManager dragDropManager = new RecyclerViewDragDropManager();
dragDropManager.setDraggingItemShadowDrawable(
(NinePatchDrawable) context.getResources().getDrawable(R.drawable.shadow_8dp));
RecyclerView.Adapter adapter = new LabelAdapter();
adapter.setHasStableIds(true);
adapter = dragDropManager.createWrappedAdapter(adapter); // wrap for dragging
mAdapter = adapter;
final GeneralItemAnimator animator = new SwipeDismissItemAnimator();
animator.setSupportsChangeAnimations(false);
mRecyclerView.hasFixedSize();
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
mRecyclerView.setAdapter(adapter);
mRecyclerView.setItemAnimator(animator);
guardManager.attachRecyclerView(mRecyclerView);
dragDropManager.attachRecyclerView(mRecyclerView);
updateView();
@@ -382,9 +377,6 @@ public class DownloadLabelsScene extends ToolbarScene {
}
EhApplication.getDownloadManager(context).moveLabel(fromPosition, toPosition);
if (mAdapter != null && mList != null) {
notifyItemMoved(fromPosition, toPosition);
}
}
@Override
Loaded 100 of 277 files, more files were not shown because too many files have changed in this diff. Show more