Compare commits

...
902 Commits
Author SHA1 Message Date
seven332 ba6d41b91f DEPRECATED 2019-08-09 12:50:16 +08:00
seven332 6a9e0198a2 Add cookie to torrent request 2019-08-07 11:05:38 +08:00
seven332 92f716170c Fix plain txt checking 2019-08-07 09:55:21 +08:00
seven332 d72f686d5a Fix data exporting 2019-08-01 17:02:36 +08:00
seven332 28eade9451 Fix check plain txt 2019-07-31 20:06:02 +08:00
seven332 7b95bc804a Check plain text after downloading 2019-07-31 19:41:51 +08:00
seven332 47c9d48787 Close #659, fix parsing gallery parent 2019-07-29 14:04:27 +08:00
seven332 8a7adbe838 1.7.3 2019-07-27 01:35:04 +08:00
seven332 0248fd4e02 Add kokomade tip 2019-07-26 21:22:26 +08:00
seven332 1cd5f7bbf7 Update libraries 2019-07-13 13:16:27 +08:00
seven332 db893b899d Add preset download dir 2019-07-13 12:59:51 +08:00
seven332 d86dd3bc06 1.7.2 2019-07-01 10:28:12 +08:00
seven332 49f420c1eb Remove useless import 2019-07-01 10:23:41 +08:00
seven332 c9103caad8 Add a tip about signing in 2019-06-21 15:08:04 +08:00
seven332 ee0ffc48d2 Remove recaptcha 2019-06-21 13:41:37 +08:00
seven332 ed7eba7ef4 Update issue templates 2019-06-20 20:30:39 +08:00
seven332 b6a16d1d58 Filter uploader for thumbnail mode 2019-06-20 19:50:02 +08:00
seven332 04521dfeb6 Remove gallery if it's downloaded 2019-06-20 19:32:08 +08:00
seven332 d00f6e6cc6 Show a confirm dialog before deleting galleries 2019-06-20 18:48:16 +08:00
seven332 7a47b2504d Show icon in selection dialogs 2019-06-20 18:21:52 +08:00
seven332 2da10a5855 Show delete downloads option if the gallery is downloaded 2019-06-20 16:37:32 +08:00
seven332 323b36c58a Remove old github issue template 2019-06-20 16:18:46 +08:00
seven332 9834d45ca9 Close #627, add quotation marks to titles for similar galleries 2019-06-20 16:17:38 +08:00
seven332 c058bb01f0 Update issue templates 2019-06-20 15:37:44 +08:00
seven332 f578c6cb8b Merge pull request #624 from dntil/master
Add auto screen rotation support.
2019-06-17 10:53:50 +08:00
liqichang 2c43589c1c Add auto screen rotation support. 2019-06-16 10:04:41 +08:00
seven332 6e73f03c19 Apply theme color to navigation bar in default 2019-06-16 00:39:58 +08:00
seven332 b7e2c5bce1 Use org.apache.http.legacy
Avoid crash in com.tencent.open.utils.HttpUtils.getHttpClient
2019-06-16 00:30:38 +08:00
seven332 9707ac470a Fix GalleryHeader 2019-06-15 12:02:53 +08:00
seven332 06fd28290c Fix GalleryHeader 2019-06-14 20:33:41 +08:00
seven332 21ef5897ef Add GalleryHeader avoid notch 2019-06-14 16:06:04 +08:00
seven332 bdd45b5f10 Readable time is more readable 2019-06-10 20:26:30 +08:00
seven332 e68d4ad2c4 Show last edited time of comments 2019-06-10 19:41:24 +08:00
seven332 2e56ba4ed0 Convert gallery title to lowercase before checking filter 2019-06-10 14:27:45 +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 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 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
seven332 116f30e496 1.3.4 2019-01-04 18:57:16 +08:00
seven332 e8d05c273f Update crashlytics sdk 2019-01-04 18:47:05 +08:00
seven332 29e3a50cd3 Update URL_PREFIX_THUMB_E 2019-01-04 13:41:49 +08:00
seven332 1409571ad8 Add ehgt.org and ul.ehgt.org to builtin hosts 2019-01-04 13:41:27 +08:00
seven332 8a7e72c412 Add repo.e-hentai.org to builtin hosts 2019-01-04 13:11:42 +08:00
seven332 948cb9ef9c Update GLView 2019-01-03 19:47:03 +08:00
seven332 926391a0fe Avoid NullPointerException in PrettyPreferenceActivity 2019-01-03 18:42:15 +08:00
seven332 24195430ab Use a7zip to extract archives 2019-01-03 18:03:15 +08:00
seven332 c9afa597d5 Avoid NullPointerException in StageActivity.onCreate() 2019-01-02 20:51:48 +08:00
seven332 adf38af673 Check updateCursorPositionMz method instead of device manufacturer 2019-01-02 18:40:14 +08:00
seven332 17f2bb670e Ignore Throwable in TextInputEditText.onDraw()
Ignore crash in updateCursorPositionMz.
2019-01-02 17:05:43 +08:00
seven332 2293654da8 Call notifyDataSetChanged() in ContentLayout restoring state 2019-01-02 16:37:20 +08:00
seven332 36067c9fac Ignore Throwable in ActivityCompat.requestPermissions() 2019-01-02 16:02:20 +08:00
seven332 8d20621ad4 Avoid crash in bindService() 2019-01-02 15:44:27 +08:00
seven332 a1d1db14c6 Override startService() instead of using SilentContextWrapper 2019-01-02 15:37:56 +08:00
seven332 44cf2b67d0 Set hint to TextInputLayout instead of TextInputEditText
It may avoid a bug of AssistStructure.
https://issuetracker.google.com/issues/62834931
2019-01-02 15:25:49 +08:00
seven332 74c0e478ef Avoid NullPointerException in MainActivity.handleIntent() 2019-01-02 14:53:41 +08:00
seven332 7496534b30 Exclude 64bit .so library
It may fix system .so missing, like "XXX.so is 32-bit instead of 64-bit"
2019-01-02 10:56:00 +08:00
seven332 415ffbc21d Avoid NullPointerException when restore items 2019-01-01 15:51:05 +08:00
seven332 ed4267cb36 Delay SystemUiHelper synchronizing in onWindowFocusChanged()
It fixes invalid SystemUiHelper synchronizing
on XiaoMi MIX2 MIUI 10 Android 8.0
2018-12-27 16:29:11 +08:00
seven332 2de859398b Fix big number causing NumberFormatException in NaturalComparator 2018-12-26 11:08:08 +08:00
seven332 62348433df Insert SilentContextWrapper to avoid crash in startService() 2018-12-25 22:36:10 +08:00
seven332 b64b14c69a Update Image
libjpeg-turbo neon runtime check
2018-12-25 10:52:29 +08:00
seven332 28e8e91303 Do io initialization tasks in new thread 2018-12-23 12:48:06 +08:00
seven332 44026f0ccc Avoid mysterious crash 2018-12-23 12:28:48 +08:00
seven332 95f2d46420 Avoid non-UI thread view touching on some devices 2018-12-23 12:20:10 +08:00
seven332 8f76f50526 Disable left drawer in GalleryDetailScene 2018-12-22 13:52:41 +08:00
seven332 ecd215d632 Avoid RecyclerView inconsistency in HistoryScene 2018-12-22 12:18:02 +08:00
seven332 b138de9563 Update GLView-Image 2018-12-22 00:29:15 +08:00
seven332 9bd344cc58 Avoid NullPointerException in deleteFileAsync() 2018-12-21 21:21:48 +08:00
seven332 ababfd57a6 Update GLView 2018-12-21 21:20:23 +08:00
seven332 45c760a507 Check mGalleryView null in GalleryMenuHelper 2018-12-21 19:51:44 +08:00
seven332 e721a6da1f 1.3.3 2018-12-21 19:35:40 +08:00
seven332 9eeba868d5 Update GLView-Image 2018-12-21 19:32:47 +08:00
seven332 8f3247bac4 Get update information from GitHub 2018-12-21 19:31:57 +08:00
seven332 e5a375c3fe Catch all throwable from startActivityForResult() 2018-12-21 18:53:50 +08:00
seven332 8d75752835 Catch all throwable while calling DownloadManager 2018-12-21 18:26:21 +08:00
seven332 8af786e687 Catch all throwable from startActivity() 2018-12-21 18:04:23 +08:00
seven332 4b1c516b3e Refresh if can't restore ContentLayout data 2018-12-21 17:01:37 +08:00
seven332 f32b79ba72 Save global stuff next id 2018-12-21 16:55:14 +08:00
seven332 92b5f2d766 Use notifyDataSetChanged() instead of notifyItemRemoved() to avoid crash 2018-12-21 16:22:01 +08:00
seven332 a5767e0fe6 Update UniFile 2018-12-21 15:04:03 +08:00
seven332 2fc48bb726 Update Image 2018-12-21 11:09:58 +08:00
seven332 4a5a426fd3 1.3.2 2018-12-20 20:11:48 +08:00
seven332 06adf8594c Fix HistoryScene crash
https://github.com/h6ah4i/android-advancedrecyclerview/issues/315
2018-12-20 19:39:48 +08:00
seven332 1ac43e6293 1.3.1 2018-12-20 18:21:28 +08:00
seven332 ceeb84812b Only ignore a special version update 2018-12-20 18:16:37 +08:00
seven332 bfd85e9bc7 Catch Throwable instead of Exception 2018-12-20 16:02:56 +08:00
seven332 8c3796605e Add scene_view action 2018-12-20 15:47:12 +08:00
seven332 3214bae157 Fix NullPointerException in ClearTask.clearFile() 2018-12-20 11:01:03 +08:00
seven332 a5b178df49 Returns null if IndexOutOfBoundsException in ContentHelper 2018-12-20 10:58:48 +08:00
seven332 c2a93f2ce4 Avoid NullPointerException in SpiderWorker.downloadImage() 2018-12-20 10:36:52 +08:00
seven332 257758b27d Avoid FingerprintManager.hasEnrolledFingerprints() crash on samsung devices 2018-12-20 10:18:32 +08:00
seven332 2681e4a6e6 Check FingerprintManager null 2018-12-19 22:17:51 +08:00
seven332 722653ac46 Update advrecyclerview 2018-12-19 20:02:27 +08:00
seven332 cb706941c5 Avoid TextInputEditText crash on some Meizu devices 2018-12-19 19:39:58 +08:00
seven332 195e9a5655 Revert "Set hint to TextInputEditText instead of TextInputLayout"
This reverts commit 405655d
2018-12-19 19:37:36 +08:00
seven332 ed2043ab7a Update Image 2018-12-19 19:16:09 +08:00
seven332 405655d0e2 Set hint to TextInputEditText instead of TextInputLayout 2018-12-19 16:03:02 +08:00
seven332 0cead11180 Update UniFile 2018-12-19 15:49:19 +08:00
seven332 141ab73089 1.3.0 2018-12-19 14:21:59 +08:00
seven332 7c349153de Fix fingerprint icon 2018-12-19 13:28:01 +08:00
seven332 168b701cca Remove G+ from readme 2018-12-19 12:49:04 +08:00
seven332 0b67e685d2 Print an error 2018-12-19 11:06:31 +08:00
seven332 741bb10a1c Allow http protocol 2018-12-19 11:06:01 +08:00
seven332 829591229d Update okhttp 2018-12-19 11:05:02 +08:00
seven332 cbed5ee8cb Add the declaration 2018-12-18 22:27:04 +08:00
seven332 a2db9038e3 Use sad pandroid icon instead of weird face icon 2018-12-18 17:44:16 +08:00
seven332 14328eaf83 Move webp images to v15 folder 2018-12-18 16:58:54 +08:00
seven332 a11fb869e2 Don't private classes or methods of support libraries 2018-12-18 16:50:15 +08:00
seven332 1285abdf71 Fix string resources 2018-12-18 15:33:53 +08:00
seven332 f0fa226b16 Use custom AssertUtils instead of Assert 2018-12-18 15:22:32 +08:00
seven332 88aebbd075 Add USE_BIOMETRIC and FOREGROUND_SERVICE permissions 2018-12-18 15:20:13 +08:00
seven332 2c08a7b56f Target SDK version 28 2018-12-18 15:19:22 +08:00
seven332 561e396c97 Use Firebase Crashlytics 2018-12-18 14:43:38 +08:00
seven332 f8676b71dc "Google Analytics" to "Google Analytics for Firebase" 2018-12-18 13:17:32 +08:00
seven332 259550e5cc Close #490, keep downloading after removing current download item 2018-12-17 17:02:19 +08:00
seven332 478e53ab96 Add download label delete button 2018-12-17 14:00:09 +08:00
seven332 286b39e679 Add quick search delete button 2018-12-17 13:44:32 +08:00
seven332 af771c7086 Remove specify gallery search 2018-12-16 02:08:56 +08:00
seven332 24d386da44 Don't scroll to top after delete a suggestion 2018-12-15 04:11:47 +08:00
seven332 419405f4e2 Apply theme color to navigation bar 2018-12-14 20:20:22 +08:00
seven332 e8de8ac5c8 Show clipboard url tip in Snackbar 2018-12-14 19:41:01 +08:00
seven332 934ec87390 Add gallery suggestion to search bar 2018-12-14 18:59:22 +08:00
seven332 46bd8e4297 Scroll suggestion list to top every time 2018-12-14 15:59:52 +08:00
seven332 70ceb83205 Increase suggestion count 2018-12-14 15:49:11 +08:00
seven332 0553fda3fa Long click category to set other categories to the opposite 2018-12-14 13:40:47 +08:00
seven332 b5f36dafdc Exclude solid archives 2018-12-13 23:29:48 +08:00
seven332 77fd0eb73e Update libraries 2018-12-13 21:50:35 +08:00
seven332 ff6b0bf01d Remove ZipGalleryProvider 2018-12-13 21:42:35 +08:00
seven332 6734ace077 Add ArchiveGalleryProvider 2018-12-13 15:15:39 +08:00
seven332 c013c82f90 Use NaturalComparator in DirGalleryProvider 2018-12-12 21:43:45 +08:00
seven332 618ca14eca Add NaturalComparator and PathNaturalComparator 2018-12-12 21:30:42 +08:00
seven332 700ebdfee3 Remove useless code 2018-12-11 09:55:31 +08:00
seven332 9899552e4b Close #488, detect gallery page url in clipboard 2018-12-04 21:45:22 +08:00
seven332 7104fddded GalleryPageUrlParser supports non-strict url 2018-12-04 21:27:37 +08:00
seven332 54f1c4806f GalleryDetailUrlParser supports non-strict url 2018-12-04 20:54:22 +08:00
UShimamura 9c66298cb8 Some little fixes 2018-11-29 21:57:35 +08:00
UShimamura bb266d46d3 Improved sentence to avoid ambiguity 2018-11-29 21:57:35 +08:00
UShimamura 8cd7d01e10 Add new translated strings 2018-11-29 21:57:35 +08:00
UShimamura 9692224dec Add new translated strings 2018-11-29 21:57:35 +08:00
UShimamura 41b4f00b91 Add translated strings 2018-11-29 21:57:35 +08:00
UShimamura 611a4c8853 Improve English strings. 2018-11-29 21:57:35 +08:00
UShimamura c8f1080b9e Update strings.xml
Error corrections
2018-11-24 11:53:04 +08:00
UShimamura 92ecf84c5e Update strings.xml
Polishing
2018-11-24 11:53:04 +08:00
UShimamura d9c0c80172 Update strings.xml
Grammar polishing
2018-11-24 11:53:04 +08:00
GUIHU 74a7b16252 Deleted wordy translations 2018-11-24 11:52:28 +08:00
GUIHU 5ccbeda6d5 Fixed incorrect spelled translations in values-zh-rTW 2018-11-24 11:52:28 +08:00
GUIHU 75a2be5d38 Translations polishing in values-zh-rTW 2018-11-24 11:52:28 +08:00
akazaa96 c5d5778961 Denmark strings.xml are missing a string argument 2018-11-19 21:35:04 +08:00
hbina4326 eb16df63e1 fixed french typo causing build failure 2018-11-16 14:08:38 +08:00
hzy980512 1bb2f6eb5f Update strings.xml 2018-11-05 14:54:24 +08:00
hzy980512 4a905a5226 Update strings.xml 2018-11-05 14:54:24 +08:00
hzy980512 fe60b26eec Update strings.xml 2018-11-05 14:54:24 +08:00
hzy980512 3b1028b9cc Add new translations. 2018-11-05 14:54:24 +08:00
hzy980512 36b7a6211e Update strings.xml 2018-11-05 14:54:24 +08:00
hzy980512 8cd89f8a06 Add new translations 2018-11-05 14:54:24 +08:00
hzy980512 b599f6e71c Update strings.xml 2018-11-05 14:54:24 +08:00
hzy980512 2e38237a99 Add new translations 2018-11-05 14:54:24 +08:00
seven332 d23c145790 Add shadow to adaptive icon 2018-11-03 20:26:57 +08:00
seven332 c3e0bbaa0a Exclude all google-services.json 2018-11-03 20:05:34 +08:00
seven332 4582556f65 Moved from Google Analytics to Firebase Analytics 2018-11-02 20:54:55 +08:00
seven332 e07316f25a Support mpv links 2018-10-30 18:34:26 +08:00
scese250 7379bdaa67 Translated new features to Spanish
And by the way, also I updated text.

btw thanks for add dark theme. 👍
2018-10-30 12:26:12 +08:00
seven332 c4519c5914 Fix missing gallery uploader 2018-10-29 20:30:06 +08:00
seven332 358d9861f5 Add changing theme shortcut to left drawer 2018-10-29 15:24:11 +08:00
seven332 bdf2df0ed1 Get simple language from tags 2018-10-29 13:53:11 +08:00
seven332 291a6515c1 Fix missing simple language 2018-10-29 11:38:20 +08:00
seven332 2667bacd9d 1.2.1 2018-10-27 13:55:56 +08:00
seven332 7967f289b7 Fix preference header background 2018-10-27 12:09:48 +08:00
seven332 31e1cb7e6d Fix gallery comments EditText bg color 2018-10-27 10:42:44 +08:00
seven332 a472d0509a 1.2.0 2018-10-25 20:08:37 +08:00
seven332 3f71a97cbd Change colorEdgeEffect 2018-10-25 19:26:06 +08:00
seven332 ed8c818d4f Adjust dark theme color 2018-10-25 18:40:27 +08:00
seven332 1db14cd998 Parse gallery list in thumbnail view 2018-10-25 16:02:04 +08:00
seven332 d06dd87ff4 Adjust text color 2018-10-25 14:32:26 +08:00
seven332 a31a64efd6 Revert textColor of ButtonInCard 2018-10-25 14:14:18 +08:00
seven332 cfa87a5a02 Adjust text color 2018-10-25 14:00:03 +08:00
seven332 2833691c34 Adjust text color 2018-10-25 13:37:25 +08:00
seven332 22d6ed8c39 Revert colorPrimary and colorAccent 2018-10-24 19:05:29 +08:00
seven332 110bae7cb7 Adjust progress view color 2018-10-22 13:45:15 +08:00
seven332 5bd7d6fae3 Adjust gallery detail header button background color 2018-10-22 13:35:59 +08:00
seven332 afa45fd8d9 Change black colorPrimary and colorAccent to grey_700 2018-10-22 13:08:16 +08:00
seven332 2c544607ec Add tagGroupBackgroundColor and tagBackgroundColor attribute 2018-10-22 13:05:38 +08:00
seven332 730b52d6cd Fix RatingBar color 2018-10-20 01:45:54 +08:00
seven332 0704579d26 Adjust card elevation 2018-10-20 01:41:20 +08:00
seven332 cb92fbad3d Don't finish the activity in second level of SettingsActivity 2018-10-19 23:07:45 +08:00
seven332 c7c6f8f706 Disable right swipe of HistoryScene 2018-10-19 23:04:06 +08:00
seven332 fdd81e21b1 Adjust card color 2018-10-19 22:54:02 +08:00
seven332 1093da6565 Update strings.xml 2018-10-19 22:13:12 +08:00
seven332 c625315a76 Apply theme to GalleryActivity 2018-10-19 22:09:04 +08:00
seven332 1deb4c2d6c Add dark widget color 2018-10-19 21:55:48 +08:00
seven332 9201b9baed Apply theme to dialog background 2018-10-19 21:52:43 +08:00
seven332 557bd9f54b Apply theme to play icon 2018-10-19 21:47:28 +08:00
seven332 0353dbdb27 Add activated color to reactive items 2018-10-19 21:45:13 +08:00
seven332 8b07cf62a9 Yellow RatingBar 2018-10-19 21:12:32 +08:00
seven332 111025cb98 Change colorControlActivated 2018-10-19 20:39:57 +08:00
seven332 b3d9c4c2b9 Apply theme to Security 2018-10-19 20:04:32 +08:00
seven332 f2695b6a2c Apply theme to some drawables 2018-10-19 19:39:52 +08:00
seven332 f6ec40e8ed Revert colorPrimary and colorAccent 2018-10-19 19:19:39 +08:00
seven332 9bc6920448 Add galleryDetailDivider attribute 2018-10-19 19:03:31 +08:00
seven332 abb8483723 Apply theme to Guides 2018-10-19 18:47:53 +08:00
seven332 81eadbb794 Apply theme to image_failed 2018-10-19 18:11:33 +08:00
seven332 22cc32778d Use system image in Html 2018-10-19 16:56:59 +08:00
seven332 c9d432b7c8 Change colorPrimary and colorAccent of dark theme and black theme 2018-10-19 16:48:53 +08:00
seven332 168a1dcfb2 Apply theme to text 2018-10-19 16:39:42 +08:00
seven332 b6718078f2 Add widgetColorThemePrimary and widgetColorThemeAccent attributes 2018-10-19 15:59:59 +08:00
seven332 960a7751ad Apply theme to ShadowLinearLayout 2018-10-19 15:34:22 +08:00
seven332 e5335de859 Apply theme to content color 2018-10-19 15:26:46 +08:00
seven332 1eb960eaf9 Clean theme 2018-10-19 14:57:09 +08:00
seven332 6bc9f0da64 Apply theme to big icons 2018-10-19 14:08:48 +08:00
seven332 f4d986a5bd Rename attributes
colorDivider -> dividerColor
colorToolbar -> toolbarColor
colorDrawablePrimary -> textColorThemeAccent
colorDrawableThemePrimary -> drawableColorPrimary
colorTextThemeAccent -> drawableColorThemePrimary
2018-10-19 13:56:33 +08:00
seven332 9aa22aab34 Apply theme to accent text 2018-10-18 23:08:31 +08:00
seven332 afa839ed0b Rename color drawable attribute
colorDrawableOpposite -> colorDrawablePrimary
colorDrawablePrimary -> colorDrawableThemePrimary
2018-10-18 23:01:57 +08:00
seven332 f2725331fe Fix duplicate clipboard text test 2018-10-18 22:20:55 +08:00
seven332 590963024a Apply theme to Ripple 2018-10-18 22:10:50 +08:00
seven332 1f55977182 Apply theme to the color of comment vote 2018-10-18 21:51:18 +08:00
seven332 4bed3d5b8e Rename colorXXXDrawable to colorDrawableXXX 2018-10-18 21:45:42 +08:00
seven332 7eab4e00e1 Replace @color/primary_text_light with ?android:attr/textColorPrimary 2018-10-18 21:39:28 +08:00
seven332 776813df17 Add colorPrimaryDrawable attribute 2018-10-18 21:36:22 +08:00
seven332 12beeedf29 Rename colorPrimaryDrawable to colorOppositeDrawable 2018-10-18 20:06:11 +08:00
seven332 d0e7f25fd9 Apply theme to AddDeleteDrawable and DrawerArrowDrawable 2018-10-18 19:58:50 +08:00
seven332 ab2a066992 Optimize themes.xml 2018-10-18 18:42:19 +08:00
seven332 596f95e463 Fix toolbarPopupTheme 2018-10-18 16:43:46 +08:00
seven332 79d07f98a8 Change Toolbar popup them 2018-10-18 15:53:42 +08:00
seven332 22ec2e8926 Change Toolbar background color 2018-10-18 15:33:53 +08:00
seven332 bc4d20d0a4 Fix SearchBar animations 2018-10-18 14:44:47 +08:00
seven332 84ed520c1c Change divider color 2018-10-18 14:37:59 +08:00
seven332 34eb6a423a Use CardView instead of card 9 png drawable 2018-10-18 13:28:07 +08:00
seven332 7dc1491c26 Use ?android:attr/windowBackground to draw background 2018-10-18 13:02:25 +08:00
seven332 6ecce9ddc5 Add dark theme and black theme 2018-10-18 12:56:56 +08:00
seven332 029373a8d2 Recreate all activities if theme changed 2018-10-18 12:44:43 +08:00
seven332 e8c06fd876 Add theme setting 2018-10-17 23:07:01 +08:00
seven332 8c9218e8af Use a non-reflect way to change how PreferenceActivity looks
Android P doesn't support invoking hidden API.
2018-10-15 22:31:53 +08:00
jerry855202 f922d41775 Fixed rCN text in rTW
"不允許螢幕抓取" was still rCN, fixed in this commit
2018-10-13 17:59:29 +08:00
seven332 e483105eb2 Android Studio 3.2.0 2018-10-10 18:26:20 +08:00
seven332 9aecb79b17 Calculate height of history item at runtime 2018-10-10 18:25:33 +08:00
seven332 bfc6bf07d9 Calculate height of download item at runtime 2018-10-10 15:51:39 +08:00
seven332 b671999e5a Calculate height of gallery list item at runtime 2018-10-10 13:13:20 +08:00
seven332 3ed2cb329c Remove the link of Google+ Community
Google+ is dying.
2018-10-09 15:20:05 +08:00
seven332 fe9970523f Avoid detecting current gallery 2018-09-23 16:00:30 +08:00
seven332 62944f7b71 Lint on release builds 2018-09-19 20:00:09 +08:00
seven332 a7e1101c87 Statement about about donation 2018-09-19 19:58:40 +08:00
seven332 b79d991b25 Set favoriteName null if isFavorited is false 2018-09-19 16:19:08 +08:00
seven332 10a15fc5cf fix: only update favoriteName after success 2018-09-19 15:50:37 +08:00
Tsukatsuki Kanade 428a5ab20e fix: change favoriteName b4 send request 2018-09-19 15:47:58 +08:00
Tsukatsuki Kanade b3d19d752b fix: update favoriteName after added favorite 2018-09-19 15:47:58 +08:00
Tsukatsuki Kanade 73b702aa56 feat: Add favorite gallery name to scene 2018-09-19 15:47:58 +08:00
hzy980512 3360035402 Fix choices of words 2018-09-18 10:19:26 +08:00
hzy980512 b97069a04e A little fix 2018-09-18 10:19:26 +08:00
hzy980512 9df8d050b2 Add some new translations 2018-09-18 10:19:26 +08:00
hzy980512 ba4ca96b77 Add some translations 2018-09-18 10:19:26 +08:00
hzy980512 fd93baf583 Add some new translations 2018-09-18 10:19:26 +08:00
hzy980512 0a9a1976cd Grammar fix 2018-09-18 10:19:26 +08:00
hzy980512 450e05c819 Make some sentences shorter 2018-09-18 10:19:26 +08:00
hzy980512 59d36d29da Fix some bugs, where quotes break the sentences 2018-09-18 10:19:26 +08:00
seven332 f0cd92f82e Check settings while try showing gallery page count 2018-09-17 11:34:32 +08:00
seven332 e847338ef4 Light background toolbar popup 2018-09-17 00:32:17 +08:00
seven332 23c34258ff Update strings.xml 2018-09-16 23:36:58 +08:00
seven332 d441960107 Update strings.xml 2018-09-16 23:35:53 +08:00
seven332 185ae6beb4 1.1.0 2018-09-16 22:18:06 +08:00
seven332 d84376e4dc Google style reorder icon 2018-09-16 22:12:26 +08:00
seven332 dcc6af3367 Update local favourites count 2018-09-14 19:48:48 +08:00
seven332 1cd8ef1b47 Back up gallery list moved from local favourites to cloud favourites 2018-09-14 19:35:02 +08:00
seven332 f8c5caf6bc Don't throw null exception 2018-09-14 19:15:39 +08:00
seven332 8e84b5b67b Update libraries 2018-09-14 13:33:32 +08:00
seven332 dc697af081 Show identity cookies 2018-09-14 13:32:03 +08:00
seven332 a69f36b652 Don't cache gif while reading
Update GLGallery
2018-09-02 14:53:33 +08:00
seven332 d5c788fe80 Add resetting reading progress 2018-09-02 01:25:43 +08:00
seven332 021fe45c8d Fix string format in zh-rTW translation 2018-09-01 20:56:43 +08:00
seven332 18881e549f Save gallery toke to saved filename 2018-08-15 21:54:35 +08:00
seven332 ed2f3510d8 Android Studio 3.1.4 2018-08-07 14:02:04 +08:00
seven332 5290340b97 Show gallery pages 2018-08-06 13:25:12 +08:00
hzy980512 9514d42032 Fix translations 2018-07-31 10:38:23 +08:00
hzy980512 2cc140eaf4 Translations fix 2018-07-31 10:38:23 +08:00
hzy980512 c4934fc89e Fix translations 2018-07-31 10:38:23 +08:00
seven332 7feb5552c1 Always print errors in EhEngine 2018-07-30 10:03:24 +08:00
seven332 fce659c41c Fix error_bad_status_code chinese string 2018-07-23 19:13:53 +08:00
seven332 2e899f5fa8 SSLException is network error 2018-07-20 14:03:43 +08:00
hzy980512 4580d781db Correct a typo 2018-07-18 12:14:16 +08:00
hzy980512 6fdab6f89c Fix a typo 2018-07-18 12:14:16 +08:00
hzy980512 145b6523e9 Fixed grammar 2018-07-18 12:14:16 +08:00
hzy980512 1d03d35685 Fix translation 2018-07-18 12:14:16 +08:00
hzy980512 71396bc632 Fix translation 2018-07-18 12:14:16 +08:00
hzy980512 511d70838a Fix more translations 2018-07-18 12:14:16 +08:00
hzy980512 1e31052767 Some fixes 2018-07-18 12:14:16 +08:00
hzy980512 e1c88c53f3 Some more corrections 2018-07-18 12:14:16 +08:00
hzy980512 de16081c79 Some corrections 2018-07-18 12:14:16 +08:00
hzy980512 e9d1ce1720 Some corrections 2018-07-18 12:14:16 +08:00
hzy980512 3bce3c41f2 Some corrections 2018-07-18 12:14:16 +08:00
hzy980512 c71729c560 Correcting sentences 2018-07-18 12:14:16 +08:00
seven332 3cbf5d0a8f Disable no media file checker at during startup 2018-07-16 13:56:07 +08:00
hzy980512 6f99f5a226 Fix translations 2018-07-12 16:48:34 +08:00
hzy980512 252dcb6175 Corrections 2018-07-12 16:48:34 +08:00
hzy980512 72971341b2 Corrections 2018-07-12 16:48:34 +08:00
hzy980512 32f4205240 Improved 2018-07-12 16:48:34 +08:00
hzy980512 36e66a8714 Grammar fix 2018-07-12 16:48:34 +08:00
hzy980512 7ee1777e7b More fixes of errors 2018-07-12 16:48:34 +08:00
hzy980512 d8dc9ad576 Fix of translation 2018-07-11 22:17:20 +08:00
hzy980512 8ae8842f81 A little fix of translation 2018-07-11 21:31:35 +08:00
hzy980512 ddb82292f9 Update strings.xml 2018-07-11 21:31:35 +08:00
hzy980512 83ade321bb A little fix 2018-07-11 21:31:35 +08:00
hzy980512 a4ea8a6bfc Add support for French and German translations 2018-07-11 21:31:35 +08:00
hzy980512 2d32852d18 Update Spanish translations (partly) 2018-07-11 21:31:35 +08:00
hzy980512 3ef3510ad3 Fix crash when there's an image in clipboard 2018-07-11 21:31:35 +08:00
hzy980512 82cb0eb7d6 Add strings for language switcher 2018-07-11 21:31:35 +08:00
hzy980512 2c428d3306 Add new languages to language switcher 2018-07-11 21:31:35 +08:00
hzy980512 5fa9e8677d Improve English translation 2018-07-11 21:31:35 +08:00
hzy980512 b57abfdc57 Add French and German translations 2018-07-11 21:31:35 +08:00
hzy980512 2f7906d3db Correct errors and update Japanese translation 2018-07-11 21:31:35 +08:00
seven332 d56f86b47e Show password toggle 2018-07-02 19:25:25 +08:00
seven332 e558be2b89 Disable clipboard check if the top scene is solid 2018-06-25 14:53:33 +08:00
seven332 66cab7b41e Close #417, click error text to refresh 2018-06-25 13:55:49 +08:00
seven332 4f431bb7ea Check ClipData null 2018-06-22 15:37:24 +08:00
seven332 d411623da6 Only save the hash code of the text in the clipboard 2018-06-21 13:42:53 +08:00
seven332 d121e839c9 Close #312, read gallery link from clipboard 2018-06-14 20:28:31 +08:00
seven332 c397bd0211 Close #276, save drawer view state 2018-06-13 15:18:48 +08:00
seven332 ec2782ddad Android Studio 3.1.3 2018-06-11 21:52:40 +08:00
scese250 6b6a60ae02 Updated spanish translation
Translated new options and updated some texts.

Thanks for keep working in this great app!!
2018-06-07 18:55:10 +08:00
seven332 f870674bd2 Use intent chooser when sharing 2018-06-05 21:03:59 +08:00
seven332 6af75a9758 1.0.30 2018-06-04 11:07:40 +08:00
seven332 e4fc925b04 Fix preview page estimation 2018-05-24 20:11:05 +08:00
seven332 2262779ba0 Close #396, fix preload pages calculation 2018-05-10 20:32:16 +08:00
lilymaniac b52cd2a619 Update Korean localization
Catch up to commit 8bad20e58c ("add option of disable auto update").
2018-05-02 22:03:06 +08:00
onlymash 8bad20e58c add option of disable auto update 2018-05-02 13:03:56 +08:00
seven332 30ca44b9c6 Android Studio 3.1.2 2018-04-28 22:47:30 +08:00
seven332 cf43ed965e Add Filter.hashCode() 2018-04-28 22:47:01 +08:00
onlymash dab29819bd make gradlew executable for linux 2018-04-28 22:29:50 +08:00
seven332 5fb090f241 No more mandatory check on igneous field 2018-04-20 09:15:59 +08:00
onlymash ff84c63445 update fav drawer 2018-04-10 22:13:37 +08:00
onlymash 140ace739e update support libs 2018-04-10 22:13:37 +08:00
onlymash 5f8c078367 rename recyclerview drawer layout 2018-04-10 22:13:37 +08:00
onlymash faddb37557 save favorites count 2018-04-10 22:13:37 +08:00
onlymash 5d8fe06d5c fix favories layout & count issue 2018-04-10 22:13:37 +08:00
seven332 2e34913c7d Android Studio 3.1.1 2018-04-10 22:10:10 +08:00
onlymash 6cc607469b update favorites list layout 2018-04-08 12:10:12 +08:00
onlymash 26eff55e6d update favorites right drawer layout 2018-04-08 12:10:12 +08:00
PYC 9a5743dd67 Correct the japanese sentence. 2018-04-02 12:02:32 +08:00
onlymash 0b547147b1 fix judgment issue 2018-04-02 11:56:56 +08:00
onlymash 6bd3bd5e80 fix judgment issue 2018-04-02 11:56:56 +08:00
onlymash af93a6730e update shortcut background 2018-03-29 19:30:58 +08:00
onlymash 27e4bd4e0b merge background color to color.xml 2018-03-29 19:30:58 +08:00
onlymash 459b27253a redraw shortcut icon 2018-03-29 19:30:58 +08:00
onlymash bb99570cd4 update shortcut foreground icon inset 2018-03-29 19:30:58 +08:00
onlymash 3f2b62c119 restore unifile 2018-03-29 19:30:58 +08:00
onlymash 91e9975a24 update shortcut 2018-03-29 19:30:58 +08:00
onlymash 00485efd0e update shortcut 2018-03-29 19:30:58 +08:00
onlymash c5d56243e0 update shortcut icon 2018-03-29 19:30:58 +08:00
onlymash b8c3229d9f add license to shortcut icon 2018-03-29 19:30:58 +08:00
onlymash 8cf935accc fix shortcuts 2018-03-29 19:30:58 +08:00
onlymash 2cf5589369 shortcuts: update icons 2018-03-29 19:30:58 +08:00
onlymash 89addaf211 update unifile 2018-03-29 19:30:58 +08:00
onlymash f5409c7b8a update shortcut 2018-03-29 19:30:58 +08:00
onlymash 733ddb5964 remove process 2018-03-29 19:30:58 +08:00
onlymash 537380eeb7 update shortcut categories 2018-03-29 19:30:58 +08:00
onlymash e44473f26b clean import 2018-03-29 19:30:58 +08:00
onlymash a503832016 update app shortcuts 2018-03-29 19:30:58 +08:00
onlymash 4935995342 update manifest 2018-03-29 19:30:58 +08:00
onlymash a367373c87 add shortcut icon for android 7.1 2018-03-29 19:30:58 +08:00
onlymash 62cd2e4809 add app shortcuts 2018-03-29 19:30:58 +08:00
seven332 7df7defa92 Save the images, which will be shared, to temp dir 2018-03-28 09:35:17 +08:00
seven332 56b42c67d5 Fix gallery favorite block 2018-03-27 18:06:05 +08:00
seven332 d1afcc2f54 Fix the parsing, language to Local 2018-03-27 17:09:09 +08:00
seven332 f6b05ed42b Fix strings 2018-03-27 16:51:01 +08:00
seven332 095334d338 Recreate all activities after changing app language 2018-03-27 14:01:05 +08:00
seven332 dac0ef178d Add RecordingApplication 2018-03-27 13:59:35 +08:00
seven332 c23a502e9e Add app language option 2018-03-27 13:40:58 +08:00
seven332 5ddd652076 Ignore past error while reading 2018-03-27 10:53:45 +08:00
seven332 3f9e3f620d Android Studio 3.1.0 2018-03-27 10:29:50 +08:00
seven332 1c62fe9615 1.0.29 2018-03-26 22:46:55 +08:00
seven332 8703102c97 Update UniFile 2018-03-26 22:45:45 +08:00
onlymash 28ab591769 update showPageDialog 2018-03-26 20:42:12 +08:00
onlymash 8cc2bfbced dynamically add dialog items 2018-03-26 20:42:12 +08:00
onlymash 7612dde6d4 clean string.xml 2018-03-26 20:42:12 +08:00
onlymash 5188fe7170 only show 'Save to...' at KiKat or higher 2018-03-26 20:42:12 +08:00
onlymash c31048e829 clean import 2018-03-26 20:42:12 +08:00
onlymash 44629bb405 support image custom save 2018-03-26 20:42:12 +08:00
seven332 3e387b1833 1.0.28 2018-03-26 18:24:03 +08:00
seven332 080693656a Update adaptive icon 2018-03-26 17:56:25 +08:00
seven332 bc5479fa96 Add built-in hosts 2018-03-26 12:02:44 +08:00
seven332 b95892d3b6 Use "Custom hosts.txt" to distinguish "built-in" and "custom" 2018-03-26 11:07:13 +08:00
seven332 e1eea40fd7 Use "hosts.txt" instead of "Hosts"
Users might be more familiar with the former
2018-03-26 10:16:51 +08:00
seven332 c00fb901a0 Close #363, select download pipe if download dir exists 2018-03-25 20:23:16 +08:00
seven332 029bca22ed Add hosts UI 2018-03-24 02:17:58 +08:00
seven332 facb931cb6 Use Java 8 language features 2018-03-24 01:16:32 +08:00
onlymash 2f319afd40 restore app_name 2018-03-23 21:24:08 +08:00
onlymash 95114502c9 add strings.xml to debug 2018-03-23 21:24:08 +08:00
onlymash 2eef9b8fb0 rename FILE_PROVIDER_AUTHORITY 2018-03-23 21:24:08 +08:00
onlymash 6180ea3302 remove productFlavors 2018-03-23 21:24:08 +08:00
onlymash bf3ebc5ff8 remove unused applicationId 2018-03-23 21:24:08 +08:00
onlymash 5f77728a7b use another package name for debug 2018-03-23 21:24:08 +08:00
seven332 e823834889 Fix UConfigActivity registered name 2018-03-23 12:48:06 +08:00
seven332 35c97a7772 Add Hosts 2018-03-23 12:10:03 +08:00
seven332 d59a520aa5 Fix test 2018-03-23 12:09:15 +08:00
seven332 6bcdbfeaa4 Use field mLocation instead of local variable location 2018-03-21 19:41:12 +08:00
bfkro dcb11102f6 use ViewUtils to calculate offset between SeekBar and SeekBarPanel 2018-03-21 19:25:12 +08:00
bfkro a0e957b1fd Fix a bug so when user clicks the SeekBarPanel, the x coordinate with the correct x-offset is sent to SeekBar. 2018-03-21 19:25:12 +08:00
onlymash c8c0a3aae0 update foreground 2018-03-20 23:10:52 +08:00
onlymash aed7acfdc8 update foreground 2018-03-20 23:10:52 +08:00
onlymash 6707f0ee35 update launcher backgound 2018-03-20 23:10:52 +08:00
onlymash 44694f351e add adaptive icons for android 8.0+ 2018-03-20 23:10:52 +08:00
onlymash 8e3585b32d use implementation for gradle 3.0+ 2018-03-20 15:18:47 +08:00
onlymash 25312953af add notification channel for Oreo 2018-03-19 22:44:23 +08:00
seven332 c8a32ba76e Update ISSUE_TEMPLATE.md
能说中文就别说英文了
2018-03-19 18:15:10 +08:00
lilymaniac a97a6682fb Add Korean localization 2018-03-19 09:28:03 +08:00
lilymaniac ed8151632e Add Korean to resConfigs entry 2018-03-19 09:28:03 +08:00
seven332 aca061ecf6 Ignore release dir 2018-03-08 20:42:32 +08:00
seven332 b2bef7a4b0 Update okhttp 2018-03-08 20:35:02 +08:00
seven332 db63a8f05b Print exception in ExceptionUtils.getReadableString()
I don't want to track all callings, just add it here
2018-03-08 19:33:44 +08:00
seven332 998f57f435 Fix gallery comment parsing 2018-03-05 10:09:47 +08:00
seven332 46c9197cce Update sdk version and libraries 2018-03-04 15:59:32 +08:00
seven332 3f3c0c6c6a Show sign in failure reason 2018-03-03 23:52:54 +08:00
seven332 ff34acfe59 Update values-zh-rTW/strings.xml 2018-03-02 09:03:42 +08:00
seven332 b969177244 Update values-zh-rHK/strings.xml 2018-02-28 17:03:00 +08:00
seven332 32efad2b33 1.0.27 2018-02-28 10:08:03 +08:00
trhjew bad4cdac1a Update strings.xml 2018-02-27 22:35:27 +08:00
seven332 5cebca42e9 Add Japanese support 2018-02-27 22:20:08 +08:00
trhjew 3ef2447eef Update strings.xml 2018-02-27 22:06:34 +08:00
trhjew a8faa2930a Update strings.xml 2018-02-27 22:06:34 +08:00
trhjew 02abba52a7 Create strings.xml 2018-02-27 22:06:34 +08:00
seven332 6da2bc352d Update gradle 2018-02-25 20:27:40 +08:00
seven332 cc39e0dda3 Show post gallery comment error 2018-02-25 20:26:34 +08:00
seven332 c81145d46e Close #341, update gallery comment post format 2018-02-24 19:03:09 +08:00
0w0@0w0.pw a56c79d4bb Remove some translations
Rename Privacy settings
2018-02-11 13:20:18 +08:00
0w0@0w0.pw fa3f409a70 Clean up the import 2018-02-11 13:20:18 +08:00
0w0@0w0.pw 1865924469 Clean Code 2018-02-11 13:20:18 +08:00
0w0@0w0.pw b3a23ad4e8 Add Privacy and Security Settings 2018-02-11 13:20:18 +08:00
seven332 7a02103e05 Close #328, fix Chinese language detection
Add 中国翻訳
2018-02-10 21:50:22 +08:00
seven332 95ed0eb7ea 1.0.26 2018-02-10 16:02:41 +08:00
seven332 9ec74934bc Always show the help route in error message 2018-02-10 15:56:21 +08:00
seven332 4f868a4556 Add uconfig saving tip 2018-02-10 14:51:18 +08:00
seven332 21bff4dff7 Merge branch 'master' of https://github.com/seven332/EhViewer 2018-02-10 14:03:03 +08:00
seven332 30819fc7c6 Add UConfigActivity 2018-02-10 14:02:20 +08:00
scese250 ce70859fb2 Fixed orthography and translation (Spanish)
Some words weren't translated and there were several orthographic errors.
2018-02-06 00:06:35 +08:00
seven332 197a34721b Closes #320, fix strings.xml 2018-01-29 20:04:40 +08:00
seven332 3a21724342 Add an option to disable page interval 2018-01-25 22:33:43 +08:00
seven332 ffceda72b1 Merge branch 'master' of https://github.com/seven332/EhViewer 2018-01-25 21:42:26 +08:00
seven332 bb655783b8 Update GLView-Image library to fix invalid gif autoplay 2018-01-25 21:38:06 +08:00
seven332 d5cd23c130 Update Image library to avoid gif super short delay 2018-01-25 18:42:29 +08:00
seven332 70bb0d06b2 Update ISSUE_TEMPLATE.md 2018-01-25 11:19:59 +08:00
GUIHU 18f1ec7403 Update strings.xml 2018-01-13 22:05:36 +08:00
gui 20c0030cdc polish 2018-01-13 22:05:36 +08:00
gui 7509bf9776 polish 2018-01-13 22:05:36 +08:00
gui fb7b9b28a7 針對台灣使用者慣用語(或已有既有用法)的文字字串進行調整
以迎合台灣使用者使用習慣
localization for values-zh-rTW  in order to fit Taiwanese user's habit
2018-01-13 22:05:36 +08:00
seven332 185ab00431 1.0.25 2017-12-28 22:00:51 +08:00
LackOfDream b48b38e8c4 remove redundant trailing whitespace of tags when parsing gallery detail 2017-12-24 18:12:44 +08:00
LackOfDream 34632342fc Notify change of single item instead of the whole data set, disable item animation 2017-12-19 15:46:42 +08:00
LackOfDream c7bf9509e3 Add enable/disable feature on Filter 2017-12-19 15:46:42 +08:00
seven332 877c354f84 Add the Telegram link 2017-11-14 21:42:58 +08:00
seven332 6c7b33e86f Add community links 2017-11-14 21:35:02 +08:00
seven332 2c3fa31e91 Add recaptcha 2017-09-06 16:49:48 +08:00
scese250 550d3735c7 Fixed typos, incorrect capital and added accents
Thanks for add spanish translation, I'll help for correct errors.
2017-07-24 12:48:05 +08:00
Jabasukuriputo Wang 71f654635c Add textbox for cookie:igneous.
Fix #208 #274
It seems that login via other ways is impossible to get correct igneous atm.
(DAMN, SAVE IT ELSEWHERE NOW)
2017-07-14 21:08:12 +08:00
seven332 e9c7695367 1.0.24 2017-06-04 23:03:28 +08:00
seven332 b2e34e622c Set default request id to invalid one 2017-06-04 23:02:13 +08:00
seven332 78db7ecbc5 1.0.23 2017-06-01 22:31:41 +08:00
seven332 4896a1edbc Use HashMap instead of WeakHashMap for GlobalStuffMap 2017-06-01 22:30:02 +08:00
seven332 61b2075302 Add e-hentai.org to intent-filter
Close #249
2017-05-25 01:04:35 +08:00
seven332 b21fe89ea1 1.0.22 2017-05-23 16:35:42 +08:00
seven332 4af054a9cd Update gradle tools 2017-05-23 16:35:19 +08:00
seven332 3f579060b5 Fix GalleryDetailParser parsing gallery cover 2017-05-23 16:31:26 +08:00
seven332 1e87279310 Avoid saving large data in ContentLayout 2017-05-23 16:21:05 +08:00
seven332 5fae1df78c Update libraries 2017-04-22 20:48:26 +08:00
seven332 84949442ee Add ISSUE_TEMPLATE English translate 2017-04-07 19:48:21 +08:00
seven332 3b395380c7 Merge remote-tracking branch 'origin/master' 2017-04-05 20:26:00 +08:00
seven332 3e3de0ff2a Update gradle library 2017-04-05 20:24:45 +08:00
seven332 da802c5371 Update ISSUE_TEMPLATE 2017-04-05 20:23:20 +08:00
seven332 24405f7c44 Merge pull request #251 from danthe100/mycommits
Fixed Spanish translation
2017-03-30 22:09:41 -05:00
Dante Garcia 9ed826a87e Fixed certain errors 2017-03-30 12:01:03 -05:00
seven332 9c5c9dfa95 Add ISSUE_TEMPLATE 2017-03-27 23:26:21 +08:00
seven332 6eb29c783a 1.0.21 2017-03-20 22:36:05 +08:00
seven332 cb11ecc9f0 Fix category parsing 2017-03-20 22:34:05 +08:00
seven332 bf5feaacd1 Merge pull request #242 from sorz/master
Add fingerprint unlock
2017-03-18 01:41:53 -05:00
seven332 0ef4088b88 Update gradle 2017-03-17 23:12:11 +08:00
sorz 1e87d34806 Add translations for fingerprint setting
Spanish by Google Translate
2017-03-16 01:52:54 +11:00
sorz 0b35fb01ee Add fingerprint on SecurityScene 2017-03-16 01:11:19 +11:00
sorz 7f1d590fbd Add fingerprint protection switch 2017-03-15 22:38:47 +11:00
seven332 97ce2bbe54 Apply Spanish strings.xml to all countries 2017-02-23 16:54:06 +08:00
seven332 d8a6424ecc Merge pull request #235 from danthe100/mycommits
Added translation into Spanish
2017-02-23 13:10:04 +08:00
Dante Garcia fdc199cc49 Added translation into Spanish 2017-02-22 20:18:17 -05:00
seven332 a02fe88765 1.0.20 2017-02-09 21:45:24 +08:00
seven332 6488de75f1 Adjust gallery detail actions order 2017-02-09 21:40:24 +08:00
seven332 439f199a10 Sanitize torrent filename 2017-02-09 21:36:44 +08:00
seven332 e535b2fa09 Fix TorrentParser 2017-02-09 21:30:07 +08:00
seven332 81ae752975 Fix Chinese translations 2017-02-09 21:24:28 +08:00
seven332 5dd584776a Fix Chinese translations 2017-02-09 21:19:36 +08:00
seven332 f617e62b85 Add android-chinese-string 2017-02-09 21:09:58 +08:00
Lin, Yi-Li 4d95a7163f use snackbar to tell users that H@H client is required for this feature 2017-01-29 17:27:56 +09:00
Lin, Yi-Li b5cae76de5 able to request archive download 2017-01-29 02:00:02 +09:00
seven332 9065e7457a 1.0.19 2017-01-26 13:30:48 +08:00
seven332 08ab9159a5 Fix RecyclerView crashing 2017-01-26 11:39:56 +08:00
seven332 6b5b961986 1.0.18 2017-01-25 13:22:09 +08:00
seven332 6a96035149 Avoid RecyclerView scrolling after detached 2017-01-25 13:19:23 +08:00
seven332 1ce035591a Fix GalleryPageParser 2017-01-25 00:13:55 +08:00
seven332 6cc78802ee 1.0.17 2017-01-24 19:41:23 +08:00
seven332 636c011c23 Rename XXX_G to XXX_E 2017-01-24 19:39:05 +08:00
seven332 92490ca1a6 e-hentai switched to HTTPS 2017-01-24 19:34:24 +08:00
seven332 b6a5d237ac Add EhUrl.getFixedPreviewThumbUrl() 2017-01-24 19:22:58 +08:00
seven332 8be0b5c588 Don't use jack anymore 2016-12-31 19:29:33 +08:00
seven332 fcbe129b6e Fix URL_PREFIX_THUMB_EX 2016-12-30 12:10:59 +08:00
seven332 befbcd6720 Add fix thumb url 2016-12-29 21:50:26 +08:00
seven332 ee5062d4c7 Add round icon 2016-12-19 00:38:26 +08:00
seven332 a4392523d6 1.0.16 2016-12-15 02:06:46 +08:00
seven332 b3371304bf Sync media store after saving image 2016-12-15 02:05:23 +08:00
seven332 38911c2d34 Be compatible with some bad share mechanism
Some apps need file path to share it, but it's not necessary at all.
2016-12-15 01:59:49 +08:00
seven332 6c5ad068d2 Update gradle tools and libraries 2016-12-15 01:30:32 +08:00
seven332 868521f19f Try to get image reload key more than once 2016-12-15 01:13:58 +08:00
seven332 c4cd965306 Add excluding japanese original
Eh site doesn't support it, but just modifying the cookie works fine.
2016-12-03 19:38:49 +08:00
seven332 639adaf7fa Close #201, list local favorites by favorited time 2016-10-29 00:05:18 +08:00
seven332 e174ee0b2c Ensure dao gen called 2016-10-22 00:42:41 +08:00
seven332 04da83f950 Set targetSdkVersion to 25 2016-10-22 00:16:06 +08:00
seven332 84a35e9283 1.0.15 2016-10-18 00:10:10 +08:00
seven332 a907db43be Update libraries 2016-10-18 00:06:09 +08:00
seven332 890be41aa5 Update gradle tool 2016-08-13 18:49:57 +08:00
seven332 f3db305cee Add https in intent-filter 2016-08-13 18:48:57 +08:00
seven332 4626ab1ec4 Update image search url 2016-07-31 19:27:59 +08:00
seven332 a44b070120 1.0.14 2016-07-28 14:28:23 +08:00
seven332 1760fb65e2 Use LinearLayout instead of android.support.v7.widget.ButtonBarLayout 2016-07-28 14:25:01 +08:00
seven332 47d28beddd 1.0.13 2016-07-28 00:17:39 +08:00
seven332 8d39829e54 Update libraries 2016-07-28 00:17:06 +08:00
seven332 2cb8319c91 Check download image size 2016-07-27 23:34:09 +08:00
seven332 27ca88f0c2 Use https for ex and forums 2016-07-27 23:32:31 +08:00
seven332 9aa033c31b Add https support for url parser 2016-07-27 23:27:27 +08:00
seven332 1f1d968766 Make error message different 2016-07-27 23:24:53 +08:00
seven332 3b8ba148dc Save temp share image to internal folder 2016-06-20 23:27:03 +08:00
seven332 5448bdf7bb Use FileProvider to share image
For apps targeting Android N, file:// URIs outside app is not supported any more.
2016-06-18 22:08:29 +08:00
seven332 e7cfd8831e Set targetSdkVersion to 24, upgrade libraries 2016-06-18 21:04:26 +08:00
seven332 148588e53a Show version name in about 2016-06-10 20:37:27 +08:00
seven332 cacfd58330 1.0.12 2016-06-09 21:14:23 +08:00
seven332 97cf075ffb Upgrade libraries 2016-06-09 21:10:21 +08:00
seven332 d93ce846e2 Remove item from decode queue when cancel request 2016-06-08 21:20:53 +08:00
seven332 7e45e379b3 Fix fragment class check 2016-06-08 20:43:21 +08:00
seven332 f3c90d46fd Remove AssertUtils 2016-06-08 20:31:47 +08:00
seven332 c80445e43a Upgrade libraries 2016-06-08 19:33:21 +08:00
seven332 4faa031ae1 Upgrade gradle tool 2016-06-07 17:55:58 +08:00
seven332 17bdb7cb93 Use Queue for decode list 2016-06-07 17:55:10 +08:00
seven332 d17f98f3e4 Upgrade GLGallery to 0.1.2 2016-06-03 01:31:34 +08:00
seven332 52bc260998 Start gallery provider before get start page 2016-06-01 18:58:44 +08:00
seven332 ebaba88cde Add GLGallery library 2016-05-31 00:01:05 +08:00
seven332 94c50b27bf Check existence of views in onAnimationEnd 2016-05-30 00:28:32 +08:00
seven332 b2cf4d1fb0 Check existence of index when clear pToken 2016-05-30 00:25:20 +08:00
seven332 b52f260c9e Avoid restore download null 2016-05-30 00:20:04 +08:00
seven332 b4fc856a51 Fix SpiderInfo read 2016-05-30 00:18:20 +08:00
seven332 e1b07b715f Add GLView library 2016-05-29 15:52:33 +08:00
seven332 1e434c09e6 Use webp image resources 2016-05-28 22:13:53 +08:00
seven332 7fb4ae682a Add compileOptions.incremental 2016-05-25 20:14:38 +08:00
seven332 f2f7821b55 Don't use TransitionDrawable when LoadImageView is not showing 2016-05-25 13:59:00 +08:00
seven332 02b5f6289e Run executeDaoGenerator after copyNotice 2016-05-24 01:30:12 +08:00
seven332 9293e92a99 Upgrade build tool and image library 2016-05-24 00:53:34 +08:00
seven332 ccd98ff36e Block new intent when SolidScene is shown 2016-05-19 16:16:48 +08:00
seven332 6c5cbd9f2f Fix for java6 2016-05-19 15:18:10 +08:00
seven332 4a7edf648b 1.0.11 2016-05-14 13:56:15 +08:00
seven332 cfc9411223 Clean up 2016-05-14 13:23:59 +08:00
seven332 05030e9bb6 Save separated memory information in crash file
app memory, app native memory, app max memory, system total memory
2016-05-14 12:54:38 +08:00
seven332 ab3fc7d842 Avoid create dir when loading thumb in download list 2016-05-14 12:45:02 +08:00
seven332 fb216a960b Lock drawer when suggestion list showing 2016-05-13 13:43:37 +08:00
seven332 c0fbdee61f Copy email address when click donate item 2016-05-13 02:12:10 +08:00
seven332 901c0ae3ec Disable zero rating to gallery 2016-05-12 14:53:46 +08:00
seven332 f727554afd Update libraries 2016-05-12 14:32:09 +08:00
seven332 b0a5666a6d Fix gallery restore
SpiderInfo has changed, but restore code was the old version
2016-05-12 01:22:31 +08:00
seven332 1edf98c9e1 1.0.10 2016-05-11 18:22:28 +08:00
seven332 32ed409a28 Update strings.xml 2016-05-10 17:09:46 +08:00
seven332 cac950fa40 Get ThumbDataContainer file in non-UI thread 2016-05-10 14:05:37 +08:00
seven332 3a03e9aad1 Change fab color
Primary fab is colorPrimary, secondary fab is colorAccent
2016-05-10 13:40:39 +08:00
seven332 971aa86c4e Set SpiderQueen.mMode to local 2016-05-10 02:10:23 +08:00
seven332 bbb5f89a66 Avoid mSpiderInfo null
Use AtomicReference for mSpiderInfo
2016-05-10 02:09:06 +08:00
seven332 f777b694d5 Add memory usage to crash file 2016-05-10 00:56:58 +08:00
seven332 d59fa1756e Use OSUtils 2016-05-10 00:46:00 +08:00
seven332 5ac9ad4d71 Upgrade yorozuya to 0.1.1 2016-05-10 00:40:51 +08:00
seven332 adb3860107 Upgrade libraries 2016-05-09 22:41:54 +08:00
seven332 81876955c6 Upgrade Yorozuya-Thread library to 0.1.1 2016-05-09 21:48:21 +08:00
seven332 b8189d76d6 Decode image partly 2016-05-09 18:47:03 +08:00
seven332 0a472d28b5 Add multi-thread support for image decoding 2016-05-09 00:40:25 +08:00
seven332 9a0ba6f676 Ensure notifyGetImageXXX called after pipe released 2016-05-08 15:52:47 +08:00
seven332 e22010f2b0 Update state at once when force request 2016-05-07 18:49:36 +08:00
seven332 5a2fe3fe19 Update beerbelly to 0.1.3 2016-05-07 18:48:44 +08:00
seven332 c9bbbca311 Set decoder thread priority to default
The priority of a decode thread was THREAD_PRIORITY_BACKGROUND. It may cause a long time waiting before image decoded.
2016-05-07 16:46:01 +08:00
seven332 83d66f9c56 Fix ptoken failed error
When get last page of gallery, the page preview count is not preview count pre page. So old version spider info file may store wrong preview count pre page. Spider info file version is added in the first line.
2016-05-07 15:51:47 +08:00
seven332 1feca40a5c Use System.nanoTime() to calculate frame delay compensation
Use System.nanoTime() instead of SystemClock.elapsedRealtime()
2016-05-07 14:17:10 +08:00
seven332 1bc07a89b8 Prepare for library upgrade 2016-05-07 14:09:03 +08:00
seven332 6c0ad0e329 Upgrade image library to 0.1.6 2016-05-07 14:03:20 +08:00
seven332 21151a5031 Fix FabLayout onClick
mExpanded blocked onClickPrimaryFab and onClickSecondaryFab before. But it should only block onClickSecondaryFab
2016-05-07 14:02:37 +08:00
seven332 74e10178be Fix default rating text 2016-05-05 22:56:43 +08:00
seven332 e289e83983 Update string.xml
Change unfavorited to not favorited
2016-05-05 01:06:33 +08:00
seven332 d07dc49dc7 Add cellular network warning 2016-05-05 01:05:00 +08:00
seven332 981598dc70 Fix some cookies missing in request 2016-05-04 23:50:29 +08:00
seven332 f82c576970 Update pd_big_weird_face 2016-05-04 21:18:24 +08:00
seven332 a0f1e97332 Upgrade image library to 0.1.5 2016-05-04 15:51:00 +08:00
seven332 2dca63b342 Avoid call fab on click listener when not expanded 2016-05-03 21:35:23 +08:00
seven332 9590c758fd 1.0.9 2016-05-03 02:50:51 +08:00
seven332 74bbbabdd4 Add debug print Image count 2016-05-03 02:46:24 +08:00
seven332 363ad7686e Use ImageMovableTextTexture instead of MovableTextTexture
NativeTexture can avoid bad buffer
2016-05-03 02:34:23 +08:00
seven332 ad9f544fe1 Add GLView.onPause and GLView.onResume 2016-05-03 00:52:03 +08:00
seven332 4c3c84f1a6 Clean up 2016-05-02 23:17:29 +08:00
seven332 512fef80db Bump TuXiang library version to 0.1.1 2016-05-02 22:50:36 +08:00
seven332 fad9e3ccc0 1.0.8 2016-05-02 19:38:21 +08:00
seven332 5aa56e0237 Add detail size options
Large for 480dp width
Small for 320dp width
2016-05-02 19:36:41 +08:00
seven332 d4d4ba8c75 Use TuXiang library
Make GLRootView extends com.hippo.tuxiang.GLSurfaceView
2016-05-02 18:56:56 +08:00
seven332 2a324c4d89 Call GLRootView onPause and onResume 2016-05-02 13:20:35 +08:00
seven332 e6638b6f56 Remove ANRWatchDog 2016-05-01 23:20:00 +08:00
seven332 5d956b43fb 1.0.7 2016-05-01 17:11:17 +08:00
seven332 9e19b16735 Close #142, save thumb to download dir 2016-05-01 17:08:03 +08:00
seven332 af8cc34048 Bump image library version 2016-05-01 15:53:18 +08:00
seven332 430e748490 Remove TODO list 2016-05-01 15:23:46 +08:00
seven332 297c35b14d Use custom GLSurfaceView
Ensure GLRootView's mContentView.detachFromRoot() called in render thread
2016-05-01 15:21:26 +08:00
seven332 b973e0244e Add gallery image cache 2016-05-01 13:26:13 +08:00
seven332 f672fe1e96 Remove 'git submodule update --init' in build instruction 2016-04-30 19:09:22 +08:00
seven332 e3113083bc Use jitpack libraries 2016-04-30 19:03:59 +08:00
seven332 d186a6ac3b Run copyNotice task automatically 2016-04-28 02:07:17 +08:00
seven332 10693c5ffc Use jack and jill 2016-04-27 22:07:42 +08:00
seven332 9b54fd09c9 Bump gradle tool version 2016-04-27 22:06:30 +08:00
seven332 7f4dc1f131 Fix regex for jack 2016-04-27 21:58:56 +08:00
seven332 5638832c05 Use image library 2016-04-27 21:15:01 +08:00
seven332 a7e8b96b4c Change gallery_list_column_width to 480dp 2016-04-26 18:04:39 +08:00
seven332 a8df181ff8 Add TODO list 2016-04-26 18:03:45 +08:00
seven332 58acaa7287 Add html-format NOTICE 2016-04-25 17:03:35 +08:00
seven332 b00ed5a360 Bump libraries version 2016-04-25 17:02:05 +08:00
seven332 42eeb4f44c Bump libraries and gradle tool version 2016-04-25 00:10:11 +08:00
seven332 2ccb5d92c9 Bump gradle tool version 2016-04-21 16:41:38 +08:00
seven332 e12a35cb52 Remove DumpBrowsableActivity to fix default app error 2016-04-21 16:41:05 +08:00
seven332 fbeaf3d5ea Add anr watch dog 2016-04-14 19:10:38 +08:00
seven332 b4d8168457 Bump gradle tool version 2016-04-14 14:50:23 +08:00
seven332 9561fcf662 requestLayout when set different-size ImageTexture in ImageView 2016-04-14 02:40:25 +08:00
seven332 453a56aa23 Use hotspot and ripple library 2016-04-14 00:58:38 +08:00
seven332 df108f9678 Adjust build instruction for Linux 2016-04-13 14:04:26 +08:00
seven332 a835ca9547 Remove some @TargetApi 2016-04-13 01:54:45 +08:00
seven332 3f4cc46bc1 Do not show animation for image has no valid rect 2016-04-12 01:09:13 +08:00
seven332 27bc38ae8b Fix gif delay calculation 2016-04-12 00:55:36 +08:00
seven332 fd1aca48d6 Update UniFile library 2016-04-12 00:22:44 +08:00
seven332 adbb1f11a5 Use SystemClock.currentThreadTimeMillis to calculate gif delay 2016-04-12 00:21:58 +08:00
seven332 4b8e46d220 Use drawerLayout library 2016-04-11 15:36:00 +08:00
seven332 1c45c4b042 Add thumb resolution option 2016-04-11 14:28:01 +08:00
seven332 d33e3c27fc Rename image_size to image_resolution 2016-04-11 13:59:35 +08:00
seven332 189a95e49c Use RefreshLayout from jitpack 2016-04-11 00:05:17 +08:00
seven332 4e3717fa69 Avoid write null in SpiderInfo 2016-04-10 15:58:41 +08:00
seven332 97d51b1fc3 Start home page when can't recognize the intent 2016-04-10 15:41:17 +08:00
seven332 ba5a554ca8 Use unifile library for jitpack 2016-04-10 15:22:48 +08:00
seven332 b4095449c1 Fix mDownloadingDelay NullPointerException 2016-04-09 22:36:20 +08:00
seven332 05f9ce59f3 Update giflib to 5.1.4 2016-04-09 21:42:50 +08:00
seven332 793dca3674 Set APP_PLATFORM to android-15 2016-04-09 21:42:23 +08:00
seven332 e10172c09c Hide ime in go to dialog 2016-04-09 20:41:52 +08:00
seven332 2d65b71fff Rename ActivityHelper to AppHelper 2016-04-09 20:35:57 +08:00
seven332 7693275967 Use card for gallery thumb 2016-04-09 18:40:31 +08:00
seven332 9d4eadffac Add up react to SnackBar 2016-04-09 16:52:27 +08:00
seven332 1bf826a923 Clean up 2016-04-09 13:44:12 +08:00
seven332 4866e963de 1.0.6 2016-04-09 02:01:02 +08:00
seven332 2b15c8f620 Use clipRect instead of clipPath in SearchBar 2016-04-09 01:54:47 +08:00
seven332 d9265610c3 Check pages in read SpiderInfo 2016-04-08 22:44:09 +08:00
seven332 81dce7d297 Remove customtabs, set minSdkVersion to 14 2016-04-08 22:40:36 +08:00
seven332 078d086362 1.0.5 2016-04-08 22:09:15 +08:00
seven332 492d483467 Request again if image missing in cache 2016-04-08 21:19:57 +08:00
seven332 d9c1b81eb3 Add support zip file support for GalleryActivity 2016-04-08 20:46:07 +08:00
seven332 a2a9dbcb02 Add media scan config 2016-04-08 20:28:05 +08:00
seven332 97c28c04c5 Fix typo 2016-04-08 19:53:08 +08:00
seven332 f4d8cbf3a4 Add back icon callback in SetSecurityActivity 2016-04-08 19:49:58 +08:00
seven332 4291493256 Fix status bar background color above NavigationView 2016-04-08 19:33:13 +08:00
seven332 ce6cb19e73 Rename SlidingDrawerLayout to DrawerLayout 2016-04-08 18:59:36 +08:00
seven332 574d09302e Bump libraries version 2016-04-08 16:36:41 +08:00
seven332 f37b479400 Adjust table layout 2016-04-08 15:30:11 +08:00
seven332 87c27b6256 Avoid showing download path warning for the first time 2016-04-08 02:02:09 +08:00
seven332 b3881f8562 Adjust layout for table 2016-04-07 20:45:20 +08:00
seven332 3f8e872d55 Apply new MarginItemDecoration 2016-04-07 19:33:09 +08:00
seven332 7e62673e5a Improve SpiderQueen 2016-04-07 02:23:52 +08:00
seven332 69be0c48fb Put save parse error to AppConfig 2016-04-07 02:23:10 +08:00
seven332 9d783fa86d Use GetText in ExceptionUtils 2016-04-07 02:22:06 +08:00
seven332 28b81a0db0 Fix parse gallery page error in e-hentai 2016-04-07 02:16:13 +08:00
seven332 3ac1964069 Adjust download thumb guide 2016-04-07 00:53:35 +08:00
seven332 a2241e62a3 Fix SwipeProgressBar finish animation 2016-04-07 00:33:50 +08:00
seven332 100a3d872e Set minSdkVersion to 15 2016-04-06 18:24:33 +08:00
seven332 413a17acf1 Update icon 2016-04-06 18:05:49 +08:00
seven332 79bc2bcd22 Apply thumb size settings to preview size 2016-04-06 14:53:33 +08:00
seven332 c6e45cc080 Update EasyRecyclerView 2016-04-06 01:53:05 +08:00
seven332 7a215acd18 Add progress in GalleryActivity 2016-04-05 20:38:26 +08:00
seven332 3ca6b69984 Add image size option 2016-04-05 02:07:08 +08:00
seven332 084f352d71 Add favorites sort, image size, gallery title, popular for EhConfig 2016-04-05 00:47:11 +08:00
seven332 f4a16b3edd Only show error when no cookie saved 2016-04-04 22:20:58 +08:00
seven332 e8d8ee8501 1.0.4 2016-04-04 21:08:53 +08:00
seven332 9a87701ad6 Fix memory leak which due to GalleryView.onDetachFromRootInternal not called 2016-04-04 15:20:26 +08:00
seven332 cdc8a7aea6 Adjust GLView attachToRoot detachFromRoot 2016-04-04 15:12:33 +08:00
seven332 90bfd445d1 Do not show warning after get profile error 2016-04-04 13:24:20 +08:00
seven332 7493bd57f4 Fix not showing click-thumb-detail guide 2016-04-04 13:15:52 +08:00
seven332 629c2bb80d Fix add to favorites failed 2016-04-03 23:59:17 +08:00
seven332 4d45d717e2 1.0.3 2016-04-03 20:18:38 +08:00
seven332 b8e80c6c8c Make identity live long 2016-04-03 20:15:58 +08:00
seven332 efed7776d3 Remove cancel button in sign in failed dialog 2016-04-03 19:24:57 +08:00
seven332 56cfc0669b Add set read cache max size 2016-04-03 19:19:20 +08:00
seven332 6d9ed41382 Don't scroll vertically unloaded page when scaling for ScrollLayoutManager 2016-04-03 18:20:46 +08:00
seven332 505efbdef6 Avoid unnecessary invalidate in GalleryView 2016-04-03 17:18:41 +08:00
seven332 52ab8cebb0 Improve ScrollLayoutManager 2016-04-03 17:12:13 +08:00
seven332 e8251ee521 Improve PageLayoutManager scale 2016-04-03 02:37:28 +08:00
seven332 d4195c6e5b Add scale for ScrollLayoutManager 2016-04-03 02:36:51 +08:00
seven332 f50975d767 Adjust search bar size 2016-04-02 23:11:56 +08:00
seven332 4d9452c791 Add thumb size option 2016-04-02 21:12:17 +08:00
seven332 474eea094d Add remove download redundancy 2016-04-02 19:14:42 +08:00
seven332 bbb6b634ff Remove unused resources 2016-04-02 16:59:32 +08:00
seven332 d5da97141f Remove unsupported language 2016-04-02 16:59:03 +08:00
seven332 a12f9ba595 Add fullscreen option 2016-04-02 16:36:37 +08:00
seven332 75944e5a8b Improve EhGalleryProvider 2016-04-02 16:03:49 +08:00
seven332 1aa51a5934 Bump gradle version 2016-04-02 15:49:35 +08:00
seven332 092fd6779c Bump build tools version 2016-04-02 15:42:14 +08:00
seven332 618dc2b180 Adjust SlidingDrawerLayout min margin 2016-04-02 14:05:21 +08:00
seven332 44a84f2bc2 1.0.2 2016-04-02 00:06:20 +08:00
seven332 5fb3b61669 Add screen lightness 2016-04-01 23:18:37 +08:00
seven332 57a9865d99 Add rotation effect for showing fab 2016-04-01 20:08:07 +08:00
seven332 250e1256b9 Add insert helper for SlidingDrawerLayout 2016-04-01 19:18:00 +08:00
seven332 015bcce8a3 Use -1.0f instead of NaN to represent no rating 2016-04-01 18:18:31 +08:00
seven332 b874a259fe Improve SimpleRatingView 2016-04-01 18:08:53 +08:00
seven332 c8ab84aa9e Improve render status bar and nav bar 2016-04-01 17:18:05 +08:00
seven332 d6efe2c7ba Fix status bar color in KK 2016-04-01 17:17:39 +08:00
seven332 46915fed3a Close #133, search via sharing 2016-04-01 16:22:27 +08:00
seven332 5d1f599f48 OH MY GREENDAO 2016-04-01 14:38:44 +08:00
seven332 9d5877e867 Hide status bar for pre-KK 2016-04-01 14:20:34 +08:00
seven332 e998f80574 Use no padding card 2016-04-01 02:03:32 +08:00
871 changed files with 27187 additions and 153801 deletions

No files matched your search

@@ -0,0 +1,20 @@
---
name: 功能申请 / Feature request
about: 有个想法 / Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**这个功能是用来解决问题的吗? / Is your feature request related to a problem? Please describe.**
描述这个问题。
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**描述你想要的解决方法 / Describe the solution you'd like**
描述应通过何种行为来解决这个问题。
A clear and concise description of what you want to happen.
**备注 / Additional context**
还有别的想说的吗?
Add any other context or screenshots about the feature request here.
@@ -0,0 +1,41 @@
---
name: Bug 反馈 / Bug report
about: 出问题了 / Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**简略描述 / Describe the bug**
大概说下是什么问题。
A clear and concise description of what the bug is.
**如何重现 / To Reproduce**
重现的步骤:
1. 打开什么什么
2. 点击什么什么
3. 出现什么什么问题
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**预期行为 / Expected behavior**
应该是什么样子的?
A clear and concise description of what you expected to happen.
**截图 / Screenshots**
能截图的话就发截图,请注意风序良俗。
If applicable, add screenshots to help explain your problem.
**设备型号与 Android 版本 / Device model and Android version**
- 设备型号:【比如 Pixel 6 XXXL】
- Android 版本:【比如 Android 12.1】
- Device model: [e.g. Pixel 6 XXXL]
- Android version: [e.g. Android 12.1]
**备注 / Additional context**
还有什么想说的?
Add any other context about the problem here.
@@ -0,0 +1,11 @@
---
name: Sad Panda / 下载太慢 / Slow download speed
about: 所有其他问题 / All other questions
title: ''
labels: ''
assignees: ''
---
加入我们的 Telegram 群组,[https://t.me/ehviewer](https://t.me/ehviewer)。温柔[大小]姐姐手把手帮你解决问题。
Join our Telegram group, [https://t.me/ehviewer](https://t.me/ehviewer). Administrators will help you solve the problem.
+2
View File
@@ -6,3 +6,5 @@
*.iml
.idea
/captures
release
google-services.json
-21
View File
@@ -1,21 +0,0 @@
[submodule "yorozuya"]
path = yorozuya
url = https://github.com/seven332/Yorozuya
[submodule "hotspot"]
path = hotspot
url = https://github.com/seven332/Hotspot
[submodule "easyrecyclerview"]
path = easyrecyclerview
url = https://github.com/seven332/EasyRecyclerView
[submodule "beerbelly"]
path = beerbelly
url = https://github.com/seven332/BeerBelly
[submodule "conaco"]
path = conaco
url = https://github.com/seven332/Conaco
[submodule "rippleold"]
path = rippleold
url = https://github.com/seven332/RippleOld
[submodule "unifile"]
path = unifile
url = https://github.com/seven332/UniFile
+4 -843
View File
@@ -1,846 +1,7 @@
======================================================================
EhViewer
======================================================================
Copyright 2014-2016 Hippo Seven
Copyright (C) 2014-2016 Hippo Seven
An Unofficial E-Hentai Application for Android.
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.
======================================================================
Library ("Advanced RecyclerView")
======================================================================
Copyright (C) 2015 Haruki Hasegawa
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.
======================================================================
Library ("giflib")
======================================================================
The GIFLIB distribution is Copyright (c) 1997 Eric S. Raymond
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
======================================================================
Library ("greenDAO")
======================================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
======================================================================
Library ("jsoup")
======================================================================
The MIT License
© 2009-2015, Jonathan Hedley <jonathan@hedley.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
======================================================================
Library ("libjpeg-turbo")
======================================================================
libjpeg-turbo Licenses
----------------------
libjpeg-turbo is covered by three compatible BSD-style open source licenses:
-- The IJG (Independent JPEG Group) License, which is listed in README
This license applies to the libjpeg API library and associated programs
(any code inherited from libjpeg, and any modifications to that code.)
-- The Modified (3-clause) BSD License, which is listed in turbojpeg.c
This license covers the TurboJPEG API library and associated programs.
-- The zlib License, which is listed in simd/jsimdext.inc
This license is a subset of the other two, and it covers the libjpeg-turbo
SIMD extensions.
Complying with the libjpeg-turbo Licenses
-----------------------------------------
This section provides a roll-up of the libjpeg-turbo licensing terms, to the
best of our understanding.
1. If you are distributing a modified version of the libjpeg-turbo source,
then:
a. You cannot alter or remove any existing copyright or license notices
from the source.
Origin: Clause 1 of the IJG License
Clause 1 of the Modified BSD License
Clauses 1 and 3 of the zlib License
b. You must add your own copyright notice to the header of each source
file you modified, so others can tell that you modified that file (if
there is not an existing copyright header in that file, then you can
simply add a notice stating that you modified the file.)
Origin: Clause 1 of the IJG License
Clause 2 of the zlib License
c. You must include the IJG README file, and you must not alter any of the
copyright or license text in that file.
Origin: Clause 1 of the IJG License
2. If you are distributing only libjpeg-turbo binaries without the source, or
if you are distributing an application that statically links with
libjpeg-turbo, then:
a. Your product documentation must include a message stating:
This software is based in part on the work of the Independent JPEG
Group.
Origin: Clause 2 of the IJG license
b. If your binary distribution includes or uses the TurboJPEG API, then
your product documentation must include the text of the Modified BSD
License.
Origin: Clause 2 of the Modified BSD License
3. You cannot use the name of the IJG or The libjpeg-turbo Project or the
contributors thereof in advertising, publicity, etc.
Origin: IJG License
Clause 3 of the Modified BSD License
4. The IJG and The libjpeg-turbo Project do not warrant libjpeg-turbo to be
free of defects, nor do we accept any liability for undesirable
consequences resulting from your use of the software.
Origin: IJG License
Modified BSD License
zlib License
======================================================================
Library ("libpng" + "apng")
======================================================================
This copy of the libpng notices is provided for your convenience. In case of
any discrepancy between this copy and the notices in the file png.h that is
included in the libpng distribution, the latter shall prevail.
COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
If you modify libpng you may insert additional notices immediately following
this sentence.
This modified version of libpng code adds animated PNG support and is
released under the libpng license described below. The modifications are
Copyright (c) 2006-2007 Andrew Smith, Copyright (c) 2008-2015 Max Stepin,
and are delimited by "#ifdef PNG_APNG_SUPPORTED / #endif" directives
surrounding them in the modified libpng source files.
This code is released under the libpng license.
libpng versions 1.0.7, July 1, 2000, through 1.6.20, December 3, 2015, are
Copyright (c) 2000-2002, 2004, 2006-2015 Glenn Randers-Pehrson, are
derived from libpng-1.0.6, and are distributed according to the same
disclaimer and license as libpng-1.0.6 with the following individuals
added to the list of Contributing Authors:
Simon-Pierre Cadieux
Eric S. Raymond
Mans Rullgard
Cosmin Truta
Gilles Vollant
James Yu
and with the following additions to the disclaimer:
There is no warranty against interference with your enjoyment of the
library or against infringement. There is no warranty that our
efforts or the library will fulfill any of your particular purposes
or needs. This library is provided with all faults, and the entire
risk of satisfactory quality, performance, accuracy, and effort is with
the user.
libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
libpng-0.96, and are distributed according to the same disclaimer and
license as libpng-0.96, with the following individuals added to the list
of Contributing Authors:
Tom Lane
Glenn Randers-Pehrson
Willem van Schaik
libpng versions 0.89, June 1996, through 0.96, May 1997, are
Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
and are distributed according to the same disclaimer and license as
libpng-0.88, with the following individuals added to the list of
Contributing Authors:
John Bowler
Kevin Bracey
Sam Bushell
Magnus Holmgren
Greg Roelofs
Tom Tanner
libpng versions 0.5, May 1995, through 0.88, January 1996, are
Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
For the purposes of this copyright and license, "Contributing Authors"
is defined as the following set of individuals:
Andreas Dilger
Dave Martindale
Guy Eric Schalnat
Paul Schmidt
Tim Wegner
The PNG Reference Library is supplied "AS IS". The Contributing Authors
and Group 42, Inc. disclaim all warranties, expressed or implied,
including, without limitation, the warranties of merchantability and of
fitness for any purpose. The Contributing Authors and Group 42, Inc.
assume no liability for direct, indirect, incidental, special, exemplary,
or consequential damages, which may result from the use of the PNG
Reference Library, even if advised of the possibility of such damage.
Permission is hereby granted to use, copy, modify, and distribute this
source code, or portions hereof, for any purpose, without fee, subject
to the following restrictions:
1. The origin of this source code must not be misrepresented.
2. Altered versions must be plainly marked as such and must not
be misrepresented as being the original source.
3. This Copyright notice may not be removed or altered from any
source or altered source distribution.
The Contributing Authors and Group 42, Inc. specifically permit, without
fee, and encourage the use of this source code as a component to
supporting the PNG file format in commercial products. If you use this
source code in a product, acknowledgment is not required but would be
appreciated.
END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.
A "png_get_copyright" function is available, for convenient use in "about"
boxes and the like:
printf("%s", png_get_copyright(NULL));
Also, the PNG logo (in PNG format, of course) is supplied in the
files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
Libpng is OSI Certified Open Source Software. OSI Certified Open Source is
a certification mark of the Open Source Initiative. OSI has not addressed
the additional disclaimers inserted at version 1.0.7.
Glenn Randers-Pehrson
glennrp at users.sourceforge.net
December 3, 2015
======================================================================
Library ("OkHttp")
======================================================================
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.
======================================================================
Library ("roaster")
======================================================================
Forge Roaster
Copyright 2011-2015 Red Hat Inc. and/or its affiliates.
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
======================================================================
Library ("ShowcaseView")
======================================================================
Copyright Alex Curran (@amlcurran) © 2012-2014. All rights reserved.
This library is distributed under an Apache 2.0 License.
======================================================================
Font ("Slabo")
======================================================================
Copyright (c) 2013, Tiro Typeworks Ltd (www.tiro.com).
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
======================================================================
Library ("TagSoup")
======================================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
香风智乃是最可爱的女孩子。
chino kafuu is the cutest girl.
+1840
View File
File diff suppressed because it is too large. Load diff
+19 -12
View File
@@ -1,3 +1,7 @@
# DEPRECATED
[![Telegram](https://img.shields.io/badge/chat-Telegram-blue.svg)](https://t.me/ehviewer)
# EhViewer
![Icon](art/launcher_icon-web.png)
@@ -14,26 +18,28 @@ An E-Hentai Application for Android.
# Build
Windows
> git clone https://github.com/seven332/EhViewer
> cd EhViewer
> gradlew app:assembleDebug
Linux
$ git clone https://github.com/seven332/EhViewer
$ cd EhViewer
$ git submodule update --init
$ gradlew app:copyNotice
$ gradlew daogenerator:executeDaoGenerator
$ gradlew app:assembleDebug
$ ./gradlew app:assembleDebug
生成的 apk 文件在 app\build\outputs\apk 目录下
The apk is in app\build\outputs\apk
**注意**:如果你遇到了下面这样的错误,需要添加系统变量 NDK_HOME 为 android NDK 路径
**Note**: If you get the error below, set NDK_HOME environment variable
# Download
* What went wrong:
A problem occurred evaluating project ':app'.
> assert ndkDir != null
| |
null false
[下载](https://github.com/seven332/EhViewer/releases)
[Download](https://github.com/seven332/EhViewer/releases)
# Thanks
@@ -44,6 +50,7 @@ Here is the libraries
- [AOSP](http://source.android.com/)
- [android-advancedrecyclerview](https://github.com/h6ah4i/android-advancedrecyclerview)
- [Apache Commons Lang](https://commons.apache.org/proper/commons-lang/)
- [apng](http://apng.sourceforge.net/)
- [giflib](http://giflib.sourceforge.net)
- [greenDAO](https://github.com/greenrobot/greenDAO)
@@ -59,7 +66,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.
+1 -1
View File
@@ -1,4 +1,4 @@
/src/main/assets/NOTICE
/src/main/assets/NOTICE.html
/build
/src/main/java-gen
manifest-merger-release-report.txt
+90 -58
View File
@@ -1,87 +1,119 @@
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
if (file('google-services.json').exists()) {
apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric'
}
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
compileSdkVersion 28
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 16
targetSdkVersion 23
versionCode 54
versionName "1.0.1"
minSdkVersion 14
targetSdkVersion 28
versionCode 104
versionName "1.7.3"
vectorDrawables.useSupportLibrary = true
resConfigs "zh", "zh-rCN", "zh-rHK", "zh-rTW",
"es", "ja", "ko", "fr", "de", "th"
testOptions.unitTests.includeAndroidResources = true
ndk {
abiFilters "armeabi-v7a", "x86"
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lintOptions {
disable 'MissingTranslation'
abortOnError true
checkReleaseBuilds true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField 'String', 'FILE_PROVIDER_AUTHORITY', '"com.hippo.ehviewer.fileprovider"'
}
debug {
applicationIdSuffix ".debug"
buildConfigField 'String', 'FILE_PROVIDER_AUTHORITY', '"com.hippo.ehviewer.debug.fileprovider"'
}
}
sourceSets {
main {
java.srcDirs += 'src/main/java-gen'
// Disable default NdkCompile task
jni.srcDirs = []
// Set new jni lib dir
jniLibs.srcDir 'src/main/libs'
}
}
// noinspection GroovyAssignabilityCheck
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
def ndkDir = project.plugins.findPlugin('com.android.application').sdkHandler.getNdkFolder()
if (ndkDir == null) {
ndkDir = System.getenv('NDK_HOME')
}
assert ndkDir != null
def ndkBuilder
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
ndkBuilder = 'ndk-build.cmd'
} else {
ndkBuilder = 'ndk-build'
}
commandLine "$ndkDir\\$ndkBuilder",
'-C', file('src/main/jni').absolutePath,
'-j', Runtime.runtime.availableProcessors()
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
}
clean {
delete file('src/main/obj').absolutePath
delete file('src/main/libs').absolutePath
}
task copyNotice(type: Copy) {
from '../NOTICE'
from '../NOTICE.html'
into './src/main/assets'
finalizedBy ":daogenerator:executeDaoGenerator"
}
tasks.withType(JavaCompile) {
task -> task.dependsOn copyNotice
}
clean {
delete file('src/main/assets/NOTICE.html').absolutePath
}
dependencies {
compile project(':beerbelly')
compile project(':conaco')
compile project(':easyrecyclerview')
compile project(':hotspot')
compile project(':okhttp3')
compile project(':rippleold')
compile project(':unifile')
compile project(':yorozuya')
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:customtabs:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.github.amlcurran.showcaseview:library:5.4.1'
compile 'com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.8.7'
compile 'de.greenrobot:greendao:2.1.0'
compile 'org.ccil.cowan.tagsoup:tagsoup:1.2.1'
compile 'org.jsoup:jsoup:1.8.3'
implementation fileTree(include: ['*.jar'], dir: 'libs')
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: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: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.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: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.12.1'
testImplementation 'junit:junit:4.12'
testImplementation 'org.robolectric:robolectric:4.2.1'
testImplementation 'org.jooq:joor:0.9.6'
}
configurations.all {
resolutionStrategy {
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'
}
}
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:shortcutId="start_all"
android:enabled="true"
android:icon="@drawable/ic_shortcut_start"
android:shortcutShortLabel="@string/download_start_all"
android:shortcutLongLabel="@string/download_start_all"
android:shortcutDisabledMessage="@string/download_start_all">
<intent
android:action="start_all"
android:targetPackage="com.hippo.ehviewer.debug"
android:targetClass="com.hippo.ehviewer.shortcuts.ShortcutsActivity"/>
<categories android:name="android.shortcut.conversation" />
</shortcut>
<shortcut
android:shortcutId="stop_all"
android:enabled="true"
android:icon="@drawable/ic_shortcut_stop"
android:shortcutShortLabel="@string/download_stop_all"
android:shortcutLongLabel="@string/download_stop_all"
android:shortcutDisabledMessage="@string/download_stop_all">
<intent
android:action="stop_all"
android:targetPackage="com.hippo.ehviewer.debug"
android:targetClass="com.hippo.ehviewer.shortcuts.ShortcutsActivity" />
<categories android:name="android.shortcut.conversation" />
</shortcut>
</shortcuts>
Regular → Executable
+113 -44
View File
@@ -22,17 +22,26 @@
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<application
android:name="com.hippo.ehviewer.EhApplication"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:allowBackup="true"
android:fullBackupContent="@xml/backup_scheme"
android:largeHeap="true">
android:largeHeap="true"
android:networkSecurityConfig="@xml/network_security_config">
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
<meta-data android:name="android.max_aspect" android:value="2.1"/>
<activity
android:name="com.hippo.ehviewer.ui.MainActivity"
@@ -46,97 +55,157 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="http"/>
<data android:scheme="https"/>
<data android:host="exhentai.org"/>
<data android:host="e-hentai.org"/>
<data android:host="g.e-hentai.org"/>
<data android:host="lofi.e-hentai.org"/>
</intent-filter>
<intent-filter android:label="@string/keyword_search">
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
<intent-filter android:label="@string/image_search">
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
</intent-filter>
</activity>
<activity
android:name="com.hippo.ehviewer.ui.DumpBrowsableActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter android:priority="-10">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="http"/>
<data android:host="exhentai.org"/>
<data android:host="g.e-hentai.org"/>
<data android:host="lofi.e-hentai.org"/>
<data android:pathPrefix="/g/"/>
</intent-filter>
</activity>
<activity-alias
android:name="com.hippo.ehviewer.ui.DumpBrowsableActivity2"
android:targetActivity="com.hippo.ehviewer.ui.DumpBrowsableActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter android:priority="-10">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="http"/>
<data android:host="exhentai.org"/>
<data android:host="g.e-hentai.org"/>
<data android:host="lofi.e-hentai.org"/>
<data android:pathPrefix="/s/"/>
</intent-filter>
</activity-alias>
<activity
android:name="com.hippo.ehviewer.ui.GalleryActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.Gallery"
android:launchMode="singleTask"/>
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="file"/>
<data android:scheme="content"/>
<data android:host="*"/>
<data android:mimeType="application/octet-stream"/>
<data android:mimeType="application/7z"/>
<data android:mimeType="application/rar"/>
<data android:mimeType="application/zip"/>
<data android:mimeType="application/x-7z-compressed"/>
<data android:mimeType="application/x-rar-compressed"/>
<data android:mimeType="application/x-zip-compressed"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="file"/>
<data android:scheme="content"/>
<data android:host="*"/>
<data android:pathPattern=".*\\.7z"/>
<data android:pathPattern=".*\\.rar"/>
<data android:pathPattern=".*\\.zip"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="file"/>
<data android:scheme="content"/>
<data android:host="*"/>
<data android:mimeType="*/*"/>
<data android:pathPattern=".*\\.7z"/>
<data android:pathPattern=".*\\.rar"/>
<data android:pathPattern=".*\\.zip"/>
</intent-filter>
</activity>
<activity
android:name="com.hippo.ehviewer.ui.SettingsActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme"/>
android:theme="@style/AppTheme.Settings"/>
<activity
android:name="com.hippo.ehviewer.ui.ExcludedLanguagesActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/excluded_languages"/>
<activity
android:name="com.hippo.ehviewer.ui.DirPickerActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/dir_picker"/>
<activity
android:name="com.hippo.ehviewer.ui.LicenseActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/license"/>
<activity
android:name="com.hippo.ehviewer.ui.FilterActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/filter"/>
<activity
android:name="com.hippo.ehviewer.ui.SetSecurityActivity"
android:configChanges="screenSize|uiMode"
android:theme="@style/AppTheme.NoActionBar"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/set_pattern_protection"/>
<activity
android:name="com.hippo.ehviewer.ui.UConfigActivity"
android:configChanges="screenSize|uiMode"
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"
android:theme="@style/AppTheme.Toolbar"
android:label="@string/hosts"/>
<activity
android:name="com.hippo.ehviewer.shortcuts.ShortcutsActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:excludeFromRecents="true"
android:taskAffinity=""
android:launchMode="singleTask">
</activity>
<service
android:name="com.hippo.ehviewer.download.DownloadService"
android:icon="@mipmap/ic_launcher"
android:label="@string/download_service_label"/>
<provider
android:name="com.hippo.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="com.hippo.content.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths"/>
</provider>
</application>
</manifest>
@@ -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 class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider {
public abstract class AppCompatPreferenceActivity extends PreferenceActivity implements AppCompatCallback,
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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
}
/**
* 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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
* </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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
*/
@Override
@CallSuper
public void onSupportActionModeStarted(ActionMode mode) {
public void onSupportActionModeStarted(@NonNull ActionMode mode) {
}
/**
@@ -203,7 +251,7 @@ public class AppCompatPreferenceActivity extends PreferenceActivity implements A
*/
@Override
@CallSuper
public void onSupportActionModeFinished(ActionMode mode) {
public void onSupportActionModeFinished(@NonNull ActionMode mode) {
}
/**
@@ -217,14 +265,49 @@ public class AppCompatPreferenceActivity extends PreferenceActivity implements A
*/
@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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
* 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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
*
* <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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
* 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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
* 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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
* <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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
/**
* 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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
* <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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
*
* @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 class AppCompatPreferenceActivity extends PreferenceActivity implements A
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;
@@ -0,0 +1,113 @@
/*
* Copyright 2018 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.app;
import android.content.Context;
import android.preference.PreferenceActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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;
public abstract class PrettyPreferenceActivity extends AppCompatPreferenceActivity {
@Override
public void setListAdapter(ListAdapter adapter) {
if (adapter == null) {
super.setListAdapter(null);
return;
}
int count = adapter.getCount();
List<PreferenceActivity.Header> headers = new ArrayList<>(count);
for (int i = 0; i < count; ++i) {
headers.add((PreferenceActivity.Header) adapter.getItem(i));
}
super.setListAdapter(new HeaderAdapter(this, headers, R.layout.item_preference_header, true));
}
private static class HeaderAdapter extends ArrayAdapter<PreferenceActivity.Header> {
private static class HeaderViewHolder {
ImageView icon;
TextView title;
TextView summary;
}
private LayoutInflater mInflater;
private int mLayoutResId;
private boolean mRemoveIconIfEmpty;
private HeaderAdapter(Context context, List<PreferenceActivity.Header> objects, int layoutResId,
boolean removeIconBehavior) {
super(context, 0, objects);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLayoutResId = layoutResId;
mRemoveIconIfEmpty = removeIconBehavior;
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
HeaderViewHolder holder;
View view;
if (convertView == null) {
view = mInflater.inflate(mLayoutResId, parent, false);
holder = new HeaderViewHolder();
holder.icon = view.findViewById(android.R.id.icon);
holder.title = view.findViewById(android.R.id.title);
holder.summary = view.findViewById(android.R.id.summary);
view.setTag(holder);
} else {
view = convertView;
holder = (HeaderViewHolder) view.getTag();
}
// All view fields must be updated every time, because the view may be recycled
PreferenceActivity.Header header = getItem(position);
if (mRemoveIconIfEmpty) {
if (header.iconRes == 0) {
holder.icon.setVisibility(View.GONE);
} else {
holder.icon.setVisibility(View.VISIBLE);
holder.icon.setImageResource(header.iconRes);
}
} else {
holder.icon.setImageResource(header.iconRes);
}
holder.title.setText(header.getTitle(getContext().getResources()));
CharSequence summary = header.getSummary(getContext().getResources());
if (!TextUtils.isEmpty(summary)) {
holder.summary.setVisibility(View.VISIBLE);
holder.summary.setText(summary);
} else {
holder.summary.setVisibility(View.GONE);
}
return view;
}
}
}
@@ -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;
/**
@@ -0,0 +1,61 @@
/*
* Copyright 2018 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.content;
/*
* Created by Hippo on 2018/3/27.
*/
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import java.util.Locale;
public class ContextLocalWrapper extends ContextWrapper {
public ContextLocalWrapper(Context base) {
super(base);
}
public static ContextLocalWrapper wrap(Context context, Locale newLocale) {
Resources res = context.getResources();
Configuration configuration = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
configuration.setLocale(newLocale);
LocaleList localeList = new LocaleList(newLocale);
LocaleList.setDefault(localeList);
configuration.setLocales(localeList);
context = context.createConfigurationContext(configuration);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLocale(newLocale);
context = context.createConfigurationContext(configuration);
} else {
configuration.locale = newLocale;
res.updateConfiguration(configuration, res.getDisplayMetrics());
}
return new ContextLocalWrapper(context);
}
}
@@ -0,0 +1,814 @@
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
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 org.xmlpull.v1.XmlPullParserException;
/**
* FileProvider is a special subclass of {@link ContentProvider} that facilitates secure sharing
* of files associated with an app by creating a <code>content://</code> {@link Uri} for a file
* instead of a <code>file:///</code> {@link Uri}.
* <p>
* A content URI allows you to grant read and write access using
* temporary access permissions. When you create an {@link Intent} containing
* a content URI, in order to send the content URI
* to a client app, you can also call {@link Intent#setFlags(int) Intent.setFlags()} to add
* permissions. These permissions are available to the client app for as long as the stack for
* a receiving {@link android.app.Activity} is active. For an {@link Intent} going to a
* {@link android.app.Service}, the permissions are available as long as the
* {@link android.app.Service} is running.
* <p>
* In comparison, to control access to a <code>file:///</code> {@link Uri} you have to modify the
* file system permissions of the underlying file. The permissions you provide become available to
* <em>any</em> app, and remain in effect until you change them. This level of access is
* fundamentally insecure.
* <p>
* The increased level of file access security offered by a content URI
* makes FileProvider a key part of Android's security infrastructure.
* <p>
* This overview of FileProvider includes the following topics:
* </p>
* <ol>
* <li><a href="#ProviderDefinition">Defining a FileProvider</a></li>
* <li><a href="#SpecifyFiles">Specifying Available Files</a></li>
* <li><a href="#GetUri">Retrieving the Content URI for a File</li>
* <li><a href="#Permissions">Granting Temporary Permissions to a URI</a></li>
* <li><a href="#ServeUri">Serving a Content URI to Another App</a></li>
* </ol>
* <h3 id="ProviderDefinition">Defining a FileProvider</h3>
* <p>
* Since the default functionality of FileProvider includes content URI generation for files, you
* don't need to define a subclass in code. Instead, you can include a FileProvider in your app
* by specifying it entirely in XML. To specify the FileProvider component itself, add a
* <code><a href="{@docRoot}guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></code>
* element to your app manifest. Set the <code>android:name</code> attribute to
* <code>android.support.v4.content.FileProvider</code>. Set the <code>android:authorities</code>
* attribute to a URI authority based on a domain you control; for example, if you control the
* domain <code>mydomain.com</code> you should use the authority
* <code>com.mydomain.fileprovider</code>. Set the <code>android:exported</code> attribute to
* <code>false</code>; the FileProvider does not need to be public. Set the
* <a href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn"
* >android:grantUriPermissions</a> attribute to <code>true</code>, to allow you
* to grant temporary access to files. For example:
* <pre class="prettyprint">
*&lt;manifest&gt;
* ...
* &lt;application&gt;
* ...
* &lt;provider
* android:name="android.support.v4.content.FileProvider"
* android:authorities="com.mydomain.fileprovider"
* android:exported="false"
* android:grantUriPermissions="true"&gt;
* ...
* &lt;/provider&gt;
* ...
* &lt;/application&gt;
*&lt;/manifest&gt;</pre>
* <p>
* If you want to override any of the default behavior of FileProvider methods, extend
* the FileProvider class and use the fully-qualified class name in the <code>android:name</code>
* attribute of the <code>&lt;provider&gt;</code> element.
* <h3 id="SpecifyFiles">Specifying Available Files</h3>
* A FileProvider can only generate a content URI for files in directories that you specify
* beforehand. To specify a directory, specify the its storage area and path in XML, using child
* elements of the <code>&lt;paths&gt;</code> element.
* For example, the following <code>paths</code> element tells FileProvider that you intend to
* request content URIs for the <code>images/</code> subdirectory of your private file area.
* <pre class="prettyprint">
*&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt;
* &lt;files-path name="my_images" path="images/"/&gt;
* ...
*&lt;/paths&gt;
*</pre>
* <p>
* The <code>&lt;paths&gt;</code> element must contain one or more of the following child elements:
* </p>
* <dl>
* <dt>
* <pre class="prettyprint">
*&lt;files-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the <code>files/</code> subdirectory of your app's internal storage
* area. This subdirectory is the same as the value returned by {@link Context#getFilesDir()
* Context.getFilesDir()}.
* </dd>
* <dt>
* <pre>
*&lt;cache-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* <dt>
* <dd>
* Represents files in the cache subdirectory of your app's internal storage area. The root path
* of this subdirectory is the same as the value returned by {@link Context#getCacheDir()
* getCacheDir()}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of the external storage area. The root path of this subdirectory
* is the same as the value returned by
* {@link Environment#getExternalStorageDirectory() Environment.getExternalStorageDirectory()}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-files-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of your app's external storage area. The root path of this
* subdirectory is the same as the value returned by
* {@code Context#getExternalFilesDir(String) Context.getExternalFilesDir(null)}.
* </dd>
* <dt>
* <pre class="prettyprint">
*&lt;external-cache-path name="<i>name</i>" path="<i>path</i>" /&gt;
*</pre>
* </dt>
* <dd>
* Represents files in the root of your app's external cache area. The root path of this
* subdirectory is the same as the value returned by
* {@link Context#getExternalCacheDir() Context.getExternalCacheDir()}.
* </dd>
* </dl>
* <p>
* These child elements all use the same attributes:
* </p>
* <dl>
* <dt>
* <code>name="<i>name</i>"</code>
* </dt>
* <dd>
* A URI path segment. To enforce security, this value hides the name of the subdirectory
* you're sharing. The subdirectory name for this value is contained in the
* <code>path</code> attribute.
* </dd>
* <dt>
* <code>path="<i>path</i>"</code>
* </dt>
* <dd>
* The subdirectory you're sharing. While the <code>name</code> attribute is a URI path
* segment, the <code>path</code> value is an actual subdirectory name. Notice that the
* value refers to a <b>subdirectory</b>, not an individual file or files. You can't
* share a single file by its file name, nor can you specify a subset of files using
* wildcards.
* </dd>
* </dl>
* <p>
* You must specify a child element of <code>&lt;paths&gt;</code> for each directory that contains
* files for which you want content URIs. For example, these XML elements specify two directories:
* <pre class="prettyprint">
*&lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt;
* &lt;files-path name="my_images" path="images/"/&gt;
* &lt;files-path name="my_docs" path="docs/"/&gt;
*&lt;/paths&gt;
*</pre>
* <p>
* Put the <code>&lt;paths&gt;</code> element and its children in an XML file in your project.
* For example, you can add them to a new file called <code>res/xml/file_paths.xml</code>.
* To link this file to the FileProvider, add a
* <a href="{@docRoot}guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a> element
* as a child of the <code>&lt;provider&gt;</code> element that defines the FileProvider. Set the
* <code>&lt;meta-data&gt;</code> element's "android:name" attribute to
* <code>android.support.FILE_PROVIDER_PATHS</code>. Set the element's "android:resource" attribute
* to <code>&#64;xml/file_paths</code> (notice that you don't specify the <code>.xml</code>
* extension). For example:
* <pre class="prettyprint">
*&lt;provider
* android:name="android.support.v4.content.FileProvider"
* android:authorities="com.mydomain.fileprovider"
* android:exported="false"
* android:grantUriPermissions="true"&gt;
* &lt;meta-data
* android:name="android.support.FILE_PROVIDER_PATHS"
* android:resource="&#64;xml/file_paths" /&gt;
*&lt;/provider&gt;
*</pre>
* <h3 id="GetUri">Generating the Content URI for a File</h3>
* <p>
* To share a file with another app using a content URI, your app has to generate the content URI.
* To generate the content URI, create a new {@link File} for the file, then pass the {@link File}
* to {@link #getUriForFile(Context, String, File) getUriForFile()}. You can send the content URI
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()} to another app in an
* {@link android.content.Intent}. The client app that receives the content URI can open the file
* and access its contents by calling
* {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
* ContentResolver.openFileDescriptor} to get a {@link ParcelFileDescriptor}.
* <p>
* For example, suppose your app is offering files to other apps with a FileProvider that has the
* authority <code>com.mydomain.fileprovider</code>. To get a content URI for the file
* <code>default_image.jpg</code> in the <code>images/</code> subdirectory of your internal storage
* add the following code:
* <pre class="prettyprint">
*File imagePath = new File(Context.getFilesDir(), "images");
*File newFile = new File(imagePath, "default_image.jpg");
*Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);
*</pre>
* As a result of the previous snippet,
* {@link #getUriForFile(Context, String, File) getUriForFile()} returns the content URI
* <code>content://com.mydomain.fileprovider/my_images/default_image.jpg</code>.
* <h3 id="Permissions">Granting Temporary Permissions to a URI</h3>
* To grant an access permission to a content URI returned from
* {@link #getUriForFile(Context, String, File) getUriForFile()}, do one of the following:
* <ul>
* <li>
* Call the method
* {@link Context#grantUriPermission(String, Uri, int)
* Context.grantUriPermission(package, Uri, mode_flags)} for the <code>content://</code>
* {@link Uri}, using the desired mode flags. This grants temporary access permission for the
* content URI to the specified package, according to the value of the
* the <code>mode_flags</code> parameter, which you can set to
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION}, {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}
* or both. The permission remains in effect until you revoke it by calling
* {@link Context#revokeUriPermission(Uri, int) revokeUriPermission()} or until the device
* reboots.
* </li>
* <li>
* Put the content URI in an {@link Intent} by calling {@link Intent#setData(Uri) setData()}.
* </li>
* <li>
* Next, call the method {@link Intent#setFlags(int) Intent.setFlags()} with either
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} or
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION} or both.
* </li>
* <li>
* Finally, send the {@link Intent} to
* another app. Most often, you do this by calling
* {@link android.app.Activity#setResult(int, android.content.Intent) setResult()}.
* <p>
* Permissions granted in an {@link Intent} remain in effect while the stack of the receiving
* {@link android.app.Activity} is active. When the stack finishes, the permissions are
* automatically removed. Permissions granted to one {@link android.app.Activity} in a client
* app are automatically extended to other components of that app.
* </p>
* </li>
* </ul>
* <h3 id="ServeUri">Serving a Content URI to Another App</h3>
* <p>
* There are a variety of ways to serve the content URI for a file to a client app. One common way
* is for the client app to start your app by calling
* {@link android.app.Activity#startActivityForResult(Intent, int, Bundle) startActivityResult()},
* which sends an {@link Intent} to your app to start an {@link android.app.Activity} in your app.
* In response, your app can immediately return a content URI to the client app or present a user
* interface that allows the user to pick a file. In the latter case, once the user picks the file
* your app can return its content URI. In both cases, your app returns the content URI in an
* {@link Intent} sent via {@link android.app.Activity#setResult(int, Intent) setResult()}.
* </p>
* <p>
* You can also put the content URI in a {@link android.content.ClipData} object and then add the
* object to an {@link Intent} you send to a client app. To do this, call
* {@link Intent#setClipData(ClipData) Intent.setClipData()}. When you use this approach, you can
* add multiple {@link android.content.ClipData} objects to the {@link Intent}, each with its own
* content URI. When you call {@link Intent#setFlags(int) Intent.setFlags()} on the {@link Intent}
* to set temporary access permissions, the same permissions are applied to all of the content
* URIs.
* </p>
* <p class="note">
* <strong>Note:</strong> The {@link Intent#setClipData(ClipData) Intent.setClipData()} method is
* only available in platform version 16 (Android 4.1) and later. If you want to maintain
* compatibility with previous versions, you should send one content URI at a time in the
* {@link Intent}. Set the action to {@link Intent#ACTION_SEND} and put the URI in data by calling
* {@link Intent#setData setData()}.
* </p>
* <h3 id="">More Information</h3>
* <p>
* To learn more about FileProvider, see the Android training class
* <a href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files Securely with URIs</a>.
* </p>
*/
public class FileProvider extends ContentProvider {
private static final String[] COLUMNS = {
MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.SIZE,
MediaStore.MediaColumns.DATA
};
private static final String
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";
private static final String TAG_CACHE_PATH = "cache-path";
private static final String TAG_EXTERNAL = "external-path";
private static final String TAG_EXTERNAL_FILES = "external-files-path";
private static final String TAG_EXTERNAL_CACHE = "external-cache-path";
private static final String ATTR_NAME = "name";
private static final String ATTR_PATH = "path";
private static final File DEVICE_ROOT = new File("/");
// @GuardedBy("sCache")
private static HashMap<String, PathStrategy> sCache = new HashMap<String, PathStrategy>();
private PathStrategy mStrategy;
/**
* The default FileProvider implementation does not need to be initialized. If you want to
* override this method, you must provide your own subclass of FileProvider.
*/
@Override
public boolean onCreate() {
return true;
}
/**
* After the FileProvider is instantiated, this method is called to provide the system with
* information about the provider.
*
* @param context A {@link Context} for the current component.
* @param info A {@link ProviderInfo} for the new provider.
*/
@Override
public void attachInfo(Context context, ProviderInfo info) {
super.attachInfo(context, info);
// Sanity check our security
if (info.exported) {
throw new SecurityException("Provider must not be exported");
}
if (!info.grantUriPermissions) {
throw new SecurityException("Provider must grant uri permissions");
}
mStrategy = getPathStrategy(context, info.authority);
}
/**
* Return a content URI for a given {@link File}. Specific temporary
* permissions for the content URI can be set with
* {@link Context#grantUriPermission(String, Uri, int)}, or added
* to an {@link Intent} by calling {@link Intent#setData(Uri) setData()} and then
* {@link Intent#setFlags(int) setFlags()}; in both cases, the applicable flags are
* {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} and
* {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}. A FileProvider can only return a
* <code>content</code> {@link Uri} for file paths defined in their <code>&lt;paths&gt;</code>
* meta-data element. See the Class Overview for more information.
*
* @param context A {@link Context} for the current component.
* @param authority The authority of a {@link FileProvider} defined in a
* {@code <provider>} element in your app's manifest.
* @param file A {@link File} pointing to the filename for which you want a
* <code>content</code> {@link Uri}.
* @return A content URI for the file.
* @throws IllegalArgumentException When the given {@link File} is outside
* the paths supported by the provider.
*/
public static Uri getUriForFile(Context context, String authority, File file) {
final PathStrategy strategy = getPathStrategy(context, authority);
return strategy.getUriForFile(file);
}
/**
* Use a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()} to get information about a file
* managed by the FileProvider.
* FileProvider reports the column names defined in {@link android.provider.MediaStore.MediaColumns}:
* <ul>
* <li>{@link android.provider.MediaStore.MediaColumns#DISPLAY_NAME}</li>
* <li>{@link android.provider.MediaStore.MediaColumns#SIZE}</li>
* <li>{@link android.provider.MediaStore.MediaColumns#DATA}</li>
* </ul>
* For more information, see
* {@link ContentProvider#query(Uri, String[], String, String[], String)
* ContentProvider.query()}.
*
* @param uri A content URI returned by {@link #getUriForFile}.
* @param projection The list of columns to put into the {@link Cursor}. If null all columns are
* included.
* @param selection Selection criteria to apply. If null then all data that matches the content
* URI is returned.
* @param selectionArgs An array of {@link java.lang.String}, containing arguments to bind to
* the <i>selection</i> parameter. The <i>query</i> method scans <i>selection</i> from left to
* right and iterates through <i>selectionArgs</i>, replacing the current "?" character in
* <i>selection</i> with the value at the current position in <i>selectionArgs</i>. The
* values are bound to <i>selection</i> as {@link java.lang.String} values.
* @param sortOrder A {@link java.lang.String} containing the column name(s) on which to sort
* the resulting {@link Cursor}.
* @return A {@link Cursor} containing the results of the query.
*
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
if (projection == null) {
projection = COLUMNS;
}
String[] cols = new String[projection.length];
Object[] values = new Object[projection.length];
int i = 0;
for (String col : projection) {
if (MediaStore.MediaColumns.DISPLAY_NAME.equals(col)) {
cols[i] = MediaStore.MediaColumns.DISPLAY_NAME;
values[i++] = file.getName();
} else if (MediaStore.MediaColumns.SIZE.equals(col)) {
cols[i] = MediaStore.MediaColumns.SIZE;
values[i++] = file.length();
} else if (MediaStore.MediaColumns.DATA.equals(col)) {
cols[i] = MediaStore.MediaColumns.DATA;
values[i++] = file.getPath();
}
}
cols = copyOf(cols, i);
values = copyOf(values, i);
final MatrixCursor cursor = new MatrixCursor(cols, 1);
cursor.addRow(values);
return cursor;
}
/**
* Returns the MIME type of a content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
*
* @param uri A content URI returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @return If the associated file has an extension, the MIME type associated with that
* extension; otherwise <code>application/octet-stream</code>.
*/
@Override
public String getType(Uri uri) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
final int lastDot = file.getName().lastIndexOf('.');
if (lastDot >= 0) {
final String extension = file.getName().substring(lastDot + 1);
final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (mime != null) {
return mime;
}
}
return "application/octet-stream";
}
/**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality.
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException("No external inserts");
}
/**
* By default, this method throws an {@link java.lang.UnsupportedOperationException}. You must
* subclass FileProvider if you want to provide different functionality.
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException("No external updates");
}
/**
* Deletes the file associated with the specified content URI, as
* returned by {@link #getUriForFile(Context, String, File) getUriForFile()}. Notice that this
* method does <b>not</b> throw an {@link java.io.IOException}; you must check its return value.
*
* @param uri A content URI for a file, as returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @param selection Ignored. Set to {@code null}.
* @param selectionArgs Ignored. Set to {@code null}.
* @return 1 if the delete succeeds; otherwise, 0.
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
return file.delete() ? 1 : 0;
}
/**
* By default, FileProvider automatically returns the
* {@link ParcelFileDescriptor} for a file associated with a <code>content://</code>
* {@link Uri}. To get the {@link ParcelFileDescriptor}, call
* {@link android.content.ContentResolver#openFileDescriptor(Uri, String)
* ContentResolver.openFileDescriptor}.
*
* To override this method, you must provide your own subclass of FileProvider.
*
* @param uri A content URI associated with a file, as returned by
* {@link #getUriForFile(Context, String, File) getUriForFile()}.
* @param mode Access mode for the file. May be "r" for read-only access, "rw" for read and
* write access, or "rwt" for read and write access that truncates any existing file.
* @return A new {@link ParcelFileDescriptor} with which you can access the file.
*/
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
// ContentProvider has already checked granted permissions
final File file = mStrategy.getFileForUri(uri);
final int fileMode = modeToMode(mode);
return ParcelFileDescriptor.open(file, fileMode);
}
/**
* Return {@link PathStrategy} for given authority, either by parsing or
* returning from cache.
*/
private static PathStrategy getPathStrategy(Context context, String authority) {
PathStrategy strat;
synchronized (sCache) {
strat = sCache.get(authority);
if (strat == null) {
try {
strat = parsePathStrategy(context, authority);
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
} catch (XmlPullParserException e) {
throw new IllegalArgumentException(
"Failed to parse " + META_DATA_FILE_PROVIDER_PATHS + " meta-data", e);
}
sCache.put(authority, strat);
}
}
return strat;
}
/**
* Parse and return {@link PathStrategy} for given authority as defined in
* {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
*
* @see #getPathStrategy(Context, String)
*/
private static PathStrategy parsePathStrategy(Context context, String authority)
throws IOException, XmlPullParserException {
final SimplePathStrategy strat = new SimplePathStrategy(authority);
final ProviderInfo info = context.getPackageManager()
.resolveContentProvider(authority, PackageManager.GET_META_DATA);
final XmlResourceParser in = info.loadXmlMetaData(
context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
if (in == null) {
throw new IllegalArgumentException(
"Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
}
int type;
while ((type = in.next()) != END_DOCUMENT) {
if (type == START_TAG) {
final String tag = in.getName();
final String name = in.getAttributeValue(null, ATTR_NAME);
String path = in.getAttributeValue(null, ATTR_PATH);
File target = null;
if (TAG_ROOT_PATH.equals(tag)) {
target = DEVICE_ROOT;
} else if (TAG_FILES_PATH.equals(tag)) {
target = context.getFilesDir();
} else if (TAG_CACHE_PATH.equals(tag)) {
target = context.getCacheDir();
} else if (TAG_EXTERNAL.equals(tag)) {
target = Environment.getExternalStorageDirectory();
} else if (TAG_EXTERNAL_FILES.equals(tag)) {
File[] externalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
if (externalFilesDirs.length > 0) {
target = externalFilesDirs[0];
}
} else if (TAG_EXTERNAL_CACHE.equals(tag)) {
File[] externalCacheDirs = ContextCompat.getExternalCacheDirs(context);
if (externalCacheDirs.length > 0) {
target = externalCacheDirs[0];
}
}
if (target != null) {
strat.addRoot(name, buildPath(target, path));
}
}
}
return strat;
}
/**
* Strategy for mapping between {@link File} and {@link Uri}.
* <p>
* Strategies must be symmetric so that mapping a {@link File} to a
* {@link Uri} and then back to a {@link File} points at the original
* target.
* <p>
* Strategies must remain consistent across app launches, and not rely on
* dynamic state. This ensures that any generated {@link Uri} can still be
* resolved if your process is killed and later restarted.
*
* @see SimplePathStrategy
*/
interface PathStrategy {
/**
* Return a {@link Uri} that represents the given {@link File}.
*/
public Uri getUriForFile(File file);
/**
* Return a {@link File} that represents the given {@link Uri}.
*/
public File getFileForUri(Uri uri);
}
/**
* Strategy that provides access to files living under a narrow whitelist of
* filesystem roots. It will throw {@link SecurityException} if callers try
* accessing files outside the configured roots.
* <p>
* For example, if configured with
* {@code addRoot("myfiles", context.getFilesDir())}, then
* {@code context.getFileStreamPath("foo.txt")} would map to
* {@code content://myauthority/myfiles/foo.txt}.
*/
static class SimplePathStrategy implements PathStrategy {
private final String mAuthority;
private final HashMap<String, File> mRoots = new HashMap<String, File>();
public SimplePathStrategy(String authority) {
mAuthority = authority;
}
/**
* Add a mapping from a name to a filesystem root. The provider only offers
* access to files that live under configured roots.
*/
public void addRoot(String name, File root) {
if (TextUtils.isEmpty(name)) {
throw new IllegalArgumentException("Name must not be empty");
}
try {
// Resolve to canonical path to keep path checking fast
root = root.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException(
"Failed to resolve canonical path for " + root, e);
}
mRoots.put(name, root);
}
@Override
public Uri getUriForFile(File file) {
String path;
try {
path = file.getCanonicalPath();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
// Find the most-specific root path
Map.Entry<String, File> mostSpecific = null;
for (Map.Entry<String, File> root : mRoots.entrySet()) {
final String rootPath = root.getValue().getPath();
if (path.startsWith(rootPath) && (mostSpecific == null
|| rootPath.length() > mostSpecific.getValue().getPath().length())) {
mostSpecific = root;
}
}
if (mostSpecific == null) {
throw new IllegalArgumentException(
"Failed to find configured root that contains " + path);
}
// Start at first char of path under root
final String rootPath = mostSpecific.getValue().getPath();
if (rootPath.endsWith("/")) {
path = path.substring(rootPath.length());
} else {
path = path.substring(rootPath.length() + 1);
}
// Encode the tag and path separately
path = Uri.encode(mostSpecific.getKey()) + '/' + Uri.encode(path, "/");
return new Uri.Builder().scheme("content")
.authority(mAuthority).encodedPath(path).build();
}
@Override
public File getFileForUri(Uri uri) {
String path = uri.getEncodedPath();
final int splitIndex = path.indexOf('/', 1);
final String tag = Uri.decode(path.substring(1, splitIndex));
path = Uri.decode(path.substring(splitIndex + 1));
final File root = mRoots.get(tag);
if (root == null) {
throw new IllegalArgumentException("Unable to find configured root for " + uri);
}
File file = new File(root, path);
try {
file = file.getCanonicalFile();
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve canonical path for " + file);
}
if (!file.getPath().startsWith(root.getPath())) {
throw new SecurityException("Resolved path jumped beyond configured root");
}
return file;
}
}
/**
* Copied from ContentResolver.java
*/
private static int modeToMode(String mode) {
int modeBits;
if ("r".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_ONLY;
} else if ("w".equals(mode) || "wt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else if ("wa".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_APPEND;
} else if ("rw".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE;
} else if ("rwt".equals(mode)) {
modeBits = ParcelFileDescriptor.MODE_READ_WRITE
| ParcelFileDescriptor.MODE_CREATE
| ParcelFileDescriptor.MODE_TRUNCATE;
} else {
throw new IllegalArgumentException("Invalid mode: " + mode);
}
return modeBits;
}
private static File buildPath(File base, String... segments) {
File cur = base;
for (String segment : segments) {
if (segment != null) {
cur = new File(cur, segment);
}
}
return cur;
}
private static String[] copyOf(String[] original, int newLength) {
final String[] result = new String[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
private static Object[] copyOf(Object[] original, int newLength) {
final Object[] result = new Object[newLength];
System.arraycopy(original, 0, result, 0, newLength);
return result;
}
}
@@ -0,0 +1,90 @@
/*
* Copyright 2018 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.content;
/*
* Created by Hippo on 2018/3/27.
*/
import android.app.Activity;
import android.os.Bundle;
import com.hippo.scene.SceneApplication;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public abstract class RecordingApplication extends SceneApplication {
private List<WeakReference<Activity>> list = new LinkedList<>();
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
list.add(new java.lang.ref.WeakReference<>(activity));
}
@Override
public void onActivityDestroyed(Activity activity) {
Iterator<WeakReference<Activity>> iterator = list.iterator();
while (iterator.hasNext()) {
WeakReference<Activity> reference = iterator.next();
Activity a = reference.get();
// Remove current activity and null
if (a == null || a == activity) {
iterator.remove();
}
}
}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
});
}
public void recreate() {
// Copy list
ArrayList<Activity> listCopy = new ArrayList<>(list.size());
for (WeakReference<Activity> reference: list) {
Activity activity = reference.get();
if (activity == null) continue;
listCopy.add(activity);
}
// Finish all activities
for (int i = listCopy.size() - 1; i >= 0; --i) {
listCopy.get(i).recreate();
}
}
}
@@ -0,0 +1,130 @@
/*
* Copyright 2017 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.database;
/*
* Created by Hippo on 2017/9/3.
*/
import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MSQLiteBuilder {
public static final String COLUMN_ID = "_id";
private static final Map<Class, String> JAVA_TYPE_TO_SQLITE_TYPE = new HashMap<>();
static {
JAVA_TYPE_TO_SQLITE_TYPE.put(boolean.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(byte.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(short.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(int.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(long.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(float.class, "REAL NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(double.class, "REAL NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(String.class, "TEXT");
}
private static String javaTypeToSQLiteType(Class clazz) {
String type = JAVA_TYPE_TO_SQLITE_TYPE.get(clazz);
if (type == null) {
throw new IllegalStateException("Unknown type: " + clazz);
}
return type;
}
private int version = 0;
private List<String> statements;
private SparseArray<List<String>> statementsMap = new SparseArray<>();
/**
* Bump database version.
*/
public MSQLiteBuilder version(int version) {
if (version <= this.version) {
throw new IllegalStateException("New version must be bigger than current version. "
+ "current version: " + this.version + ", new version: " + version + ".");
}
this.version = version;
this.statements = new ArrayList<>();
this.statementsMap.put(version, this.statements);
return this;
}
/**
* Creates a table with int {@link #COLUMN_ID} primary key.
*/
public MSQLiteBuilder createTable(String table) {
return createTable(table, COLUMN_ID, int.class);
}
/**
* Creates a table.
*/
public MSQLiteBuilder createTable(String table, String column, Class clazz) {
return statement("CREATE TABLE " + table + " (" + column + " " + javaTypeToSQLiteType(clazz) + " PRIMARY KEY);");
}
/**
* Drops a table.
*/
public MSQLiteBuilder dropTable(String table) {
return statement("DROP TABLE " + table + ";");
}
/**
* Inserts a column to the table.
*/
public MSQLiteBuilder insertColumn(String table, String column, Class clazz) {
return statement("ALTER TABLE " + table + " ADD COLUMN " + column + " " + javaTypeToSQLiteType(clazz) + ";");
}
/**
* Add a statement.
*/
public MSQLiteBuilder statement(String statement) {
if (version == 0 || statements == null) {
throw new IllegalStateException("Call version() first!");
}
statements.add(statement);
return this;
}
/**
* Build a SQLiteOpenHelper from it.
*/
public SQLiteOpenHelper build(Context context, String name, int version) {
return new MSQLiteOpenHelper(context, name, version, this);
}
List<String> getStatements(int oldVersion, int newVersion) {
List<String> result = new ArrayList<>();
for (int i = oldVersion + 1; i <= newVersion; ++i) {
List<String> list = statementsMap.get(i);
if (list != null) {
result.addAll(list);
}
}
return result;
}
}
@@ -0,0 +1,56 @@
/*
* Copyright 2017 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.database;
/*
* Created by Hippo on 2017/9/4.
*/
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.hippo.util.SqlUtils;
class MSQLiteOpenHelper extends SQLiteOpenHelper {
private final int version;
private final MSQLiteBuilder builder;
public MSQLiteOpenHelper(Context context, String name, int version, MSQLiteBuilder builder) {
super(context, name, null, version);
this.version = version;
this.builder = builder;
}
@Override
public void onCreate(SQLiteDatabase db) {
onUpgrade(db, 0, version);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (String command : builder.getStatements(oldVersion, newVersion)) {
db.execSQL(command);
}
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
SqlUtils.dropAllTable(db);
onCreate(db);
}
}
@@ -46,13 +46,13 @@ public class AddDeleteDrawable extends Drawable {
/**
* @param context used to get the configuration for the drawable from
*/
public AddDeleteDrawable(Context context) {
public AddDeleteDrawable(Context context, int color) {
Resources resources = context.getResources();
mSize = resources.getDimensionPixelSize(R.dimen.add_size);
float barThickness = Math.round(resources.getDimension(R.dimen.add_thickness));
mPaint.setColor(resources.getColor(R.color.primary_drawable_light));
mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.MITER);
mPaint.setStrokeCap(Paint.Cap.BUTT);
@@ -59,6 +59,7 @@ public class BatteryDrawable extends Drawable {
}
@Override
@SuppressWarnings("SuspiciousNameCombination")
protected void onBoundsChange(Rect bounds) {
int width = bounds.width();
int height = bounds.height();
@@ -89,8 +90,9 @@ public class BatteryDrawable extends Drawable {
*/
@Override
public void draw(Canvas canvas) {
if (mElect == -1)
if (mElect == -1) {
return;
}
mElectRect.right = MathUtils.lerp(mStart, mStop, mElect / 100.0f);
@@ -152,21 +154,22 @@ public class BatteryDrawable extends Drawable {
}
private void updatePaint(boolean warn) {
if (warn)
if (warn) {
mPaint.setColor(mWarningColor);
else
} else {
mPaint.setColor(mColor);
}
invalidateSelf();
}
@Override
public void setAlpha(int alpha) {
// Empty
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter cf) {
// Empty
mPaint.setColorFilter(cf);
}
@Override
@@ -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;
@@ -0,0 +1,180 @@
/*
* Copyright 2018 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.drawable;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.core.graphics.drawable.DrawableCompat;
public class DrawableWrapper extends Drawable implements Drawable.Callback {
private Drawable mDrawable;
public DrawableWrapper(Drawable drawable) {
this.setWrappedDrawable(drawable);
}
public void draw(@NonNull Canvas canvas) {
this.mDrawable.draw(canvas);
}
protected void onBoundsChange(Rect bounds) {
this.mDrawable.setBounds(bounds);
}
public void setChangingConfigurations(int configs) {
this.mDrawable.setChangingConfigurations(configs);
}
public int getChangingConfigurations() {
return this.mDrawable.getChangingConfigurations();
}
public void setDither(boolean dither) {
this.mDrawable.setDither(dither);
}
public void setFilterBitmap(boolean filter) {
this.mDrawable.setFilterBitmap(filter);
}
public void setAlpha(int alpha) {
this.mDrawable.setAlpha(alpha);
}
public void setColorFilter(ColorFilter cf) {
this.mDrawable.setColorFilter(cf);
}
public boolean isStateful() {
return this.mDrawable.isStateful();
}
public boolean setState(@NonNull int[] stateSet) {
return this.mDrawable.setState(stateSet);
}
@NonNull
public int[] getState() {
return this.mDrawable.getState();
}
public void jumpToCurrentState() {
this.mDrawable.jumpToCurrentState();
}
@NonNull
public Drawable getCurrent() {
return this.mDrawable.getCurrent();
}
public boolean setVisible(boolean visible, boolean restart) {
return super.setVisible(visible, restart) || this.mDrawable.setVisible(visible, restart);
}
public int getOpacity() {
return this.mDrawable.getOpacity();
}
public Region getTransparentRegion() {
return this.mDrawable.getTransparentRegion();
}
public int getIntrinsicWidth() {
return this.mDrawable.getIntrinsicWidth();
}
public int getIntrinsicHeight() {
return this.mDrawable.getIntrinsicHeight();
}
public int getMinimumWidth() {
return this.mDrawable.getMinimumWidth();
}
public int getMinimumHeight() {
return this.mDrawable.getMinimumHeight();
}
public boolean getPadding(@NonNull Rect padding) {
return this.mDrawable.getPadding(padding);
}
public void invalidateDrawable(@NonNull Drawable who) {
this.invalidateSelf();
}
public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) {
this.scheduleSelf(what, when);
}
public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
this.unscheduleSelf(what);
}
protected boolean onLevelChange(int level) {
return this.mDrawable.setLevel(level);
}
public void setAutoMirrored(boolean mirrored) {
DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);
}
public boolean isAutoMirrored() {
return DrawableCompat.isAutoMirrored(this.mDrawable);
}
public void setTint(int tint) {
DrawableCompat.setTint(this.mDrawable, tint);
}
public void setTintList(ColorStateList tint) {
DrawableCompat.setTintList(this.mDrawable, tint);
}
public void setTintMode(@NonNull PorterDuff.Mode tintMode) {
DrawableCompat.setTintMode(this.mDrawable, tintMode);
}
public void setHotspot(float x, float y) {
DrawableCompat.setHotspot(this.mDrawable, x, y);
}
public void setHotspotBounds(int left, int top, int right, int bottom) {
DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);
}
public Drawable getWrappedDrawable() {
return this.mDrawable;
}
public void setWrappedDrawable(Drawable drawable) {
if (this.mDrawable != null) {
this.mDrawable.setCallback(null);
}
this.mDrawable = drawable;
if (drawable != null) {
drawable.setCallback(this);
}
}
}
@@ -27,7 +27,7 @@ import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import androidx.annotation.ColorInt;
import com.hippo.ehviewer.R;
import com.hippo.yorozuya.MathUtils;
@@ -38,7 +38,7 @@ public class DrawerArrowDrawable extends Drawable {
private final Paint mPaint = new Paint();
// The angle in degress that the arrow head is inclined at.
// The angle in degrees that the arrow head is inclined at.
private static final float ARROW_HEAD_ANGLE = (float) Math.toRadians(45);
private final float mBarThickness;
// The length of top and bottom bars when they merge into an arrow
@@ -61,16 +61,16 @@ public class DrawerArrowDrawable extends Drawable {
// The interpolated version of the original progress
private float mProgress;
// the amount that overlaps w/ bar size when rotation is max
private float mMaxCutForBarSize;
private final float mMaxCutForBarSize;
/**
* @param context used to get the configuration for the drawable from
*/
public DrawerArrowDrawable(Context context) {
public DrawerArrowDrawable(Context context, int color) {
Resources resources = context.getResources();
mPaint.setAntiAlias(true);
mPaint.setColor(resources.getColor(R.color.primary_drawable_light));
mPaint.setColor(color);
mSize = resources.getDimensionPixelSize(R.dimen.dad_drawable_size);
// round this because having this floating may cause bad measurements
mBarSize = Math.round(resources.getDimension(R.dimen.dad_bar_size));
@@ -144,6 +144,11 @@ public class DrawerArrowDrawable extends Drawable {
canvas.restore();
}
public void setColor(@ColorInt int color) {
mPaint.setColor(color);
invalidateSelf();
}
@Override
public void setAlpha(int i) {
mPaint.setAlpha(i);
@@ -20,10 +20,12 @@ import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.v7.graphics.drawable.DrawableWrapper;
import com.hippo.yorozuya.MathUtils;
/**
* Show a part of the original drawable
*/
public class PreciselyClipDrawable extends DrawableWrapper {
private final boolean mClip;
@@ -16,26 +16,58 @@
package com.hippo.drawable;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.widget.TextView;
import android.util.Log;
import androidx.annotation.NonNull;
import com.hippo.conaco.Conaco;
import com.hippo.conaco.ConacoTask;
import com.hippo.conaco.Unikery;
import com.hippo.conaco.ValueHolder;
import com.hippo.image.ImageBitmap;
import com.hippo.image.ImageDrawable;
import com.hippo.image.RecycledException;
import com.hippo.widget.ObservedTextView;
public class UnikeryDrawable extends WrapDrawable implements Unikery<Bitmap> {
public class UnikeryDrawable extends WrapDrawable implements Unikery<ImageBitmap>,
ObservedTextView.OnWindowAttachListener {
private static final String TAG = UnikeryDrawable.class.getSimpleName();
private int mTaskId = Unikery.INVALID_ID;
private final TextView mTextView;
private final ObservedTextView mTextView;
private final Conaco<ImageBitmap> mConaco;
private String mUrl;
private ValueHolder<Bitmap> mHolder;
public UnikeryDrawable(TextView textView) {
public UnikeryDrawable(ObservedTextView textView, Conaco<ImageBitmap> conaco) {
mTextView = textView;
mTextView.setOnWindowAttachListener(this);
mConaco = conaco;
}
@Override
public void onAttachedToWindow() {
load(mUrl);
}
@Override
public void onDetachedFromWindow() {
mConaco.cancel(this);
clearDrawable();
}
public void load(String url) {
if (url != null) {
mUrl = url;
mConaco.load(new ConacoTask.Builder<ImageBitmap>().setUnikery(this).setUrl(url).setKey(url));
}
}
private void clearDrawable() {
Drawable drawable = getDrawable();
if (drawable instanceof ImageDrawable) {
((ImageDrawable) drawable).recycle();
}
setDrawable(null);
}
@Override
@@ -54,9 +86,7 @@ public class UnikeryDrawable extends WrapDrawable implements Unikery<Bitmap> {
updateBounds();
if (drawable != null) {
// mTextView.requestLayout() not work!
CharSequence cs = mTextView.getText();
mTextView.setText(cs);
invalidateSelf();
}
}
@@ -71,49 +101,41 @@ public class UnikeryDrawable extends WrapDrawable implements Unikery<Bitmap> {
}
@Override
public void onMiss(Conaco.Source source) {
public void invalidateSelf() {
CharSequence cs = mTextView.getText();
mTextView.setText(cs);
}
@Override
public void onRequest() {
}
public void onMiss(int source) {}
@Override
public void onProgress(long singleReceivedSize, long receivedSize, long totalSize) {
}
public void onRequest() {}
private void removeDrawableAndHolder() {
// Remove drawable
setDrawable(null);
@Override
public void onProgress(long singleReceivedSize, long receivedSize, long totalSize) {}
// Remove holder
if (mHolder != null) {
mHolder.release(this);
mHolder = null;
@Override
public void onWait() {}
@Override
public boolean onGetValue(@NonNull ImageBitmap value, int source) {
ImageDrawable drawable;
try {
drawable = new ImageDrawable(value);
} catch (RecycledException e) {
Log.d(TAG, "The ImageBitmap is recycled", e);
return false;
}
}
@Override
public boolean onGetObject(@NonNull ValueHolder<Bitmap> holder, Conaco.Source source) {
holder.obtain(this);
removeDrawableAndHolder();
mHolder = holder;
Drawable drawable = new BitmapDrawable(mTextView.getResources(), holder.getValue());
clearDrawable();
setDrawable(drawable);
drawable.start();
return true;
}
@Override
public void onSetDrawable(Drawable drawable) {
removeDrawableAndHolder();
setDrawable(drawable);
}
@Override
public void onFailure() {
// Empty
@@ -17,15 +17,47 @@
package com.hippo.ehviewer;
import android.content.Context;
import com.google.analytics.tracking.android.EasyTracker;
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() {}
public static void start(Context context) {
EasyTracker.getInstance(context).set("&uid", Settings.getUserID());
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() {
return analytics != null && Settings.getEnableAnalytics();
}
public static void onSceneView(SceneFragment scene) {
if (isEnabled()) {
Bundle bundle = new Bundle();
bundle.putString("scene_simple_class", scene.getClass().getSimpleName());
bundle.putString("scene_class", scene.getClass().getName());
analytics.logEvent("scene_view", bundle);
}
}
}
@@ -18,11 +18,15 @@ 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;
import java.io.OutputStream;
public class AppConfig {
@@ -31,10 +35,10 @@ public class AppConfig {
private static final String DOWNLOAD = "download";
private static final String TEMP = "temp";
private static final String IMAGE = "image";
private static final String CRASH = "crash";
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;
@@ -89,11 +93,6 @@ public class AppConfig {
return getDirInExternalAppDir(IMAGE);
}
@Nullable
public static File getExternalCrashDir() {
return getDirInExternalAppDir(CRASH);
}
@Nullable
public static File getExternalParseErrorDir() {
return getDirInExternalAppDir(PARSE_ERROR);
@@ -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);
@@ -129,4 +133,46 @@ public class AppConfig {
public static File createTempFile() {
return FileUtils.createTempFile(getTempDir(), null);
}
public static void saveParseErrorBody(ParseException e) {
File dir = getExternalParseErrorDir();
if (null == dir) {
return;
}
File file = new File(dir, ReadableTime.getFilenamableTime(System.currentTimeMillis()) + ".txt");
OutputStream os = null;
try {
os = new FileOutputStream(file);
String message = e.getMessage();
String body = e.getBody();
if (null != message) {
os.write(message.getBytes("utf-8"));
os.write('\n');
}
if (null != body) {
os.write(body.getBytes("utf-8"));
}
os.flush();
} catch (IOException e1) {
// Ignore
} finally {
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;
}
}
}
@@ -1,60 +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;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.conaco.ValueHelper;
import com.hippo.conaco.ValueHolder;
import com.hippo.yorozuya.io.InputStreamPipe;
import java.io.IOException;
public class BitmapHelper implements ValueHelper<Bitmap> {
@Nullable
@Override
public Bitmap decode(@NonNull InputStreamPipe isPipe) {
try {
isPipe.obtain();
return BitmapFactory.decodeStream(isPipe.open());
} catch (OutOfMemoryError e) {
return null;
} catch (IOException e) {
return null;
} finally {
isPipe.close();
isPipe.release();
}
}
@Override
public int sizeOf(@NonNull String key, @NonNull Bitmap value) {
return value.getByteCount();
}
@Override
public void onRemove(@NonNull String key, @NonNull ValueHolder<Bitmap> oldValue) {}
@Override
public boolean useMemoryCache(@NonNull String key, ValueHolder<Bitmap> holder) {
return true;
}
}
+114 -152
View File
@@ -1,5 +1,5 @@
/*
* Copyright 2016 Hippo Seven
* 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.
@@ -21,174 +21,136 @@ import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
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.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
public class Crash {
public final class Crash {
private Crash() {}
@NonNull
private static String avoidNull(String str) {
return null != str ? str : "null";
}
@NonNull
private static String avoidNull(String str) {
return null != str ? str : "null";
}
@SuppressWarnings("deprecation")
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) {
topSceneClazzName = ((StageActivity) topActivity).getTopSceneClazzName();
}
}
} 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");
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");
}
public 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();
// 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;
}
public static void saveCrashInfo2File(Context context, Throwable ex) {
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);
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(ex, fw);
fw.write("\r\n");
fw.flush();
Settings.putCrashFilename(fileName);
} catch (Exception e) {
file.delete();
} finally {
IOUtils.closeQuietly(fw);
}
}
public static boolean hasCrashFile() {
String filename = Settings.getCrashFilename();
if (filename == null) {
return false;
}
File dir = AppConfig.getExternalCrashDir();
if (dir == null) {
return false;
}
return new File(dir, filename).isFile();
}
public static String getCrashContent() {
String filename = Settings.getCrashFilename();
if (filename == null) {
return null;
}
File dir = AppConfig.getExternalCrashDir();
if (dir == null) {
return null;
}
File file = new File(dir, filename);
InputStream is = null;
try {
is = new FileInputStream(file);
return IOUtils.readString(is, "UTF-8");
} catch (IOException e) {
return null;
} finally {
IOUtils.closeQuietly(is);
}
}
public static void resetCrashFile() {
Settings.putCrashFilename(null);
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);
}
}
}
@@ -16,81 +16,114 @@
package com.hippo.ehviewer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
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;
import com.hippo.ehviewer.client.EhClient;
import com.hippo.ehviewer.client.EhCookieStore;
import com.hippo.ehviewer.client.EhDns;
import com.hippo.ehviewer.client.EhEngine;
import com.hippo.ehviewer.client.data.GalleryDetail;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.ehviewer.spider.SpiderDen;
import com.hippo.ehviewer.ui.CommonOperations;
import com.hippo.image.Image;
import com.hippo.image.ImageBitmap;
import com.hippo.network.StatusCodeException;
import com.hippo.okhttp.CookieDB;
import com.hippo.scene.SceneApplication;
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;
import com.hippo.yorozuya.OSUtils;
import com.hippo.yorozuya.SimpleHandler;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
public class EhApplication extends SceneApplication implements Thread.UncaughtExceptionHandler {
public class EhApplication extends RecordingApplication {
private static final String TAG = EhApplication.class.getSimpleName();
private static final String KEY_GLOBAL_STUFF_NEXT_ID = "global_stuff_next_id";
public static final boolean BETA = false;
private static final boolean DEBUG_CONACO = false;
private static final boolean DEBUG_NATIVE_MEMORY = false;
private static final boolean DEBUG_PRINT_NATIVE_MEMORY = false;
private static final boolean DEBUG_PRINT_IMAGE_COUNT = false;
private static final long DEBUG_PRINT_INTERVAL = 3000L;
private Thread.UncaughtExceptionHandler mDefaultHandler;
private static EhApplication instance;
private final IntIdGenerator mIdGenerator = new IntIdGenerator();
private final WeakHashMap<Integer, Object> mGlobalStuffMap = new WeakHashMap<>();
private final HashMap<Integer, Object> mGlobalStuffMap = new HashMap<>();
private EhCookieStore mEhCookieStore;
private EhClient mEhClient;
private EhProxySelector mEhProxySelector;
private OkHttpClient mOkHttpClient;
private BitmapHelper mBitmapHelper;
private Conaco<Bitmap> mConaco;
private ImageBitmapHelper mImageBitmapHelper;
private Conaco<ImageBitmap> mConaco;
private LruCache<Long, GalleryDetail> mGalleryDetailCache;
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() {
// Prepare to catch crash
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
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);
CookieDB.initialize(this);
StatusCodeException.initialize(this);
Settings.initialize(this);
ReadableTime.initialize(this);
@@ -100,6 +133,8 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
EhDB.initialize(this);
EhEngine.initialize();
BitmapUtils.initialize(this);
Image.initialize(this);
A7Zip.loadLibrary(A7ZipExtractLite.LIBRARY, libname -> ReLinker.loadLibrary(EhApplication.this, libname));
if (EhDB.needMerge()) {
EhDB.mergeOldDB(this);
@@ -109,8 +144,34 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
Analytics.start(this);
}
CommonOperations.ensureNoMediaFile(Settings.getDownloadLocation());
clearTempDir();
// Do io tasks in new thread
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
// Check no media file
try {
UniFile downloadLocation = Settings.getDownloadLocation();
if (Settings.getMediaScan()) {
CommonOperations.removeNoMediaFile(downloadLocation);
} else {
CommonOperations.ensureNoMediaFile(downloadLocation);
}
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
}
// Clear temp files
try {
clearTempDir();
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
}
return null;
}
}.executeOnExecutor(IoThreadPoolExecutor.getInstance());
// Check app update
update();
// Update version code
@@ -121,9 +182,13 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
// Ignore
}
if (DEBUG_NATIVE_MEMORY) {
debugNativeMemory();
mIdGenerator.setNextId(Settings.getInt(KEY_GLOBAL_STUFF_NEXT_ID, 0));
if (DEBUG_PRINT_NATIVE_MEMORY || DEBUG_PRINT_IMAGE_COUNT) {
debugPrint();
}
initialized = true;
}
private void clearTempDir() {
@@ -135,6 +200,9 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
if (null != dir) {
FileUtils.deleteContent(dir);
}
// Add .nomedia to external temp dir
CommonOperations.ensureNoMediaFile(UniFile.fromFile(AppConfig.getExternalTempDir()));
}
private void update() {
@@ -146,7 +214,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
public void clearMemoryCache() {
if (null != mConaco) {
mConaco.clearMemoryCache();
mConaco.getBeerBelly().clearMemory();
}
if (null != mGalleryDetailCache) {
mGalleryDetailCache.evictAll();
@@ -162,13 +230,18 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
}
}
private void debugNativeMemory() {
private void debugPrint() {
new Runnable() {
@Override
public void run() {
Log.i(TAG, "Native memory: " + FileUtils.humanReadableByteCount(
Debug.getNativeHeapAllocatedSize(), false));
SimpleHandler.getInstance().postDelayed(this, 3000);
if (DEBUG_PRINT_NATIVE_MEMORY) {
Log.i(TAG, "Native memory: " + FileUtils.humanReadableByteCount(
Debug.getNativeHeapAllocatedSize(), false));
}
if (DEBUG_PRINT_IMAGE_COUNT) {
Log.i(TAG, "Image count: " + Image.getImageCount());
}
SimpleHandler.getInstance().postDelayed(this, DEBUG_PRINT_INTERVAL);
}
}.run();
}
@@ -176,6 +249,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
public int putGlobalStuff(@NonNull Object o) {
int id = mIdGenerator.nextId();
mGlobalStuffMap.put(id, o);
Settings.putInt(KEY_GLOBAL_STUFF_NEXT_ID, mIdGenerator.nextId());
return id;
}
@@ -198,7 +272,7 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
public static EhCookieStore getEhCookieStore(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mEhCookieStore == null) {
application.mEhCookieStore = new EhCookieStore();
application.mEhCookieStore = new EhCookieStore(context);
}
return application.mEhCookieStore;
}
@@ -212,48 +286,56 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
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());
if (application.mOkHttpClient == null) {
application.mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.cookieJar(getEhCookieStore(application))
.dns(new EhDns(application))
.proxySelector(getEhProxySelector(application))
.build();
}
return application.mOkHttpClient;
}
@NonNull
public static BitmapHelper getBitmapHelper(@NonNull Context context) {
public static ImageBitmapHelper getImageBitmapHelper(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mBitmapHelper == null) {
application.mBitmapHelper = new BitmapHelper();
if (application.mImageBitmapHelper == null) {
application.mImageBitmapHelper = new ImageBitmapHelper();
}
return application.mBitmapHelper;
return application.mImageBitmapHelper;
}
private static int getMemoryCacheMaxSize(Context context) {
final ActivityManager activityManager = (ActivityManager) context.
getSystemService(Context.ACTIVITY_SERVICE);
return Math.min(20 * 1024 * 1024,
Math.round(0.2f * activityManager.getMemoryClass() * 1024 * 1024));
private static int getMemoryCacheMaxSize() {
return Math.min(20 * 1024 * 1024, (int) OSUtils.getAppMaxMemory());
}
@NonNull
public static Conaco<Bitmap> getConaco(@NonNull Context context) {
public static Conaco<ImageBitmap> getConaco(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mConaco == null) {
Conaco.Builder<Bitmap> builder = new Conaco.Builder<>();
Conaco.Builder<ImageBitmap> builder = new Conaco.Builder<>();
builder.hasMemoryCache = true;
builder.memoryCacheMaxSize = getMemoryCacheMaxSize(context);
builder.memoryCacheMaxSize = getMemoryCacheMaxSize();
builder.hasDiskCache = true;
builder.diskCacheDir = new File(context.getCacheDir(), "thumb");
builder.diskCacheMaxSize = 80 * 1024 * 1024; // 80MB
builder.okHttpClient = getOkHttpClient(context);
builder.objectHelper = getBitmapHelper(context);
builder.objectHelper = getImageBitmapHelper(context);
builder.debug = DEBUG_CONACO;
application.mConaco = builder.build();
}
@@ -266,6 +348,12 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
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;
}
@@ -280,6 +368,11 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
return application.mSpiderInfoCache;
}
@NonNull
public static DownloadManager getDownloadManager() {
return getDownloadManager(instance);
}
@NonNull
public static DownloadManager getDownloadManager(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
@@ -289,26 +382,27 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
return application.mDownloadManager;
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
try {
ex.printStackTrace();
Crash.saveCrashInfo2File(this, ex);
return true;
} catch (Throwable tr) {
return false;
@NonNull
public static Hosts getHosts(@NonNull Context context) {
EhApplication application = ((EhApplication) context.getApplicationContext());
if (application.mHosts == null) {
application.mHosts = new Hosts(application, "hosts.db");
}
return application.mHosts;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
@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();
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
return application.mFavouriteStatusRouter;
}
@NonNull
@@ -332,4 +426,36 @@ public class EhApplication extends SceneApplication implements Thread.UncaughtEx
return null;
}
}
// Avoid crash on some "energy saving" devices
@Override
public ComponentName startService(Intent service) {
try {
return super.startService(service);
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
return null;
}
}
// Avoid crash on some "energy saving" devices
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
try {
return super.bindService(service, conn, flags);
} catch (Throwable t) {
ExceptionUtils.throwIfFatal(t);
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);
}
}
}
+121 -41
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;
@@ -43,12 +42,14 @@ import com.hippo.ehviewer.dao.LocalFavoritesDao;
import com.hippo.ehviewer.dao.QuickSearch;
import com.hippo.ehviewer.dao.QuickSearchDao;
import com.hippo.ehviewer.download.DownloadManager;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.SqlUtils;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.sparse.SparseJLArray;
import com.hippo.yorozuya.collect.SparseJLArray;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.query.CloseableListIterator;
import de.greenrobot.dao.query.LazyList;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -58,8 +59,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();
@@ -91,8 +90,36 @@ 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);
case 2: // 2 to 3, add ENABLE column to table FILTER
db.execSQL("CREATE TABLE " + "\"FILTER2\" (" +
"\"_id\" INTEGER PRIMARY KEY ," +
"\"MODE\" INTEGER NOT NULL ," +
"\"TEXT\" TEXT," +
"\"ENABLE\" INTEGER);");
db.execSQL("INSERT INTO \"FILTER2\" (" +
"_id, MODE, TEXT, ENABLE)" +
"SELECT _id, MODE, TEXT, 1 FROM FILTER;");
db.execSQL("DROP TABLE FILTER");
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");
}
}
@@ -143,7 +170,8 @@ public class EhDB {
SQLiteDatabase oldDB;
try {
oldDB = oldDBHelper.getReadableDatabase();
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
return;
}
@@ -162,7 +190,13 @@ public class EhDB {
gi.category = cursor.getInt(4);
gi.thumb = cursor.getString(5);
gi.uploader = cursor.getString(6);
gi.rating = cursor.getFloat(7);
try {
// In 0.6.x version, NaN is stored
gi.rating = cursor.getFloat(7);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
gi.rating = -1.0f;
}
map.put(gi.gid, gi);
@@ -171,7 +205,8 @@ public class EhDB {
}
cursor.close();
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
@@ -201,7 +236,8 @@ public class EhDB {
}
cursor.close();
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
@@ -237,7 +273,8 @@ public class EhDB {
}
cursor.close();
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
@@ -278,7 +315,8 @@ public class EhDB {
}
cursor.close();
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
@@ -307,13 +345,15 @@ public class EhDB {
}
cursor.close();
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
try {
oldDBHelper.close();
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
}
@@ -444,7 +484,7 @@ public class EhDB {
public static synchronized List<GalleryInfo> getAllLocalFavorites() {
LocalFavoritesDao dao = sDaoSession.getLocalFavoritesDao();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderAsc(LocalFavoritesDao.Properties.Time).list();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderDesc(LocalFavoritesDao.Properties.Time).list();
List<GalleryInfo> result = new ArrayList<>();
result.addAll(list);
return result;
@@ -453,7 +493,7 @@ public class EhDB {
public static synchronized List<GalleryInfo> searchLocalFavorites(String query) {
query = SqlUtils.sqlEscapeString("%" + query+ "%");
LocalFavoritesDao dao = sDaoSession.getLocalFavoritesDao();
List<LocalFavoriteInfo> list = dao.queryBuilder().orderAsc(LocalFavoritesDao.Properties.Time)
List<LocalFavoriteInfo> list = dao.queryBuilder().orderDesc(LocalFavoritesDao.Properties.Time)
.where(LocalFavoritesDao.Properties.Title.like(query)).list();
List<GalleryInfo> result = new ArrayList<>();
result.addAll(list);
@@ -601,30 +641,69 @@ public class EhDB {
sDaoSession.getFilterDao().delete(filter);
}
public static synchronized boolean exportDB(Context context, File file) {
File dbFile = context.getDatabasePath("eh.db");
if (null == dbFile || !dbFile.isFile()) {
return false;
}
if (null == file || !FileUtils.ensureFile(file)) {
return false;
}
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(dbFile);
os = new FileOutputStream(file);
IOUtils.copy(is, os);
return true;
public static synchronized void triggerFilter(Filter filter) {
filter.setEnable(!filter.enable);
sDaoSession.getFilterDao().update(filter);
}
private static <T> boolean copyDao(AbstractDao<T, ?> from, AbstractDao<T, ?> to) {
try (CloseableListIterator<T> iterator = from.queryBuilder().listIterator()) {
while (iterator.hasNext()) {
to.insert(iterator.next());
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static synchronized boolean exportDB(Context context, File file) {
final String ehExportName = "eh.export.db";
// Delete old export db
context.deleteDatabase(ehExportName);
DBOpenHelper helper = new DBOpenHelper(context.getApplicationContext(), ehExportName, null);
try {
// Copy data to a export db
try (SQLiteDatabase db = helper.getWritableDatabase()) {
DaoMaster daoMaster = new DaoMaster(db);
DaoSession exportSession = daoMaster.newSession();
if (!copyDao(sDaoSession.getDownloadsDao(), exportSession.getDownloadsDao())) return false;
if (!copyDao(sDaoSession.getDownloadLabelDao(), exportSession.getDownloadLabelDao())) return false;
if (!copyDao(sDaoSession.getDownloadDirnameDao(), exportSession.getDownloadDirnameDao())) return false;
if (!copyDao(sDaoSession.getHistoryDao(), exportSession.getHistoryDao())) return false;
if (!copyDao(sDaoSession.getQuickSearchDao(), exportSession.getQuickSearchDao())) return false;
if (!copyDao(sDaoSession.getLocalFavoritesDao(), exportSession.getLocalFavoritesDao())) return false;
if (!copyDao(sDaoSession.getBookmarksBao(), exportSession.getBookmarksBao())) return false;
if (!copyDao(sDaoSession.getFilterDao(), exportSession.getFilterDao())) return false;
}
// Copy export db to data dir
File dbFile = context.getDatabasePath(ehExportName);
if (dbFile == null || !dbFile.isFile()) {
return false;
}
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(dbFile);
os = new FileOutputStream(file);
IOUtils.copy(is, os);
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
// Delete failed file
file.delete();
return false;
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
context.deleteDatabase(ehExportName);
}
// Delete failed file
file.delete();
return false;
}
/**
@@ -703,7 +782,8 @@ public class EhDB {
}
return null;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
return context.getString(R.string.cant_read_the_file);
}
@@ -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 {
@@ -0,0 +1,350 @@
/*
* Copyright 2018 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;
/*
* Created by Hippo on 2018/3/21.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Pair;
import androidx.annotation.Nullable;
import com.hippo.database.MSQLiteBuilder;
import com.hippo.util.SqlUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class Hosts {
private static final int VERSION_1 = 1;
private static final String TABLE_HOSTS = "HOSTS";
private static final String COLUMN_HOST = "HOST";
private static final String COLUMN_IP = "IP";
private static final int DB_VERSION = VERSION_1;
private final SQLiteOpenHelper helper;
private final SQLiteDatabase db;
public Hosts(Context context, String name) {
helper = new MSQLiteBuilder()
.version(VERSION_1)
.createTable(TABLE_HOSTS)
.insertColumn(TABLE_HOSTS, COLUMN_HOST, String.class)
.insertColumn(TABLE_HOSTS, COLUMN_IP, String.class)
.build(context, name, DB_VERSION);
db = helper.getWritableDatabase();
}
/**
* Gets a InetAddress with the host.
*/
@Nullable
public InetAddress get(String host) {
if (!isValidHost(host)) {
return null;
}
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + " WHERE " + COLUMN_HOST + " = ?;", new String[] {host});
try {
if (cursor.moveToNext()) {
String ip = SqlUtils.getString(cursor, COLUMN_IP, null);
return toInetAddress(host, ip);
} else {
return null;
}
} finally {
cursor.close();
}
}
private boolean contains(String host) {
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + " WHERE " + COLUMN_HOST + " = ?;", new String[] {host});
try {
return cursor.moveToNext();
} finally {
cursor.close();
}
}
/**
* Puts the host-ip pair into this hosts.
*/
public boolean put(String host, String ip) {
if (!isValidHost(host) || !isValidIp(ip)) {
return false;
}
ContentValues values = new ContentValues();
values.put(COLUMN_HOST, host);
values.put(COLUMN_IP, ip);
if (contains(host)) {
db.update(TABLE_HOSTS, values, COLUMN_HOST + " = ?", new String[] { host });
} else {
db.insert(TABLE_HOSTS, null, values);
}
return true;
}
/**
* Puts delete the entry with the host.
*/
public void delete(String host) {
db.delete(TABLE_HOSTS, COLUMN_HOST + " = ?", new String[] { host });
}
/**
* Get all data from this host.
*/
public List<Pair<String, String>> getAll() {
List<Pair<String, String>> result = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + ";", null);
try {
while (cursor.moveToNext()) {
String host = SqlUtils.getString(cursor, COLUMN_HOST, null);
String ip = SqlUtils.getString(cursor, COLUMN_IP, null);
InetAddress inetAddress = toInetAddress(host, ip);
if (inetAddress == null) {
continue;
}
result.add(new Pair<>(host, ip));
}
} finally {
cursor.close();
}
return result;
}
@Nullable
public static InetAddress toInetAddress(String host, String ip) {
if (!isValidHost(host)) {
return null;
}
if (ip == null) {
return null;
}
byte[] bytes = parseV4(ip);
if (bytes == null) {
bytes = parseV6(ip);
}
if (bytes == null) {
return null;
}
try {
return InetAddress.getByAddress(host, bytes);
} catch (UnknownHostException e) {
return null;
}
}
/**
* Returns true if the host is valid.
*/
public static boolean isValidHost(String host) {
if (host == null) {
return false;
}
if (host.length() > 253) {
return false;
}
int labelLength = 0;
for (int i = 0, n = host.length(); i < n; i++) {
char ch = host.charAt(i);
if (ch == '.') {
if (labelLength < 1 || labelLength > 63) {
return false;
}
labelLength = 0;
} else {
labelLength++;
}
if ((ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '-' && ch != '.') {
return false;
}
}
if (labelLength < 1 || labelLength > 63) {
return false;
}
return true;
}
/**
* Returns true if the ip is valid.
*/
public static boolean isValidIp(String ip) {
return ip != null && (parseV4(ip) != null || parseV6(ip) != null);
}
// org.xbill.DNS.Address.parseV4
@Nullable
private static byte[] parseV4(String s) {
int numDigits;
int currentOctet;
byte [] values = new byte[4];
int currentValue;
int length = s.length();
currentOctet = 0;
currentValue = 0;
numDigits = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
/* Can't have more than 3 digits per octet. */
if (numDigits == 3)
return null;
/* Octets shouldn't start with 0, unless they are 0. */
if (numDigits > 0 && currentValue == 0)
return null;
numDigits++;
currentValue *= 10;
currentValue += (c - '0');
/* 255 is the maximum value for an octet. */
if (currentValue > 255)
return null;
} else if (c == '.') {
/* Can't have more than 3 dots. */
if (currentOctet == 3)
return null;
/* Two consecutive dots are bad. */
if (numDigits == 0)
return null;
values[currentOctet++] = (byte) currentValue;
currentValue = 0;
numDigits = 0;
} else
return null;
}
/* Must have 4 octets. */
if (currentOctet != 3)
return null;
/* The fourth octet can't be empty. */
if (numDigits == 0)
return null;
values[currentOctet] = (byte) currentValue;
return values;
}
// org.xbill.DNS.Address.parseV6
@Nullable
private static byte[] parseV6(String s) {
int range = -1;
byte [] data = new byte[16];
String [] tokens = s.split(":", -1);
int first = 0;
int last = tokens.length - 1;
if (tokens[0].length() == 0) {
// If the first two tokens are empty, it means the string
// started with ::, which is fine. If only the first is
// empty, the string started with :, which is bad.
if (last - first > 0 && tokens[1].length() == 0)
first++;
else
return null;
}
if (tokens[last].length() == 0) {
// If the last two tokens are empty, it means the string
// ended with ::, which is fine. If only the last is
// empty, the string ended with :, which is bad.
if (last - first > 0 && tokens[last - 1].length() == 0)
last--;
else
return null;
}
if (last - first + 1 > 8)
return null;
int i, j;
for (i = first, j = 0; i <= last; i++) {
if (tokens[i].length() == 0) {
if (range >= 0)
return null;
range = j;
continue;
}
if (tokens[i].indexOf('.') >= 0) {
// An IPv4 address must be the last component
if (i < last)
return null;
// There can't have been more than 6 components.
if (i > 6)
return null;
byte [] v4addr = parseV4(tokens[i]);
if (v4addr == null)
return null;
for (int k = 0; k < 4; k++)
data[j++] = v4addr[k];
break;
}
try {
for (int k = 0; k < tokens[i].length(); k++) {
char c = tokens[i].charAt(k);
if (Character.digit(c, 16) < 0)
return null;
}
int x = Integer.parseInt(tokens[i], 16);
if (x > 0xFFFF || x < 0)
return null;
data[j++] = (byte)(x >>> 8);
data[j++] = (byte)(x & 0xFF);
}
catch (NumberFormatException e) {
return null;
}
}
if (j < 16 && range < 0)
return null;
if (range >= 0) {
int empty = 16 - j;
System.arraycopy(data, range, data, range + empty, j - range);
for (i = range; i < range + empty; i++)
data[i] = 0;
}
return data;
}
}
@@ -0,0 +1,70 @@
/*
* 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;
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> {
private static final int MAX_CACHE_SIZE = 512 * 512;
@Nullable
@Override
public ImageBitmap decode(@NonNull InputStreamPipe isPipe) {
try {
isPipe.obtain();
return ImageBitmap.decode(isPipe.open());
} catch (OutOfMemoryError e) {
return null;
} catch (IOException e) {
return null;
} finally {
isPipe.close();
isPipe.release();
}
}
@Override
public int sizeOf(@NonNull String key, @NonNull ImageBitmap value) {
return value.getWidth() * value.getHeight() * 4 /* value.getByteCount() TODO Update Image */;
}
@Override
public void onAddToMemoryCache(@NonNull ImageBitmap oldValue) {
oldValue.obtain();
}
@Override
public void onRemoveFromMemoryCache(@NonNull String key, @NonNull ImageBitmap oldValue) {
oldValue.release();
}
@Override
public boolean useMemoryCache(@NonNull String key, ImageBitmap value) {
if (value != null) {
return value.getWidth() * value.getHeight() <= MAX_CACHE_SIZE
/* value.getByteCount() <= MAX_CACHE_BYTE_COUNT TODO Update Image */;
} else {
return true;
}
}
}
+407 -110
View File
@@ -16,28 +16,28 @@
package com.hippo.ehviewer;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
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.gallery.gl.GalleryView;
import com.hippo.ehviewer.gallery.gl.ImageView;
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;
import com.hippo.yorozuya.AssertUtils;
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 {
@@ -51,10 +51,21 @@ 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() {
EhConfig ehConfig= new EhConfig();
ehConfig.imageSize = getImageResolution();
ehConfig.excludedLanguages = getExcludedLanguages();
ehConfig.defaultCategories = getDefaultCategories();
ehConfig.excludedNamespaces = getExcludedTagNamespaces();
@@ -235,6 +246,28 @@ public class Settings {
/********************
****** Eh
********************/
public static final String KEY_THEME = "theme";
public static final int THEME_LIGHT = 0;
public static final int THEME_DARK = 1;
public static final int THEME_BLACK = 2;
private static final int DEFAULT_THEME = THEME_LIGHT;
public static int getTheme() {
return getIntFromStr(KEY_THEME, DEFAULT_THEME);
}
public static void putTheme(int theme) {
putIntToStr(KEY_THEME, theme);
}
public static final String KEY_APPLY_NAV_BAR_THEME_COLOR = "apply_nav_bar_theme_color";
private static final boolean DEFAULT_APPLY_NAV_BAR_THEME_COLOR = true;
public static boolean getApplyNavBarThemeColor() {
return getBoolean(KEY_APPLY_NAV_BAR_THEME_COLOR, DEFAULT_APPLY_NAV_BAR_THEME_COLOR);
}
public static final String KEY_GALLERY_SITE = "gallery_site";
private static final int DEFAULT_GALLERY_SITE = 1;
@@ -246,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;
@@ -253,6 +302,58 @@ public class Settings {
return getIntFromStr(KEY_LIST_MODE, DEFAULT_LIST_MODE);
}
public static final String KEY_DETAIL_SIZE = "detail_size";
private static final int DEFAULT_DETAIL_SIZE = 0;
public static int getDetailSize() {
return getIntFromStr(KEY_DETAIL_SIZE, DEFAULT_DETAIL_SIZE);
}
@DimenRes
public static int getDetailSizeResId() {
switch (getDetailSize()) {
default:
case 0:
return R.dimen.gallery_list_column_width_long;
case 1:
return R.dimen.gallery_list_column_width_short;
}
}
public static final String KEY_THUMB_SIZE = "thumb_size";
private static final int DEFAULT_THUMB_SIZE = 1;
public static int getThumbSize() {
return getIntFromStr(KEY_THUMB_SIZE, DEFAULT_THUMB_SIZE);
}
@DimenRes
public static int getThumbSizeResId() {
switch (getThumbSize()) {
case 0:
return R.dimen.gallery_grid_column_width_large;
default:
case 1:
return R.dimen.gallery_grid_column_width_middle;
case 2:
return R.dimen.gallery_grid_column_width_small;
}
}
public static final String KEY_THUMB_RESOLUTION = "thumb_resolution";
private static final int DEFAULT_THUMB_RESOLUTION = 0;
public static int getThumbResolution() {
return getIntFromStr(KEY_THUMB_RESOLUTION, DEFAULT_THUMB_RESOLUTION);
}
private static final String KEY_FIX_THUMB_URL = "fix_thumb_url";
private static final boolean DEFAULT_FIX_THUMB_URL = false;
public static boolean getFixThumbUrl() {
return getBoolean(KEY_FIX_THUMB_URL, DEFAULT_FIX_THUMB_URL);
}
private static final String KEY_SHOW_JPN_TITLE = "show_jpn_title";
private static final boolean DEFAULT_SHOW_JPN_TITLE = false;
@@ -260,6 +361,20 @@ public class Settings {
return getBoolean(KEY_SHOW_JPN_TITLE, DEFAULT_SHOW_JPN_TITLE);
}
private static final String KEY_SHOW_GALLERY_PAGES = "show_gallery_pages";
private static final boolean DEFAULT_SHOW_GALLERY_PAGES = false;
public static boolean getShowGalleryPages() {
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;
@@ -299,70 +414,11 @@ 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;
private static final String KEY_CELLULAR_NETWORK_WARNING = "cellular_network_warning";
private static final boolean DEFAULT_CELLULAR_NETWORK_WARNING = 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);
public static boolean getCellularNetworkWarning() {
return getBoolean(KEY_CELLULAR_NETWORK_WARNING, DEFAULT_CELLULAR_NETWORK_WARNING);
}
/********************
@@ -380,7 +436,7 @@ public class Settings {
}
private static final String KEY_READING_DIRECTION = "reading_direction";
private static final int DEFAULT_READING_DIRECTION = GalleryView.LAYOUT_MODE_RIGHT_TO_LEFT;
private static final int DEFAULT_READING_DIRECTION = GalleryView.LAYOUT_RIGHT_TO_LEFT;
@GalleryView.LayoutMode
public static int getReadingDirection() {
@@ -392,11 +448,11 @@ public class Settings {
}
private static final String KEY_PAGE_SCALING = "page_scaling";
private static final int DEFAULT_PAGE_SCALING = ImageView.SCALE_FIT;
private static final int DEFAULT_PAGE_SCALING = GalleryView.SCALE_FIT;
@ImageView.Scale
@GalleryView.ScaleMode
public static int getPageScaling() {
return ImageView.sanitizeScaleMode(getIntFromStr(KEY_PAGE_SCALING, DEFAULT_PAGE_SCALING));
return GalleryView.sanitizeScaleMode(getIntFromStr(KEY_PAGE_SCALING, DEFAULT_PAGE_SCALING));
}
public static void putPageScaling(int value) {
@@ -404,11 +460,11 @@ public class Settings {
}
private static final String KEY_START_POSITION = "start_position";
private static final int DEFAULT_START_POSITION = ImageView.START_POSITION_TOP_RIGHT;
private static final int DEFAULT_START_POSITION = GalleryView.START_POSITION_TOP_RIGHT;
@ImageView.StartPosition
@GalleryView.StartPosition
public static int getStartPosition() {
return ImageView.sanitizeStartPosition(getIntFromStr(KEY_START_POSITION, DEFAULT_START_POSITION));
return GalleryView.sanitizeStartPosition(getIntFromStr(KEY_START_POSITION, DEFAULT_START_POSITION));
}
public static void putStartPosition(int value) {
@@ -437,6 +493,17 @@ public class Settings {
putBoolean(KEY_SHOW_CLOCK, value);
}
private static final String KEY_SHOW_PROGRESS = "gallery_show_progress";
private static final boolean DEFAULT_SHOW_PROGRESS = true;
public static boolean getShowProgress() {
return getBoolean(KEY_SHOW_PROGRESS, DEFAULT_SHOW_PROGRESS);
}
public static void putShowProgress(boolean value) {
putBoolean(KEY_SHOW_PROGRESS, value);
}
private static final String KEY_SHOW_BATTERY = "gallery_show_battery";
private static final boolean DEFAULT_SHOW_BATTERY = true;
@@ -448,6 +515,17 @@ public class Settings {
putBoolean(KEY_SHOW_BATTERY, value);
}
private static final String KEY_SHOW_PAGE_INTERVAL = "gallery_show_page_interval";
private static final boolean DEFAULT_SHOW_PAGE_INTERVAL = true;
public static boolean getShowPageInterval() {
return getBoolean(KEY_SHOW_PAGE_INTERVAL, DEFAULT_SHOW_PAGE_INTERVAL);
}
public static void putShowPageInterval(boolean value) {
putBoolean(KEY_SHOW_PAGE_INTERVAL, value);
}
private static final String KEY_VOLUME_PAGE = "volume_page";
private static final boolean DEFAULT_VOLUME_PAGE = false;
@@ -459,6 +537,52 @@ public class Settings {
putBoolean(KEY_VOLUME_PAGE, value);
}
private static final String KEY_READING_FULLSCREEN = "reading_fullscreen";
private static final boolean VALUE_READING_FULLSCREEN = true;
public static boolean getReadingFullscreen() {
return getBoolean(KEY_READING_FULLSCREEN, VALUE_READING_FULLSCREEN);
}
public static void putReadingFullscreen(boolean value) {
putBoolean(KEY_READING_FULLSCREEN, value);
}
private static final String KEY_CUSTOM_SCREEN_LIGHTNESS = "custom_screen_lightness";
private static final boolean DEFAULT_CUSTOM_SCREEN_LIGHTNESS = false;
public static boolean getCustomScreenLightness() {
return getBoolean(KEY_CUSTOM_SCREEN_LIGHTNESS, DEFAULT_CUSTOM_SCREEN_LIGHTNESS);
}
public static void putCustomScreenLightness(boolean value) {
putBoolean(KEY_CUSTOM_SCREEN_LIGHTNESS, value);
}
private static final String KEY_SCREEN_LIGHTNESS = "screen_lightness";
private static final int DEFAULT_SCREEN_LIGHTNESS = 50;
public static int getScreenLightness() {
return getInt(KEY_SCREEN_LIGHTNESS, DEFAULT_SCREEN_LIGHTNESS);
}
public static void putScreenLightness(int value) {
putInt(KEY_SCREEN_LIGHTNESS, value);
}
/********************
****** Privacy and Security
********************/
public static final String KEY_SEC_SECURITY = "enable_secure";
public static final boolean VALUE_SEC_SECURITY = false;
public static boolean getEnabledSecurity() {
return getBoolean(KEY_SEC_SECURITY, VALUE_SEC_SECURITY);
}
public static void putEnabledSecurity(boolean value) {
putBoolean(KEY_READING_FULLSCREEN, value);
}
/********************
****** Download
********************/
@@ -479,7 +603,8 @@ public class Settings {
builder.encodedQuery(getString(KEY_DOWNLOAD_SAVE_QUERY, null));
builder.encodedFragment(getString(KEY_DOWNLOAD_SAVE_FRAGMENT, null));
dir = UniFile.fromUri(sContext, builder.build());
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
return dir != null ? dir : UniFile.fromFile(AppConfig.getDefaultDownloadDir());
@@ -493,7 +618,18 @@ public class Settings {
putString(KEY_DOWNLOAD_SAVE_QUERY, uri.getEncodedQuery());
putString(KEY_DOWNLOAD_SAVE_FRAGMENT, uri.getEncodedFragment());
CommonOperations.ensureNoMediaFile(location);
if (getMediaScan()) {
CommonOperations.removeNoMediaFile(location);
} else {
CommonOperations.ensureNoMediaFile(location);
}
}
public static final String KEY_MEDIA_SCAN = "media_scan";
private static final boolean DEFAULT_MEDIA_SCAN = false;
public static boolean getMediaScan() {
return getBoolean(KEY_MEDIA_SCAN, DEFAULT_MEDIA_SCAN);
}
private static final String KEY_RECENT_DOWNLOAD_LABEL = "recent_download_label";
@@ -551,6 +687,19 @@ public class Settings {
putIntToStr(KEY_PRELOAD_IMAGE, value);
}
public static final String KEY_IMAGE_RESOLUTION = "image_size";
public static final String DEFAULT_IMAGE_RESOLUTION = EhConfig.IMAGE_SIZE_AUTO;
public static String getImageResolution() {
return getString(KEY_IMAGE_RESOLUTION, DEFAULT_IMAGE_RESOLUTION);
}
public static void putImageResolution(String value) {
sEhConfig.imageSize = value;
sEhConfig.setDirty();
putString(KEY_IMAGE_RESOLUTION, value);
}
private static final String KEY_DOWNLOAD_ORIGIN_IMAGE = "download_origin_image";
private static final boolean DEFAULT_DOWNLOAD_ORIGIN_IMAGE = false;
@@ -565,26 +714,42 @@ public class Settings {
/********************
****** Favorites
********************/
public static final String KEY_FAV_CAT_0 = "fav_cat_0";
public static final String KEY_FAV_CAT_1 = "fav_cat_1";
public static final String KEY_FAV_CAT_2 = "fav_cat_2";
public static final String KEY_FAV_CAT_3 = "fav_cat_3";
public static final String KEY_FAV_CAT_4 = "fav_cat_4";
public static final String KEY_FAV_CAT_5 = "fav_cat_5";
public static final String KEY_FAV_CAT_6 = "fav_cat_6";
public static final String KEY_FAV_CAT_7 = "fav_cat_7";
public static final String KEY_FAV_CAT_8 = "fav_cat_8";
public static final String KEY_FAV_CAT_9 = "fav_cat_9";
public static final String DEFAULT_FAV_CAT_0 = "Favorites 0";
public static final String DEFAULT_FAV_CAT_1 = "Favorites 1";
public static final String DEFAULT_FAV_CAT_2 = "Favorites 2";
public static final String DEFAULT_FAV_CAT_3 = "Favorites 3";
public static final String DEFAULT_FAV_CAT_4 = "Favorites 4";
public static final String DEFAULT_FAV_CAT_5 = "Favorites 5";
public static final String DEFAULT_FAV_CAT_6 = "Favorites 6";
public static final String DEFAULT_FAV_CAT_7 = "Favorites 7";
public static final String DEFAULT_FAV_CAT_8 = "Favorites 8";
public static final String DEFAULT_FAV_CAT_9 = "Favorites 9";
private static final String KEY_FAV_CAT_0 = "fav_cat_0";
private static final String KEY_FAV_CAT_1 = "fav_cat_1";
private static final String KEY_FAV_CAT_2 = "fav_cat_2";
private static final String KEY_FAV_CAT_3 = "fav_cat_3";
private static final String KEY_FAV_CAT_4 = "fav_cat_4";
private static final String KEY_FAV_CAT_5 = "fav_cat_5";
private static final String KEY_FAV_CAT_6 = "fav_cat_6";
private static final String KEY_FAV_CAT_7 = "fav_cat_7";
private static final String KEY_FAV_CAT_8 = "fav_cat_8";
private static final String KEY_FAV_CAT_9 = "fav_cat_9";
private static final String DEFAULT_FAV_CAT_0 = "Favorites 0";
private static final String DEFAULT_FAV_CAT_1 = "Favorites 1";
private static final String DEFAULT_FAV_CAT_2 = "Favorites 2";
private static final String DEFAULT_FAV_CAT_3 = "Favorites 3";
private static final String DEFAULT_FAV_CAT_4 = "Favorites 4";
private static final String DEFAULT_FAV_CAT_5 = "Favorites 5";
private static final String DEFAULT_FAV_CAT_6 = "Favorites 6";
private static final String DEFAULT_FAV_CAT_7 = "Favorites 7";
private static final String DEFAULT_FAV_CAT_8 = "Favorites 8";
private static final String DEFAULT_FAV_CAT_9 = "Favorites 9";
private static final String KEY_FAV_COUNT_0 = "fav_count_0";
private static final String KEY_FAV_COUNT_1 = "fav_count_1";
private static final String KEY_FAV_COUNT_2 = "fav_count_2";
private static final String KEY_FAV_COUNT_3 = "fav_count_3";
private static final String KEY_FAV_COUNT_4 = "fav_count_4";
private static final String KEY_FAV_COUNT_5 = "fav_count_5";
private static final String KEY_FAV_COUNT_6 = "fav_count_6";
private static final String KEY_FAV_COUNT_7 = "fav_count_7";
private static final String KEY_FAV_COUNT_8 = "fav_count_8";
private static final String KEY_FAV_COUNT_9 = "fav_count_9";
private static final String KEY_FAV_LOCAL = "fav_local";
private static final String KEY_FAV_CLOUD = "fav_cloud";
private static final int DEFAULT_FAV_COUNT = 0;
public static String[] getFavCat() {
String[] favCat = new String[10];
@@ -617,6 +782,53 @@ public class Settings {
.apply();
}
public static int[] getFavCount() {
int[] favCount = new int[10];
favCount[0] = sSettingsPre.getInt(KEY_FAV_COUNT_0, DEFAULT_FAV_COUNT);
favCount[1] = sSettingsPre.getInt(KEY_FAV_COUNT_1, DEFAULT_FAV_COUNT);
favCount[2] = sSettingsPre.getInt(KEY_FAV_COUNT_2, DEFAULT_FAV_COUNT);
favCount[3] = sSettingsPre.getInt(KEY_FAV_COUNT_3, DEFAULT_FAV_COUNT);
favCount[4] = sSettingsPre.getInt(KEY_FAV_COUNT_4, DEFAULT_FAV_COUNT);
favCount[5] = sSettingsPre.getInt(KEY_FAV_COUNT_5, DEFAULT_FAV_COUNT);
favCount[6] = sSettingsPre.getInt(KEY_FAV_COUNT_6, DEFAULT_FAV_COUNT);
favCount[7] = sSettingsPre.getInt(KEY_FAV_COUNT_7, DEFAULT_FAV_COUNT);
favCount[8] = sSettingsPre.getInt(KEY_FAV_COUNT_8, DEFAULT_FAV_COUNT);
favCount[9] = sSettingsPre.getInt(KEY_FAV_COUNT_9, DEFAULT_FAV_COUNT);
return favCount;
}
public static void putFavCount(int[] count) {
AssertUtils.assertEquals(10, count.length);
sSettingsPre.edit()
.putInt(KEY_FAV_COUNT_0, count[0])
.putInt(KEY_FAV_COUNT_1, count[1])
.putInt(KEY_FAV_COUNT_2, count[2])
.putInt(KEY_FAV_COUNT_3, count[3])
.putInt(KEY_FAV_COUNT_4, count[4])
.putInt(KEY_FAV_COUNT_5, count[5])
.putInt(KEY_FAV_COUNT_6, count[6])
.putInt(KEY_FAV_COUNT_7, count[7])
.putInt(KEY_FAV_COUNT_8, count[8])
.putInt(KEY_FAV_COUNT_9, count[9])
.apply();
}
public static int getFavLocalCount() {
return sSettingsPre.getInt(KEY_FAV_LOCAL, DEFAULT_FAV_COUNT);
}
public static void putFavLocalCount(int count) {
sSettingsPre.edit().putInt(KEY_FAV_LOCAL, count).apply();
}
public static int getFavCloudCount() {
return sSettingsPre.getInt(KEY_FAV_CLOUD, DEFAULT_FAV_COUNT);
}
public static void putFavCloudCount(int count) {
sSettingsPre.edit().putInt(KEY_FAV_CLOUD, count).apply();
}
private static final String KEY_RECENT_FAV_CAT = "recent_fav_cat";
private static final int DEFAULT_RECENT_FAV_CAT = FavListUrlBuilder.FAV_CAT_ALL;
@@ -733,6 +945,8 @@ public class Settings {
********************/
private static final String KEY_BETA_UPDATE_CHANNEL = "beta_update_channel";
private static final boolean DEFAULT_BETA_UPDATE_CHANNEL = EhApplication.BETA;
private static final String KEY_SKIP_UPDATE_VERSION = "skip_update_version";
private static final int DEFAULT_SKIP_UPDATE_VERSION = 0;
public static boolean getBetaUpdateChannel() {
return getBoolean(KEY_BETA_UPDATE_CHANNEL, DEFAULT_BETA_UPDATE_CHANNEL);
@@ -742,19 +956,12 @@ public class Settings {
putBoolean(KEY_BETA_UPDATE_CHANNEL, value);
}
/********************
****** Crash
********************/
private static final String KEY_CRASH_FILENAME = "crash_filename";
private static final String DEFAULT_CRASH_FILENAME = null;
public static String getCrashFilename() {
return getString(KEY_CRASH_FILENAME, DEFAULT_CRASH_FILENAME);
public static int getSkipUpdateVersion() {
return getInt(KEY_SKIP_UPDATE_VERSION, DEFAULT_SKIP_UPDATE_VERSION);
}
@SuppressLint("CommitPrefEdits")
public static void putCrashFilename(String value) {
sSettingsPre.edit().putString(KEY_CRASH_FILENAME, value).commit();
public static void putSkipUpdateVersion(int value) {
putInt(KEY_SKIP_UPDATE_VERSION, value);
}
/********************
@@ -771,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 = "";
@@ -782,6 +996,78 @@ public class Settings {
putString(KEY_SECURITY, value);
}
public static final String KEY_ENABLE_FINGERPRINT = "enable_fingerprint";
public static boolean getEnableFingerprint() {
return getBoolean(KEY_ENABLE_FINGERPRINT, false);
}
public static void putEnableFingerprint(boolean value) {
putBoolean(KEY_ENABLE_FINGERPRINT, value);
}
public static final String KEY_READ_CACHE_SIZE = "read_cache_size";
public static final int DEFAULT_READ_CACHE_SIZE = 160;
public static int getReadCacheSize() {
return getIntFromStr(KEY_READ_CACHE_SIZE, DEFAULT_READ_CACHE_SIZE);
}
public static final String KEY_BUILT_IN_HOSTS = "built_in_hosts";
private static final boolean DEFAULT_BUILT_IN_HOSTS = false;
public static boolean getBuiltInHosts() {
return getBoolean(KEY_BUILT_IN_HOSTS, DEFAULT_BUILT_IN_HOSTS);
}
public static void putBuiltInHosts(boolean value) {
putBoolean(KEY_BUILT_IN_HOSTS, value);
}
public static final String KEY_APP_LANGUAGE = "app_language";
private static final String DEFAULT_APP_LANGUAGE = "system";
public static String getAppLanguage() {
return getString(KEY_APP_LANGUAGE, DEFAULT_APP_LANGUAGE);
}
public static void putAppLanguage(String value) {
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
********************/
@@ -839,4 +1125,15 @@ public class Settings {
public static void putGuideGallery(boolean value) {
putBoolean(KEY_GUIDE_GALLERY, value);
}
private static final String KEY_CLIPBOARD_TEXT_HASH_CODE = "clipboard_text_hash_code";
private static final int DEFAULT_CLIPBOARD_TEXT_HASH_CODE = 0;
public static int getClipboardTextHashCode() {
return getInt(KEY_CLIPBOARD_TEXT_HASH_CODE, DEFAULT_CLIPBOARD_TEXT_HASH_CODE);
}
public static void putClipboardTextHashCode(int value) {
putInt(KEY_CLIPBOARD_TEXT_HASH_CODE, value);
}
}
@@ -16,29 +16,25 @@
package com.hippo.ehviewer;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Browser;
import android.support.annotation.NonNull;
import android.support.customtabs.CustomTabsIntent;
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;
import com.hippo.scene.StageActivity;
import com.hippo.util.CustomTabsHelper;
import com.hippo.util.ExceptionUtils;
public final class UrlOpener {
private UrlOpener() {
}
public static void openUrl(@NonNull Context context, String url, boolean ehUrl, boolean customTabs) {
public static void openUrl(@NonNull Context context, String url, boolean ehUrl) {
if (TextUtils.isEmpty(url)) {
return;
}
@@ -59,26 +55,13 @@ public final class UrlOpener {
}
}
// CustomTabs
if (customTabs && context instanceof Activity) {
Activity activity = (Activity) context;
String packageName = CustomTabsHelper.getPackageNameToUseFixed(activity);
if (packageName != null) {
new CustomTabsIntent.Builder()
.setToolbarColor(activity.getResources().getColor(R.color.colorPrimary))
.setShowTitle(true)
.build()
.launchUrl(activity, uri);
return;
}
}
// Intent.ACTION_VIEW
intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
Toast.makeText(context, R.string.error_cant_find_activity, Toast.LENGTH_SHORT).show();
}
}
@@ -18,23 +18,15 @@ 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.yorozuya.PriorityThreadFactory;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.IoThreadPoolExecutor;
import com.hippo.yorozuya.SimpleHandler;
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;
import okhttp3.OkHttpClient;
@@ -44,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;
@@ -55,21 +46,17 @@ 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;
public static final int METHOD_ARCHIVE_LIST = 17;
public static final int METHOD_DOWNLOAD_ARCHIVE = 18;
private final ThreadPoolExecutor mRequestThreadPool;
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]);
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,19 +160,22 @@ 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:
return EhEngine.voteComment(this, mOkHttpClient, (Long) params[0], (String) params[1], (Long) params[2], (String) params[3], (Long) params[4], (Integer) params[5]);
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], (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:
return new IllegalStateException("Can't detect method " + mMethod);
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
return e;
}
}
@@ -30,8 +30,20 @@ public class EhConfig implements Cloneable {
/**
* The key of load images through the Hentai@Home Network
* @see #LOAD_FROM_HAH_YES
* @see #LOAD_FROM_HAH_NO
*/
private static final String KEY_LOAD_FROM_HAH = "uh";
/**
* The key of Image Size Settings
* @see #IMAGE_SIZE_AUTO
* @see #IMAGE_SIZE_780X
* @see #IMAGE_SIZE_980X
* @see #IMAGE_SIZE_1280X
* @see #IMAGE_SIZE_1600X
* @see #IMAGE_SIZE_2400X
*/
private static final String KEY_IMAGE_SIZE = "xr";
/**
* The key of scale images width
*/
@@ -40,18 +52,42 @@ public class EhConfig implements Cloneable {
* The key of scale images height
*/
private static final String KEY_SCALE_HEIGHT = "ry";
/**
* The key of Gallery Name Display
* @see #GALLERY_TITLE_DEFAULT
* @see #GALLERY_TITLE_JAPANESE
*/
private static final String KEY_GALLERY_TITLE = "tl";
/**
* The key of the behavior for downloading archiver
* @see #ARCHIVER_DOWNLOAD_MAMS
* @see #ARCHIVER_DOWNLOAD_MAAS
* @see #ARCHIVER_DOWNLOAD_AAMS
* @see #ARCHIVER_DOWNLOAD_AAAS
*/
private static final String KEY_ARCHIVER_DOWNLOAD = "ar";
/**
* The key of display mode would you like to use on the front and search pages
* @see #LAYOUT_MODE_LIST
* @see #LAYOUT_MODE_THUMB
*/
private static final String KEY_LAYOUT_MODE = "dm";
/**
* The key for show popular
* @see #POPULAR_YES
* @see #POPULAR_NO
*/
private static final String KEY_POPULAR = "prn";
/**
* The key of categories would you like to view as default on the front page
*/
private static final String KEY_DEFAULT_CATEGORIES = "cats";
/**
* The key for favorites sort
* @see #FAVORITES_SORT_GALLERY_UPDATE_TIME
* @see #FAVORITES_SORT_FAVORITED_TIME
*/
private static final String KEY_FAVORITES_SORT = "fs";
/**
* The key of exclude certain namespaces from a default tag search
*/
@@ -62,34 +98,55 @@ public class EhConfig implements Cloneable {
private static final String KEY_EXCLUDED_LANGUAGES = "xl";
/**
* The key of how many results would you like per page for the index/search page and torrent search pages
* @see #RESULT_COUNT_25
* @see #RESULT_COUNT_50
* @see #RESULT_COUNT_100
* @see #RESULT_COUNT_200
*/
private static final String KEY_RESULT_COUNT = "rc";
/**
* The key of mouse-over thumb
* @see #MOUSE_OVER_YES
* @see #MOUSE_OVER_NO
*/
private static final String KEY_MOUSE_OVER = "tl";
private static final String KEY_MOUSE_OVER = "lt";
/**
* The key of preview size
* @see #PREVIEW_SIZE_NORMAL
* @see #PREVIEW_SIZE_LARGE
*/
private static final String KEY_PREVIEW_SIZE = "ts";
/**
* The key of preview row per page
* @see #PREVIEW_ROW_4
* @see #PREVIEW_ROW_10
* @see #PREVIEW_ROW_20
* @see #PREVIEW_ROW_40
*/
private static final String KEY_PREVIEW_ROW = "tr";
/**
* The key of sort order for gallery comments
* @see #COMMENTS_SORT_OLDEST_FIRST
* @see #COMMENTS_SORT_RECENT_FIRST
* @see #COMMENTS_SORT_HIGHEST_SCORE_FIRST
*/
private static final String KEY_COMMENTS_SORT = "cs";
/**
* The key of show gallery comment votes
* @see #COMMENTS_VOTES_POP
* @see #COMMENTS_VOTES_ALWAYS
*/
private static final String KEY_COMMENTS_VOTES = "sc";
/**
* The key of sort order for gallery tags
* @see #TAGS_SORT_ALPHABETICAL
* @see #TAGS_SORT_POWER
*/
private static final String KEY_TAGS_SORT = "to";
/**
* The key of show gallery page numbers
* @see #SHOW_GALLERY_INDEX_NO
* @see #SHOW_GALLERY_INDEX_YES
*/
private static final String KEY_SHOW_GALLERY_INDEX = "pn";
/**
@@ -104,22 +161,33 @@ public class EhConfig implements Cloneable {
private static final String KEY_HAH_CLIENT_PASSKEY = "hk";
/**
* The key of enable Tag Flagging
* @see #ENABLE_TAG_FLAGGING_NO
* @see #ENABLE_TAG_FLAGGING_YES
*/
private static final String KEY_ENABLE_TAG_FLAGGING = "tf";
/**
* The key of always display the original images instead of the resampled versions
* @see #ALWAYS_ORIGINAL_NO
* @see #ALWAYS_ORIGINAL_YES
*/
private static final String KEY_ALWAYS_ORIGINAL = "oi";
/**
* The key of enable the multi-Page Viewer
* @see #MULTI_PAGE_NO
* @see #MULTI_PAGE_YES
*/
private static final String KEY_MULTI_PAGE = "qb";
/**
* The key of multi-Page Viewer Display Style
* @see #MULTI_PAGE_STYLE_C
* @see #MULTI_PAGE_STYLE_N
* @see #MULTI_PAGE_STYLE_Y
*/
private static final String KEY_MULTI_PAGE_STYLE = "ms";
/**
* The key of multi-Page Viewer Thumbnail Pane
* @see #MULTI_PAGE_THUMB_HIDE
* @see #MULTI_PAGE_THUMB_SHOW
*/
private static final String KEY_MULTI_PAGE_THUMB = "mt";
@@ -142,6 +210,40 @@ public class EhConfig implements Cloneable {
*/
public static final String LOAD_FROM_HAH_NO = "n";
/**
* Image Size Auto
*/
public static final String IMAGE_SIZE_AUTO = "a";
/**
* Image Size 780x
*/
public static final String IMAGE_SIZE_780X = "780";
/**
* Image Size 980x
*/
public static final String IMAGE_SIZE_980X = "980";
/**
* Image Size 1280x
*/
public static final String IMAGE_SIZE_1280X = "1280";
/**
* Image Size 1600x
*/
public static final String IMAGE_SIZE_1600X = "1600";
/**
* Image Size 2400x
*/
public static final String IMAGE_SIZE_2400X = "2400";
/**
* Default gallery title
*/
private static final String GALLERY_TITLE_DEFAULT = "r";
/**
* Japanese gallery title
*/
private static final String GALLERY_TITLE_JAPANESE = "j";
/**
* Manual Accept, Manual Start
*/
@@ -168,6 +270,15 @@ public class EhConfig implements Cloneable {
*/
public static final String LAYOUT_MODE_THUMB = "t";
/**
* Show popular
*/
private static final String POPULAR_YES = "y";
/**
* Don't show popular
*/
private static final String POPULAR_NO = "n";
public static final int MISC = 0x1;
public static final int DOUJINSHI = 0x2;
public static final int MANGA = 0x4;
@@ -178,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;
@@ -188,6 +300,7 @@ public class EhConfig implements Cloneable {
public static final int NAMESPACES_MALE = 0x40;
public static final int NAMESPACES_FEMALE = 0x80;
public static final String JAPANESE_ORIGINAL = "0";
public static final String JAPANESE_TRANSLATED = "1024";
public static final String JAPANESE_REWRITE = "2048";
public static final String ENGLISH_ORIGINAL = "1";
@@ -239,6 +352,15 @@ public class EhConfig implements Cloneable {
public static final String OTHER_TRANSLATED = "1279";
public static final String OTHER_REWRITE = "2303";
/**
* Sort favorites by last gallery update time
*/
private static final String FAVORITES_SORT_GALLERY_UPDATE_TIME = "p";
/**
* Sort favorites by favorited time
*/
private static final String FAVORITES_SORT_FAVORITED_TIME = "f";
/**
* 25 results per page for the index/search page and torrent search pages
*/
@@ -412,6 +534,14 @@ public class EhConfig implements Cloneable {
*/
public String loadFromHAH = LOAD_FROM_HAH_YES;
/**
* Image Size<br/>
* key: {@link #KEY_IMAGE_SIZE}<br/>
* value: {@link #IMAGE_SIZE_AUTO}, {@link #IMAGE_SIZE_780X}, {@link #IMAGE_SIZE_980X},
* {@link #IMAGE_SIZE_1280X}, {@link #IMAGE_SIZE_1600X}, {@link #IMAGE_SIZE_2400X}
*/
public String imageSize = IMAGE_SIZE_AUTO;
/**
* Scale width<br/>
* key: {@link #KEY_SCALE_WIDTH}<br/>
@@ -426,6 +556,13 @@ public class EhConfig implements Cloneable {
*/
public int scaleHeight = 0;
/**
* Gallery title<br/>
* key: {@link #KEY_GALLERY_TITLE}<br/>
* value: {@link #GALLERY_TITLE_DEFAULT}, {@link #GALLERY_TITLE_JAPANESE}
*/
public String galleryTitle = GALLERY_TITLE_DEFAULT;
/**
* The default behavior for downloading an archiver<br/>
* key: {@link #KEY_ARCHIVER_DOWNLOAD}<br/>
@@ -442,6 +579,13 @@ public class EhConfig implements Cloneable {
*/
public String layoutMode = LAYOUT_MODE_LIST;
/**
* Show popular or not<br/>
* key: {@link #KEY_POPULAR}<br/>
* value: {@link #POPULAR_YES}, {@link #POPULAR_NO}
*/
public String popular = POPULAR_YES;
/**
* Default categories on the front page<br/>
* key: {@link #KEY_DEFAULT_CATEGORIES}<br/>
@@ -450,6 +594,13 @@ public class EhConfig implements Cloneable {
*/
public int defaultCategories = 0;
/**
* <br/>
* key: {@link #KEY_FAVORITES_SORT}<br/>
* value: {@link #FAVORITES_SORT_GALLERY_UPDATE_TIME}, {@link #FAVORITES_SORT_FAVORITED_TIME}
*/
public String favoritesSort = FAVORITES_SORT_FAVORITED_TIME;
/**
* Certain namespaces excluded from a default tag search<br/>
* key: {@link #KEY_EXCLUDED_NAMESPACES}<br/>
@@ -628,11 +779,15 @@ public class EhConfig implements Cloneable {
hahClientIp + "%3A" + hahClientPort : "";
String hahClientPasskey = null == this.hahClientPasskey ? "" : this.hahClientPasskey;
mUconfig = KEY_LOAD_FROM_HAH + "_" + loadFromHAH + "-" +
KEY_IMAGE_SIZE + "_" + imageSize + "-" +
KEY_SCALE_WIDTH + "_" + scaleWidth + "-" +
KEY_SCALE_HEIGHT + "_" + scaleHeight + "-" +
KEY_GALLERY_TITLE + "_" + galleryTitle + "-" +
KEY_ARCHIVER_DOWNLOAD + "_" + archiverDownload + "-" +
KEY_LAYOUT_MODE + "_" + layoutMode + "-" +
KEY_POPULAR + "_" + popular + "-" +
KEY_DEFAULT_CATEGORIES + "_" + defaultCategories + "-" +
KEY_FAVORITES_SORT + "_" + favoritesSort + "-" +
KEY_EXCLUDED_NAMESPACES + "_" + excludedNamespaces + "-" +
KEY_EXCLUDED_LANGUAGES + "_" + excludedLanguages + "-" +
KEY_RESULT_COUNT + "_" + resultCount + "-" +
@@ -16,7 +16,9 @@
package com.hippo.ehviewer.client;
import com.hippo.okhttp.CookieDBStore;
import android.content.Context;
import com.hippo.network.CookieRepository;
import java.util.ArrayList;
import java.util.Collections;
@@ -24,36 +26,45 @@ import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
import okhttp3.Request;
public class EhCookieStore extends CookieDBStore {
public class EhCookieStore extends CookieRepository {
public static final String KEY_IPD_MEMBER_ID = "ipb_member_id";
public static final String KEY_IPD_PASS_HASH = "ipb_pass_hash";
public static final String KEY_IGNEOUS = "igneous";
public static final Cookie sTipsCookie =
new Cookie.Builder()
.name(EhConfig.KEY_CONTENT_WARNING)
.value(EhConfig.CONTENT_WARNING_NOT_SHOW)
.domain(EhUrl.DOMAIN_G)
.domain(EhUrl.DOMAIN_E)
.path("/")
.expiresAt(Long.MAX_VALUE)
.build();
public EhCookieStore(Context context) {
super(context, "okhttp3-cookie.db");
}
public void signOut() {
removeAll();
clear();
}
public boolean hasSignedIn() {
return contain(EhUrl.DOMAIN_EX, KEY_IPD_MEMBER_ID) &&
contain(EhUrl.DOMAIN_EX, KEY_IPD_PASS_HASH);
HttpUrl url = HttpUrl.parse(EhUrl.HOST_E);
return contains(url, KEY_IPD_MEMBER_ID) &&
contains(url, KEY_IPD_PASS_HASH);
}
public static Cookie newCookie(Cookie cookie, String newDomain, boolean forcePersistent, boolean forceNotHostOnly) {
public static Cookie newCookie(Cookie cookie, String newDomain, boolean forcePersistent,
boolean forceLongLive, boolean forceNotHostOnly) {
Cookie.Builder builder = new Cookie.Builder();
builder.name(cookie.name());
builder.value(cookie.value());
if (cookie.persistent()) {
if (forceLongLive) {
builder.expiresAt(Long.MAX_VALUE);
} else if (cookie.persistent()) {
builder.expiresAt(cookie.expiresAt());
} else if (forcePersistent) {
builder.expiresAt(Long.MAX_VALUE);
@@ -74,64 +85,29 @@ public class EhCookieStore extends CookieDBStore {
}
@Override
public List<Cookie> loadForRequest(HttpUrl url, Request request) {
List<Cookie> cookies = super.loadForRequest(url, request);
Object tag = request.tag();
String host = url.host();
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = super.loadForRequest(url);
boolean checkTips = domainMatch(host, EhUrl.DOMAIN_G);
boolean checkUconfig = (domainMatch(host, EhUrl.DOMAIN_E) || domainMatch(host, EhUrl.DOMAIN_EX)) && tag instanceof EhConfig;
boolean checkTips = domainMatch(url, EhUrl.DOMAIN_E);
if (checkTips || checkUconfig) {
if (checkTips) {
List<Cookie> result = new ArrayList<>(cookies.size() + 1);
// Add all but skip some
for (Cookie cookie: cookies) {
String name = cookie.name();
if (checkTips && EhConfig.KEY_CONTENT_WARNING.equals(name)) {
if (EhConfig.KEY_CONTENT_WARNING.equals(name)) {
continue;
}
if (checkUconfig && EhConfig.KEY_UCONFIG.equals(name)) {
if (EhConfig.KEY_UCONFIG.equals(name)) {
continue;
}
result.add(cookie);
}
// Add some
if (checkTips) {
result.add(sTipsCookie);
}
if (checkUconfig) {
EhConfig ehConfig = (EhConfig) tag;
Cookie uconfigCookie = new Cookie.Builder()
.name(EhConfig.KEY_UCONFIG)
.value(ehConfig.uconfig())
.domain(host)
.path("/")
.expiresAt(Long.MAX_VALUE)
.build();
result.add(uconfigCookie);
}
result.add(sTipsCookie);
return Collections.unmodifiableList(result);
} else {
return cookies;
}
}
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
List<Cookie> result = new ArrayList<>(cookies.size() + 2);
for (Cookie cookie: cookies) {
if (EhUrl.DOMAIN_E.equals(cookie.domain())) {
// Save id and hash for exhentai
if (KEY_IPD_MEMBER_ID.equals(cookie.name()) ||
KEY_IPD_PASS_HASH.equals(cookie.name())) {
result.add(newCookie(cookie, EhUrl.DOMAIN_EX, false, false));
}
}
result.add(cookie);
}
super.saveFromResponse(url, Collections.unmodifiableList(result));
}
}
@@ -0,0 +1,90 @@
/*
* Copyright 2018 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;
/*
* Created by Hippo on 2018/3/23.
*/
import android.content.Context;
import com.hippo.ehviewer.EhApplication;
import com.hippo.ehviewer.Hosts;
import com.hippo.ehviewer.Settings;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Dns;
public class EhDns implements Dns {
private static final Map<String, InetAddress> builtInHosts;
static {
Map<String, InetAddress> map = new HashMap<>();
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;
}
private static void put(Map<String, InetAddress> map, String host, String ip) {
InetAddress address = Hosts.toInetAddress(host, ip);
if (address != null) {
map.put(host, address);
}
}
private final Hosts hosts;
public EhDns(Context context) {
hosts = EhApplication.getHosts(context);
}
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
if (hostname == null) throw new UnknownHostException("hostname == null");
InetAddress inetAddress = hosts.get(hostname);
if (inetAddress != null) {
return Collections.singletonList(inetAddress);
}
if (Settings.getBuiltInHosts()) {
inetAddress = builtInHosts.get(hostname);
if (inetAddress != null) {
return Collections.singletonList(inetAddress);
}
}
try {
return Arrays.asList(InetAddress.getAllByName(hostname));
} catch (NullPointerException e) {
UnknownHostException unknownHostException =
new UnknownHostException("Broken system behaviour for dns lookup of " + hostname);
unknownHostException.initCause(e);
throw unknownHostException;
}
}
}
@@ -16,50 +16,44 @@
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;
import com.hippo.ehviewer.client.exception.CancelledException;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.exception.NoHAtHClientException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.ArchiveParser;
import com.hippo.ehviewer.client.parser.FavoritesParser;
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;
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.ReadableTime;
import com.hippo.util.ExceptionUtils;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Headers;
@@ -69,6 +63,11 @@ import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class EhEngine {
@@ -78,44 +77,21 @@ public class EhEngine {
private static final String SAD_PANDA_TYPE = "image/gif";
private static final String SAD_PANDA_LENGTH = "9615";
private static final String KOKOMADE_URL = "https://exhentai.org/img/kokomade.jpg";
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
private static final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
private static final Pattern PATTERN_NEED_HATH_CLIENT = Pattern.compile("(You must have a H@H client assigned to your account to use this feature\\.)");
public static EhFilter sEhFilter;
public static void initialize() {
sEhFilter = EhFilter.getInstance();
}
private static void saveParseErrorBody(ParseException e) {
File dir = AppConfig.getExternalParseErrorDir();
if (null == dir) {
return;
}
File file = new File(dir, ReadableTime.getFilenamableTime(System.currentTimeMillis()) + ".txt");
OutputStream os = null;
try {
os = new FileOutputStream(file);
String message = e.getMessage();
String body = e.getBody();
if (null != message) {
os.write(message.getBytes("utf-8"));
os.write('\n');
}
if (null != body) {
os.write(body.getBytes("utf-8"));
}
os.flush();
} catch (IOException e1) {
// Ignore
} finally {
IOUtils.closeQuietly(os);
}
}
private static void throwException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Exception e) throws Exception {
private static void doThrowException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Throwable e) throws Throwable {
if (call.isCanceled()) {
throw new CancelledException();
}
@@ -127,12 +103,19 @@ public class EhEngine {
throw new EhException("Sad Panda");
}
// Check kokomade
if (body != null && body.contains(KOKOMADE_URL)) {
throw new EhException("今回はここまで\n\n" + GetText.getString(R.string.kokomade_tip));
}
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()) {
saveParseErrorBody((ParseException) e);
AppConfig.saveParseErrorBody((ParseException) e);
}
throw new EhException(GetText.getString(R.string.error_parse_error));
}
@@ -141,10 +124,24 @@ public class EhEngine {
if (code >= 400) {
throw new StatusCodeException(code);
}
if (e != null) {
throw e;
}
}
private static void throwException(Call call, int code, @Nullable Headers headers,
@Nullable String body, Throwable e) throws Throwable {
try {
doThrowException(call, code, headers, body, e);
} catch (Throwable error) {
error.printStackTrace();
throw error;
}
}
public static String signIn(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String username, String password) throws Exception {
String username, String password) throws Throwable {
FormBody.Builder builder = new FormBody.Builder()
.add("UserName", username)
.add("PassWord", password)
@@ -152,8 +149,10 @@ public class EhEngine {
.add("CookieDate", "1")
.add("temporary_https", "off");
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);
@@ -172,16 +171,71 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return SignInParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
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);
// Thumbnail mode need filter uploader again
if (!sEhFilter.filterUploader(info) || !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 Exception {
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
@@ -199,50 +253,27 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = GalleryListParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
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 && (Settings.getShowJpnTitle() || 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--;
}
}
}
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 Exception {
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();
}
}
@@ -250,7 +281,7 @@ public class EhEngine {
}
private static void doFillGalleryListByApi(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
List<GalleryInfo> galleryInfoList) throws Exception {
List<GalleryInfo> galleryInfoList, String referer) throws Throwable {
JSONObject json = new JSONObject();
json.put("method", "gdata");
JSONArray ja = new JSONArray();
@@ -264,8 +295,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);
@@ -284,16 +316,18 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
GalleryApiParser.parse(body, galleryInfoList);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static GalleryDetail getGalleryDetail(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Exception {
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
@@ -310,7 +344,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return GalleryDetailParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -318,9 +353,10 @@ public class EhEngine {
public static Pair<PreviewSet, Integer> getPreviewSet(
@Nullable EhClient.Task task, OkHttpClient okHttpClient, String url) throws Exception {
@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
@@ -338,7 +374,8 @@ public class EhEngine {
body = response.body().string();
return Pair.create(GalleryDetailParser.parsePreviewSet(body),
GalleryDetailParser.parsePreviewPages(body));
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -346,7 +383,7 @@ public class EhEngine {
public static RateGalleryParser.Result rateGallery(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, long apiUid, String apiKey, long gid,
String token, float rating) throws Exception {
String token, float rating) throws Throwable {
final JSONObject json = new JSONObject();
json.put("method", "rategallery");
json.put("apiuid", apiUid);
@@ -356,8 +393,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);
@@ -376,19 +415,25 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return RateGalleryParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static GalleryComment[] commentGallery(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url, String comment) throws Exception {
FormBody.Builder builder = new FormBody.Builder()
.add("commenttext", comment)
.add("postcomment", "Post New");
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);
@@ -407,23 +452,32 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
Document document = Jsoup.parse(body);
Elements elements = document.select("#chd + p");
if (elements.size() > 0) {
throw new EhException(elements.get(0).text());
}
return GalleryDetailParser.parseComments(document);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static String getGalleryToken(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long gid, String gtoken, int page) throws Exception {
long gid, String gtoken, int page) throws Throwable {
JSONObject json = new JSONObject()
.put("method", "gtoken")
.put("pagelist", new JSONArray().put(
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);
@@ -442,16 +496,18 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return GalleryTokenApiParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static FavoritesParser.Result getFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url, boolean callApi) throws Exception {
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
@@ -469,14 +525,13 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = FavoritesParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
if (callApi && result.galleryInfoList.size() > 0) {
fillGalleryListByApi(task, okHttpClient, result.galleryInfoList);
}
fillGalleryList(task, okHttpClient, result.galleryInfoList, url, false);
return result;
}
@@ -486,7 +541,7 @@ public class EhEngine {
* @param note max 250 characters
*/
public static Void addFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long gid, String token, int dstCat, String note) throws Exception {
long gid, String token, int dstCat, String note) throws Throwable {
String catStr;
if (dstCat == -1) {
catStr = "favdel";
@@ -500,9 +555,11 @@ public class EhEngine {
builder.add("favnote", note != null ? note : "");
// submit=Add+to+Favorites is not necessary, just use submit=Apply+Changes all the time
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);
@@ -521,7 +578,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
throwException(call, code, headers, body, null);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -530,8 +588,8 @@ public class EhEngine {
}
public static Void addFavoritesRange(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long[] gidArray, String[] tokenArray, int dstCat) throws Exception {
AssertUtils.assertEqualsEx(gidArray.length, tokenArray.length);
long[] gidArray, String[] tokenArray, int dstCat) throws Throwable {
AssertUtils.assertEquals(gidArray.length, tokenArray.length);
for (int i = 0, n = gidArray.length; i < n; i++) {
addFavorites(task, okHttpClient, gidArray[i], tokenArray[i], dstCat, null);
}
@@ -539,7 +597,7 @@ public class EhEngine {
}
public static FavoritesParser.Result modifyFavorites(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url, long[] gidArray, int dstCat, boolean callApi) throws Exception {
String url, long[] gidArray, int dstCat, boolean callApi) throws Throwable {
String catStr;
if (dstCat == -1) {
catStr = "delete";
@@ -554,8 +612,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);
@@ -575,22 +634,22 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = FavoritesParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
if (callApi && result.galleryInfoList.size() > 0) {
fillGalleryListByApi(task, okHttpClient, result.galleryInfoList);
}
fillGalleryList(task, okHttpClient, result.galleryInfoList, url, false);
return result;
}
public static Pair<String, String>[] getTorrentList(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
String url) throws Exception {
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
@@ -608,7 +667,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = TorrentParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -616,11 +676,11 @@ public class EhEngine {
return result;
}
public static List<GalleryInfo> getWhatsHot(@Nullable EhClient.Task task,
OkHttpClient okHttpClient) throws Exception {
String url = EhUrl.HOST_G;
public static Pair<String, Pair<String, String>[]> getArchiveList(@Nullable EhClient.Task task, 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
@@ -630,31 +690,74 @@ public class EhEngine {
String body = null;
Headers headers = null;
List<GalleryInfo> list;
Pair<String, Pair<String, String>[]> result;
int code = -1;
try {
Response response = call.execute();
code = response.code();
headers = response.headers();
body = response.body().string();
list = WhatsHotParser.parse(body);
} catch (Exception e) {
result = ArchiveParser.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);
return result;
}
public static Void downloadArchive(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long gid, String token, String or, String res) throws Throwable {
if (or == null || or.length() == 0) {
throw new EhException("Invalid form param or: " + or);
}
if (res == null || res.length() == 0) {
throw new EhException("Invalid res: " + res);
}
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, referer, origin)
.post(builder.build())
.build();
Call call = okHttpClient.newCall(request);
// Put call
if (null != task) {
task.setCall(call);
}
return list;
String body = null;
Headers headers = null;
int code = -1;
try {
Response response = call.execute();
code = response.code();
headers = response.headers();
body = response.body().string();
throwException(call, code, headers, body, null);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
Matcher m = PATTERN_NEED_HATH_CLIENT.matcher(body);
if (m.find()) {
throw new NoHAtHClientException("No H@H client");
}
return null;
}
private static ProfileParser.Result getProfileInternal(@Nullable EhClient.Task task,
OkHttpClient okHttpClient, String url) throws Exception {
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
@@ -671,17 +774,18 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return ProfileParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static ProfileParser.Result getProfile(@Nullable EhClient.Task task,
OkHttpClient okHttpClient) throws Exception {
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
@@ -697,15 +801,16 @@ public class EhEngine {
code = response.code();
headers = response.headers();
body = response.body().string();
return getProfileInternal(task, okHttpClient, ForumsParser.parse(body));
} catch (Exception e) {
return getProfileInternal(task, okHttpClient, ForumsParser.parse(body), url);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
}
public static VoteCommentParser.Result voteComment(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
long apiUid, String apiKey, long gid, String token, long commentId, int commentVote) throws Exception {
long apiUid, String apiKey, long gid, String token, long commentId, int commentVote) throws Throwable {
final JSONObject json = new JSONObject();
json.put("method", "votecomment");
json.put("apiuid", apiUid);
@@ -716,8 +821,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);
@@ -736,7 +843,8 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
return VoteCommentParser.parse(body, commentVote);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
throw e;
}
@@ -746,7 +854,7 @@ public class EhEngine {
* @param image Must be jpeg
*/
public static GalleryListParser.Result imageSearch(@Nullable EhClient.Task task, OkHttpClient okHttpClient,
File image, boolean uss, boolean osc, boolean se) throws Exception {
File image, boolean uss, boolean osc, boolean se) throws Throwable {
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addPart(
@@ -776,8 +884,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);
@@ -800,37 +910,84 @@ public class EhEngine {
headers = response.headers();
body = response.body().string();
result = GalleryListParser.parse(body);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
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 && (Settings.getShowJpnTitle() || 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--;
}
}
}
fillGalleryList(task, okHttpClient, result.galleryInfoList, url, true);
return result;
}
public static GalleryPageParser.Result getGalleryPage(@Nullable EhClient.Task task,
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, referer).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 GalleryPageParser.parse(body);
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throwException(call, code, headers, body, e);
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;
}
}
}
@@ -92,6 +92,8 @@ public final class EhFilter {
}
public synchronized void addFilter(Filter filter) {
// enable filter by default before it is added to database
filter.enable = true;
EhDB.addFilter(filter);
switch (filter.mode) {
@@ -116,6 +118,10 @@ public final class EhFilter {
}
}
public synchronized void triggerFilter(Filter filter) {
EhDB.triggerFilter(filter);
}
public synchronized void deleteFilter(Filter filter) {
EhDB.deleteFilter(filter);
@@ -138,7 +144,7 @@ public final class EhFilter {
}
}
public synchronized boolean needCallApi() {
public synchronized boolean needTags() {
return 0 != mTagFilterList.size() || 0 != mTagNamespaceFilterList.size();
}
@@ -151,9 +157,8 @@ 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 (title.contains(filters.get(i).text)) {
if (filters.get(i).enable && title.toLowerCase().contains(filters.get(i).text)) {
return false;
}
}
@@ -172,7 +177,7 @@ public final class EhFilter {
List<Filter> filters = mUploaderFilterList;
if (null != uploader && filters.size() > 0) {
for (int i = 0, n = filters.size(); i < n; i++) {
if (uploader.equals(filters.get(i).text)) {
if (filters.get(i).enable && uploader.equals(filters.get(i).text)) {
return false;
}
}
@@ -229,7 +234,7 @@ public final class EhFilter {
if (null != tags && filters.size() > 0) {
for (String tag: tags) {
for (int i = 0, n = filters.size(); i < n; i++) {
if (matchTag(tag, filters.get(i).text)) {
if (filters.get(i).enable && matchTag(tag, filters.get(i).text)) {
return false;
}
}
@@ -264,7 +269,7 @@ public final class EhFilter {
if (null != tags && filters.size() > 0) {
for (String tag: tags) {
for (int i = 0, n = filters.size(); i < n; i++) {
if (matchTagNamespace(tag, filters.get(i).text)) {
if (filters.get(i).enable && matchTagNamespace(tag, 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,35 +16,60 @@
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;
import java.util.ListIterator;
import okhttp3.HttpUrl;
public class EhUrl {
public static final int SITE_G = 0;
public static final int SITE_E = 0;
public static final int SITE_EX = 1;
public static final String DOMAIN_EX = "exhentai.org";
public static final String DOMAIN_E = "e-hentai.org";
public static final String DOMAIN_G = "g.e-hentai.org";
public static final String DOMAIN_LOFI = "lofi.e-hentai.org";
public static final String HOST_EX = "http://" + DOMAIN_EX + "/";
public static final String HOST_G = "http://" + DOMAIN_G + "/";
public static final String HOST_EX = "https://" + DOMAIN_EX + "/";
public static final String HOST_E = "https://" + DOMAIN_E + "/";
public static final String API_SIGN_IN = "http://forums.e-hentai.org/index.php?act=Login&CODE=01";
public static final String API_SIGN_IN = "https://forums.e-hentai.org/index.php?act=Login&CODE=01";
public static final String API_G = HOST_G + "api.php";
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_SIGN_IN = "http://forums.e-hentai.org/index.php?act=Login";
public static final String URL_REGISTER = "http://forums.e-hentai.org/index.php?act=Reg&CODE=00";
public static final String URL_FAVORITES_G = HOST_G + "favorites.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";
public static final String URL_SIGN_IN = "https://forums.e-hentai.org/index.php?act=Login";
public static final String URL_REGISTER = "https://forums.e-hentai.org/index.php?act=Reg&CODE=00";
public static final String URL_FAVORITES_E = HOST_E + "favorites.php";
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 REFERER_EX = "https://" + DOMAIN_EX;
public static final String REFERER_E = "https://" + DOMAIN_E;
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) {
return getGalleryDetailUrl(gid, token, 0, false);
}
@@ -52,8 +77,8 @@ public class EhUrl {
public static String getHost() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return HOST_G;
case SITE_E:
return HOST_E;
case SITE_EX:
return HOST_EX;
}
@@ -62,8 +87,8 @@ public class EhUrl {
public static String getFavoritesUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return URL_FAVORITES_G;
case SITE_E:
return URL_FAVORITES_E;
case SITE_EX:
return URL_FAVORITES_EX;
}
@@ -72,13 +97,53 @@ public class EhUrl {
public static String getApiUrl() {
switch (Settings.getGallerySite()) {
default:
case SITE_G:
return API_G;
case SITE_E:
return API_E;
case SITE_EX:
return API_EX;
}
}
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 URL_UCONFIG_E;
case SITE_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;
}
}
public static String getGalleryDetailUrl(long gid, String token, int index, boolean allComment) {
UrlBuilder builder = new UrlBuilder(getHost() + "g/" + gid + '/' + token + '/');
if (index != 0) {
@@ -98,18 +163,84 @@ public class EhUrl {
return getHost() + "gallerypopups.php?gid=" + gid + "&t=" + token + "&act=addfav";
}
public static String getDownloadArchive(long gid, String token, String or) {
return getHost() + "archiver.php?gid=" + gid + "&token=" + token + "&or=" + or;
}
public static String getTagDefinitionUrl(String tag) {
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()) {
default:
case SITE_G:
return "http://ul.e-hentai.org/image_lookup.php";
case SITE_E:
return URL_IMAGE_SEARCH_E;
case SITE_EX:
return "http://ul.exhentai.org/image_lookup.php";
return URL_IMAGE_SEARCH_EX;
}
}
@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:
//case SITE_E:
return URL_PREFIX_THUMB_E;
//case SITE_EX:
// return URL_PREFIX_THUMB_EX;
}
}
public static String getFixedPreviewThumbUrl(String originUrl) {
HttpUrl url = HttpUrl.parse(originUrl);
if (url == null) return originUrl;
List<String> pathSegments = url.pathSegments();
if (pathSegments == null || pathSegments.size() < 3) return originUrl;
ListIterator<String> iterator = pathSegments.listIterator(pathSegments.size());
// The last segments, like
// 317a1a254cd9c3269e71b2aa2671fe8d28c91097-260198-640-480-png_250.jpg
if (!iterator.hasPrevious()) return originUrl;
String lastSegment = iterator.previous();
// The second last segments, like
// 7a
if (!iterator.hasPrevious()) return originUrl;
String secondLastSegment = iterator.previous();
// The third last segments, like
// 31
if (!iterator.hasPrevious()) return originUrl;
String thirdLastSegment = iterator.previous();
// Check path segments
if (lastSegment != null && secondLastSegment != null
&& thirdLastSegment != null
&& lastSegment.startsWith(thirdLastSegment)
&& lastSegment.startsWith(secondLastSegment, thirdLastSegment.length())) {
return getThumbUrlPrefix() + thirdLastSegment + "/" + secondLastSegment + "/" + lastSegment;
} else {
return originUrl;
}
}
}
@@ -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" },
@@ -168,4 +166,31 @@ public class EhUtils {
return title;
}
}
public static String handleThumbUrlResolution(String url) {
if (null == url) {
return null;
}
String resolution;
switch (Settings.getThumbResolution()) {
default:
case 0: // Auto
return url;
case 1: // 250
resolution = "250";
break;
case 2: // 300
resolution = "300";
break;
}
int index1 = url.lastIndexOf('_');
int index2 = url.lastIndexOf('.');
if (index1 >= 0 && index2 >= 0 && index1 < index2) {
return url.substring(0, index1 + 1) + resolution + url.substring(index2);
} else {
return url;
}
}
}
@@ -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,12 +24,16 @@ 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;
public String comment;
public long lastEdited;
@Override
public int describeContents() {
@@ -40,12 +44,16 @@ 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);
dest.writeString(this.comment);
dest.writeLong(this.lastEdited);
}
public GalleryComment() {
@@ -54,12 +62,16 @@ 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();
this.comment = in.readString();
this.lastEdited = in.readLong();
}
public static final Creator<GalleryComment> CREATOR = new Creator<GalleryComment>() {
@@ -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];
}
};
}
@@ -27,6 +27,7 @@ public class GalleryDetail extends GalleryInfo {
public String apiKey;
public int torrentCount;
public String torrentUrl;
public String archiveUrl;
public String parent;
public String visible;
public String language;
@@ -36,7 +37,7 @@ 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;
@@ -50,6 +51,7 @@ public class GalleryDetail extends GalleryInfo {
super.writeToParcel(dest, flags);
dest.writeInt(this.torrentCount);
dest.writeString(this.torrentUrl);
dest.writeString(this.archiveUrl);
dest.writeString(this.parent);
dest.writeString(this.visible);
dest.writeString(this.language);
@@ -58,8 +60,8 @@ 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);
}
@@ -71,6 +73,7 @@ public class GalleryDetail extends GalleryInfo {
super(in);
this.torrentCount = in.readInt();
this.torrentUrl = in.readString();
this.archiveUrl = in.readString();
this.parent = in.readString();
this.visible = in.readString();
this.language = in.readString();
@@ -85,12 +88,7 @@ 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());
}
@@ -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,20 +61,38 @@ public class GalleryInfo implements Parcelable {
};
public static final Pattern[] S_LANG_PATTERNS = {
Pattern.compile("[(\\[]eng(?:lish)?[)\\]]", Pattern.CASE_INSENSITIVE),
Pattern.compile("[((\\[]ch(?:inese)?[))\\]]|[汉漢]化|中[国國][语語]|中文", 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("[(\\[]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),
};
public static final String[] S_LANG_TAGS = {
"language:english",
"language:chinese",
"language:spanish",
"language:korean",
"language:russian",
"language:french",
"language:portuguese",
"language:thai",
"language:german",
"language:italian",
"language:vietnamese",
"language:polish",
"language:hungarian",
"language:dutch",
};
public long gid ;
@@ -87,8 +104,10 @@ public class GalleryInfo implements Parcelable {
public String posted;
public String uploader;
public float rating;
public boolean rated;
@Nullable
public String[] simpleTags;
public int pages;
public int thumbWidth;
public int thumbHeight;
@@ -102,7 +121,30 @@ public class GalleryInfo implements Parcelable {
*/
public String simpleLanguage;
public int favoriteSlot = -2;
public String favoriteName;
public final void generateSLang() {
if (simpleTags != null) {
generateSLangFromTags();
}
if (simpleLanguage == null && title != null) {
generateSLangFromTitle();
}
}
private void generateSLangFromTags() {
for (String tag : simpleTags) {
for (int i = 0; i < S_LANGS.length; i++) {
if (S_LANG_TAGS[i].equals(tag)) {
simpleLanguage = S_LANGS[i];
return;
}
}
}
}
private void generateSLangFromTitle() {
for (int i = 0; i < S_LANGS.length; i++) {
if (S_LANG_PATTERNS[i].matcher(title).find()) {
simpleLanguage = S_LANGS[i];
@@ -128,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);
@@ -135,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() {}
@@ -149,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();
@@ -156,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>() {
@@ -21,7 +21,7 @@ import android.os.Parcelable;
import com.hippo.ehviewer.client.EhCacheKeyFactory;
import com.hippo.widget.LoadImageView;
import com.hippo.yorozuya.IntList;
import com.hippo.yorozuya.collect.IntList;
import java.util.ArrayList;
@@ -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;
@@ -19,7 +19,7 @@ package com.hippo.ehviewer.client.data;
import android.os.Parcel;
import com.hippo.widget.LoadImageView;
import com.hippo.yorozuya.IntList;
import com.hippo.yorozuya.collect.IntList;
import java.util.ArrayList;
@@ -21,4 +21,8 @@ public class EhException extends Exception {
public EhException(String detailMessage) {
super(detailMessage);
}
public EhException(String detailMessage, Throwable cause) {
super(detailMessage, cause);
}
}
@@ -14,11 +14,12 @@
* limitations under the License.
*/
package com.hippo.util;
package com.hippo.ehviewer.client.exception;
import android.os.Build;
public class NoHAtHClientException extends EhException {
public final class ApiHelper {
public NoHAtHClientException(String detailMessage) {
super(detailMessage);
}
public static final boolean SUPPORT_TRANSITION = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
@@ -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;
}
@@ -0,0 +1,48 @@
/*
* 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 android.util.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ArchiveParser {
private static final Pattern PATTERN_FORM = Pattern.compile("<form id=\"hathdl_form\" action=\"[^\"]*?or=([^=\"]*?)\" method=\"post\">");
private static final Pattern PATTERN_ARCHIVE = Pattern.compile("<a href=\"[^\"]*\" onclick=\"return do_hathdl\\('([0-9]+|org)'\\)\">([^<]+)</a>");
@SuppressWarnings("unchecked")
public static Pair<String, Pair<String, String>[]> parse(String body) {
Matcher m = PATTERN_FORM.matcher(body);
if (!m.find()) {
return new Pair<String, Pair<String, String>[]>("", new Pair[0]);
}
String paramOr = m.group(1);
List<Pair<String, String>> archiveList = new ArrayList<>();
m = PATTERN_ARCHIVE.matcher(body);
while (m.find()) {
String res = ParserUtils.trim(m.group(1));
String name = ParserUtils.trim(m.group(2));
Pair<String, String> item = new Pair<>(res, name);
archiveList.add(item);
}
return new Pair<String, Pair<String, String>[]>(paramOr, archiveList.toArray(new Pair[archiveList.size()]));
}
}
@@ -21,22 +21,22 @@ import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import com.hippo.util.JsoupUtils;
import com.hippo.yorozuya.AssertUtils;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.List;
public class FavoritesParser {
public static class Result {
public String[] catArray; // Size 10
public int[] countArray; // Size 10
public int pages;
public int nextPage;
public List<GalleryInfo> galleryInfoList;
}
@@ -53,14 +53,15 @@ public class FavoritesParser {
//noinspection ConstantConditions
Elements fps = ido.getElementsByClass("fp");
// Last one is "fp fps"
AssertUtils.assertEqualsEx(11, fps.size());
AssertUtils.assertEquals(11, fps.size());
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 (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
throw new ParseException("Parse favorites error", body);
}
@@ -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;
@@ -18,7 +18,7 @@ package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
@@ -31,7 +31,8 @@ public class ForumsParser {
Element userlinks = d.getElementById("userlinks");
Element child = userlinks.child(0).child(0).child(0);
return child.attr("href");
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Parse forums error", body);
}
}
@@ -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;
@@ -41,10 +42,10 @@ public class GalleryApiParser {
gi.title = ParserUtils.trim(g.getString("title"));
gi.titleJpn = ParserUtils.trim(g.getString("title_jpn"));
gi.category = EhUtils.getCategory(g.getString("category"));
gi.thumb = g.getString("thumb");
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,6 +54,8 @@ public class GalleryApiParser {
tags[j] = tagJa.getString(j);
}
gi.simpleTags = tags;
gi.pages = NumberUtils.parseIntSafely(g.getString("filecount"), 0);
gi.generateSLang();
}
}
@@ -16,12 +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;
@@ -31,15 +32,11 @@ import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.ehviewer.client.exception.OffensiveException;
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 org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@@ -50,12 +47,21 @@ import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
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 {
private static final Pattern PATTERN_ERROR = Pattern.compile("<div class=\"d\">\n<p>([^<]+)</p>");
private static final Pattern PATTERN_DETAIL = Pattern.compile("var gid = (\\d+);.+?var token = \"([a-f0-9]+)\";.+?var apiuid = ([\\-\\d]+);.+?var apikey = \"([a-f0-9]+)\";", Pattern.DOTALL);
private static final Pattern PATTERN_TORRENT = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Torrent Download \\( (\\d+) \\)</a>");
private static final Pattern PATTERN_ARCHIVE = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Archive Download</a>");
private static final Pattern PATTERN_COVER = Pattern.compile("width:(\\d+)px; height:(\\d+)px.+?url\\((.+?)\\)");
private static final Pattern PATTERN_TAG_GROUP = Pattern.compile("<tr><td[^<>]+>([\\w\\s]+):</td><td>(?:<div[^<>]+><a[^<>]+>[\\w\\s]+</a></div>)+</td></tr>");
private static final Pattern PATTERN_TAG = Pattern.compile("<div[^<>]+><a[^<>]+>([\\w\\s]+)</a></div>");
private static final Pattern PATTERN_COMMENT = Pattern.compile("<div class=\"c3\">Posted on ([^<>]+) by: &nbsp; <a[^<>]+>([^<>]+)</a>.+?<div class=\"c6\"[^>]*>(.+?)</div><div class=\"c[78]\"");
@@ -65,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);
@@ -107,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()) {
@@ -124,14 +133,22 @@ public class GalleryDetailParser {
gd.torrentUrl = "";
}
matcher = PATTERN_ARCHIVE.matcher(body);
if (matcher.find()) {
gd.archiveUrl = StringUtils.unescapeXml(StringUtils.trim(matcher.group(1)));
} else {
gd.archiveUrl = "";
}
try {
Element gm = JsoupUtils.getElementByClass(d, "gm");
// Thumb url
Element gd1 = gm.getElementById("gd1");
try {
gd.thumb = StringUtils.trim(gd1.child(0).attr("src"));
} catch (Exception e) {
gd.thumb = parseCoverStyle(StringUtils.trim(gd1.child(0).attr("style")));
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
gd.thumb = "";
}
@@ -154,8 +171,13 @@ public class GalleryDetailParser {
// Category
Element gdc = gm.getElementById("gdc");
try {
gd.category = EhUtils.getCategory(gdc.child(0).child(0).attr("alt"));
} catch (Exception e) {
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;
}
@@ -180,7 +202,8 @@ public class GalleryDetailParser {
for (int i = 0, n = es.size(); i < n; i++) {
parseDetailInfo(gd, es.get(i), body);
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
// Ignore
}
@@ -198,7 +221,7 @@ public class GalleryDetailParser {
if (null != rating_label) {
String ratingStr = StringUtils.trim(rating_label.text());
if ("Not Yet Rated".equals(ratingStr)) {
gd.rating = Float.NaN;
gd.rating = -1.0f;
} else {
int index = ratingStr.indexOf(' ');
if (index == -1 || index >= ratingStr.length()) {
@@ -208,17 +231,36 @@ public class GalleryDetailParser {
}
}
} else {
gd.rating = Float.NaN;
gd.rating = -1.0f;
}
// isFavorited
Element gdf = gm.getElementById("gdf");
gd.isFavorited = null != gdf && !StringUtils.trim(gdf.text()).equals("Add to Favorites");
} catch (Exception e) {
if (gdf != null) {
final String favoriteName = StringUtils.trim(gdf.text());
if (favoriteName.equals("Add to Favorites")) {
gd.favoriteName = null;
} else {
gd.favoriteName = StringUtils.trim(gdf.text());
}
}
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Can't parse gallery detail", body);
}
}
// width:250px; height:356px; background:transparent url(https://exhentai.org/t/fe/1f/fe1fcfa9bf8fba2f03982eda0aa347cc9d6a6372-145921-1050-1492-jpg_250.jpg) 0 0 no-repeat
private static String parseCoverStyle(String str) {
Matcher matcher = PATTERN_COVER.matcher(str);
if (matcher.find()) {
return EhUtils.handleThumbUrlResolution(matcher.group(3));
} else {
return "";
}
}
private static void parseDetailInfo(GalleryDetail gd, Element e, String body) {
Elements es = e.children();
if (es.size() < 2) {
@@ -230,7 +272,10 @@ public class GalleryDetailParser {
if (key.startsWith("Posted")) {
gd.posted = value;
} else if (key.startsWith("Parent")) {
gd.parent = value;
Element a = es.get(1).children().first();
if (a != null) {
gd.parent = a.attr("href");
}
} else if (key.startsWith("Visible")) {
gd.visible = value;
} else if (key.startsWith("Language")) {
@@ -280,13 +325,14 @@ public class GalleryDetailParser {
// Sometimes parody tag is followed with '|' and english translate, just remove them
int index = tag.indexOf('|');
if (index >= 0) {
tag = tag.substring(0, index);
tag = tag.substring(0, index).trim();
}
group.addTag(tag);
}
return group.size() > 0 ? group : null;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
return null;
}
@@ -300,16 +346,27 @@ 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);
}
}
return list.toArray(new GalleryTagGroup[list.size()]);
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
return EMPTY_GALLERY_TAG_GROUP_ARRAY;
}
@@ -349,13 +406,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
@@ -374,14 +441,23 @@ public class GalleryDetailParser {
// time
Element c3 = JsoupUtils.getElementByClass(element, "c3");
String temp = c3.ownText();
temp = temp.substring("Posted on ".length(), temp.length() - " by:  ".length());
temp = temp.substring("Posted on ".length(), temp.length() - " by:".length());
comment.time = WEB_COMMENT_DATE_FORMAT.parse(temp).getTime();
// user
comment.user = c3.child(0).text();
// comment
comment.comment = JsoupUtils.getElementByClass(element, "c6").html();
// last edited
Element c8 = JsoupUtils.getElementByClass(element, "c8");
if (c8 != null) {
Element e = c8.children().first();
if (e != null) {
comment.lastEdited = WEB_COMMENT_DATE_FORMAT.parse(temp).getTime();
}
}
return comment;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
return null;
}
@@ -391,7 +467,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");
@@ -403,8 +479,24 @@ public class GalleryDetailParser {
list.add(comment);
}
}
return list.toArray(new GalleryComment[list.size()]);
} catch (Exception e) {
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();
return EMPTY_GALLERY_COMMENT_ARRAY;
}
@@ -443,7 +535,8 @@ public class GalleryDetailParser {
try {
Elements elements = document.getElementsByClass("ptt").first().child(0).child(0).children();
return Integer.parseInt(elements.get(elements.size() - 2).text());
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
throw new ParseException("Can't parse preview pages", body);
}
@@ -456,7 +549,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) {
@@ -470,12 +563,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 {
@@ -511,11 +610,15 @@ public class GalleryDetailParser {
String pageUrl = element.attr("href");
element = element.child(0);
String imageUrl = element.attr("src");
if (Settings.getFixThumbUrl()) {
imageUrl = EhUrl.getFixedPreviewThumbUrl(imageUrl);
}
int index = Integer.parseInt(element.attr("alt")) - 1;
largePreviewSet.addItem(index, imageUrl, pageUrl);
}
return largePreviewSet;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
throw new ParseException("Can't parse large preview", body);
}
@@ -529,8 +632,16 @@ public class GalleryDetailParser {
LargePreviewSet largePreviewSet = new LargePreviewSet();
while (m.find()) {
largePreviewSet.addItem(ParserUtils.parseInt(m.group(2)) - 1,
ParserUtils.trim(m.group(3)), ParserUtils.trim(m.group(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()) {
imageUrl = EhUrl.getFixedPreviewThumbUrl(imageUrl);
}
largePreviewSet.addItem(index, imageUrl, pageUrl);
}
if (largePreviewSet.size() == 0) {
@@ -547,10 +658,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;
@@ -29,20 +28,32 @@ import java.util.regex.Pattern;
*/
public final class GalleryDetailUrlParser {
public static final Pattern URL_PATTERN = Pattern.compile("http://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_G + "|" + EhUrl.DOMAIN_LOFI + ")/g/(\\d+)/(\\w+)");
private static final Pattern URL_STRICT_PATTERN = Pattern.compile(
"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})(?:[^0-9a-f]|$)");
@Nullable
public static Result parse(String url) {
return parse(url, true);
}
@Nullable
public static Result parse(String url, boolean strict) {
if (url == null) {
return null;
}
Matcher m = URL_PATTERN.matcher(url);
Pattern pattern = strict ? URL_STRICT_PATTERN : URL_PATTERN;
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,37 +16,54 @@
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 org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
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;
}
@@ -54,25 +71,25 @@ public class GalleryListParser {
try {
Elements es = d.getElementsByClass("ptt").first().child(0).child(0).children();
return Integer.parseInt(es.get(es.size() - 2).text().trim());
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Can't parse gallery list pages", body);
}
}
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;
@@ -85,95 +102,191 @@ public class GalleryListParser {
return re;
}
@Nullable
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++;
}
}
return -2;
}
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 = 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 = "http://" +StringUtils.replace(html.substring(index1 + 1, index2), "~", "/");
} else {
Log.w(TAG, "Can't parse gallery info thumb url");
gi.thumb = "";
// 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;
}
}
} else {
Log.w(TAG, "Can't parse gallery info thumb");
gi.thumbWidth = 0;
gi.thumbHeight = 0;
gi.thumb = "";
if (a != null) {
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()]);
}
}
// Title (required)
Element it5 = JsoupUtils.getElementByClass(e, "it5");
if (null == it5) {
Log.e(TAG, "Can't parse gallery info title");
if (gi.title == null) {
return null;
}
Elements es = it5.children();
if (null == es || es.size() <= 0) {
Log.e(TAG, "Can't parse gallery info title");
return null;
// Category
gi.category = EhUtils.UNKNOWN;
Element ce = JsoupUtils.getElementByClass(e, "cn");
if (ce == null) {
ce = JsoupUtils.getElementByClass(e, "cs");
}
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");
return null;
if (ce != null) {
gi.category = EhUtils.getCategory(ce.text());
}
gi.gid = result.gid;
gi.token = result.token;
gi.title = a.text().trim();
// 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"));
}
}
}
// 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 it4r = JsoupUtils.getElementByClass(e, "it4r");
if (null != it4r) {
gi.rating = NumberUtils.parseFloatSafely(parseRating(it4r.attr("style")), Float.NaN);
} else {
Log.w(TAG, "Can't parse gallery info rating");
gi.rating = Float.NaN;
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
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 = "";
// 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();
@@ -186,29 +299,59 @@ 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 (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
e.printStackTrace();
throw new ParseException("Can't parse gallery list", body);
}
@@ -29,7 +29,7 @@ import java.net.URLDecoder;
public final class GalleryListUrlParser {
private static final String[] VALID_HOSTS = {EhUrl.DOMAIN_EX, EhUrl.DOMAIN_G, EhUrl.DOMAIN_LOFI};
private static final String[] VALID_HOSTS = {EhUrl.DOMAIN_EX, EhUrl.DOMAIN_E, EhUrl.DOMAIN_LOFI};
private static final String PATH_NORMAL = "/";
private static final String PATH_UPLOADER = "/uploader/";
@@ -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,18 +17,18 @@
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;
public class GalleryPageParser {
private static final Pattern PATTERN_IMAGE_URL = Pattern.compile("<div id=\"i3\"><a[^>]+><img id=\"img\" src=\"([^\"]+)\"");
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("<div id=\"i7\" class=\"if\"> &nbsp; <img[^>]+/> <a href=\"([^\"]+)\">");
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;
@@ -43,12 +43,17 @@ public class GalleryPageParser {
}
m = PATTERN_ORIGIN_IMAGE_URL.matcher(body);
if (m.find()) {
result.originImageUrl = StringUtils.unescapeXml(StringUtils.trim(m.group(1)));
result.originImageUrl = StringUtils.unescapeXml(m.group(1)) + "fullimg.php" + StringUtils.unescapeXml(m.group(2));
}
if (!TextUtils.isEmpty(result.imageUrl) && !TextUtils.isEmpty(result.skipHathKey)) {
m = PATTERN_SHOW_KEY.matcher(body);
if (m.find()) {
result.showKey = m.group(1);
}
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);
}
}
@@ -56,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 androidx.annotation.Nullable;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.yorozuya.NumberUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -26,20 +27,33 @@ import java.util.regex.Pattern;
*/
public final class GalleryPageUrlParser {
public static final Pattern URL_PATTERN = Pattern.compile("http://(?:" +
EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_G + "|" + EhUrl.DOMAIN_LOFI + ")/s/(\\w+)/(\\d+)-(\\d+)");
private static final Pattern URL_STRICT_PATTERN = Pattern.compile(
"https?://(?:" + EhUrl.DOMAIN_EX + "|" + EhUrl.DOMAIN_E + "|" + EhUrl.DOMAIN_LOFI + ")/s/([0-9a-f]{10})/(\\d+)-(\\d+)");
private static final Pattern URL_PATTERN = Pattern.compile(
"([0-9a-f]{10})/(\\d+)-(\\d+)");
@Nullable
public static Result parse(String url) {
return parse(url, true);
}
@Nullable
public static Result parse(String url, boolean strict) {
if (url == null) {
return null;
}
Matcher m = URL_PATTERN.matcher(url);
Pattern pattern = strict ? URL_STRICT_PATTERN : URL_PATTERN;
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;
@@ -17,7 +17,7 @@
package com.hippo.ehviewer.client.parser;
import com.hippo.ehviewer.client.exception.EhException;
import com.hippo.util.ExceptionUtils;
import org.json.JSONObject;
public class GalleryTokenApiParser {
@@ -36,7 +36,8 @@ public class GalleryTokenApiParser {
JSONObject jo = new JSONObject(body).getJSONArray("tokenlist").getJSONObject(0);
try {
return jo.getString("token");
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new EhException(jo.getString("error"));
}
}
@@ -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);
}
}
@@ -18,10 +18,9 @@ package com.hippo.ehviewer.client.parser;
import android.text.TextUtils;
import android.util.Log;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.ExceptionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
@@ -43,11 +42,13 @@ public class ProfileParser {
} else if (!result.avatar.startsWith("http")) {
result.avatar = EhUrl.URL_FORUMS + result.avatar;
}
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
Log.i(TAG, "No avatar");
}
return result;
} catch (Exception e) {
} catch (Throwable e) {
ExceptionUtils.throwIfFatal(e);
throw new ParseException("Parse forums error", body);
}
}
@@ -25,7 +25,7 @@ import java.util.regex.Pattern;
public class TorrentParser {
private static final Pattern PATTERN_TORRENT = Pattern.compile("<td colspan=\"5\"> &nbsp; <a href=\"([^\"]+)\">([^<]+)</a></td>");
private static final Pattern PATTERN_TORRENT = Pattern.compile("<td colspan=\"5\"> &nbsp; <a href=\"([^\"]+)\"[^<]+>([^<]+)</a></td>");
@SuppressWarnings("unchecked")
public static Pair<String, String>[] parse(String body) {
@@ -1,60 +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.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.util.JsoupUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
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 = temp.attr("src");
galleryInfo.title = temp.attr("title");
galleryInfo.generateSLang();
galleryInfoList.add(galleryInfo);
}
return galleryInfoList;
} catch (Exception e) {
throw new ParseException("Parse whats hot error", body);
}
}
}
@@ -16,25 +16,30 @@
package com.hippo.ehviewer.download;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.os.AsyncTask;
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;
import com.hippo.ehviewer.dao.DownloadLabel;
import com.hippo.ehviewer.spider.SpiderDen;
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.LongList;
import com.hippo.yorozuya.MathUtils;
import com.hippo.yorozuya.ObjectUtils;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.sparse.SparseIJArray;
import com.hippo.yorozuya.sparse.SparseJLArray;
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;
import java.util.Comparator;
@@ -289,6 +294,9 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
}
// Make sure download is running
ensureDownload();
// Add it to history
EhDB.putHistoryInfo(info);
}
}
@@ -560,6 +568,52 @@ public class DownloadManager implements SpiderQueen.OnSpiderListener {
for (DownloadInfoListener l: mDownloadInfoListeners) {
l.onReload();
}
// Ensure download
ensureDownload();
}
@SuppressLint("StaticFieldLeak")
public void resetAllReadingProgress() {
LinkedList<DownloadInfo> list = new LinkedList<>(mAllInfoList);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
GalleryInfo galleryInfo = new GalleryInfo();
for (DownloadInfo downloadInfo : list) {
galleryInfo.gid = downloadInfo.gid;
galleryInfo.token = downloadInfo.token;
galleryInfo.title = downloadInfo.title;
galleryInfo.thumb = downloadInfo.thumb;
galleryInfo.category = downloadInfo.category;
galleryInfo.posted = downloadInfo.posted;
galleryInfo.uploader = downloadInfo.uploader;
galleryInfo.rating = downloadInfo.rating;
UniFile downloadDir = SpiderDen.getGalleryDownloadDir(galleryInfo);
if (downloadDir == null) {
continue;
}
UniFile file = downloadDir.findFile(".ehviewer");
if (file == null) {
continue;
}
SpiderInfo spiderInfo = SpiderInfo.read(file);
if (spiderInfo == null) {
continue;
}
spiderInfo.startPage = 0;
try {
spiderInfo.write(file.openOutputStream());
} catch (IOException e) {
Log.e(TAG, "Can't write SpiderInfo", e);
}
}
return null;
}
}.executeOnExecutor(IoThreadPoolExecutor.getInstance());
}
// Update in DB
@@ -16,20 +16,21 @@
package com.hippo.ehviewer.download;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
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;
@@ -40,11 +41,10 @@ import com.hippo.ehviewer.ui.scene.DownloadsScene;
import com.hippo.scene.StageActivity;
import com.hippo.util.ReadableTime;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.LongList;
import com.hippo.yorozuya.SimpleHandler;
import com.hippo.yorozuya.sparse.SparseJBArray;
import com.hippo.yorozuya.sparse.SparseJLArray;
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;
@@ -90,6 +90,8 @@ public class DownloadService extends Service implements DownloadManager.Download
private static int sFinishedCount;
private static int sDownloadedCount;
private String CHANNEL_ID;
public static void clear() {
sFailedCount = 0;
sFinishedCount = 0;
@@ -102,7 +104,12 @@ public class DownloadService extends Service implements DownloadManager.Download
public void onCreate() {
super.onCreate();
CHANNEL_ID = getPackageName()+".download";
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
mNotifyManager.createNotificationChannel(new NotificationChannel(CHANNEL_ID, getString(R.string.download_service),
NotificationManager.IMPORTANCE_LOW));
}
mDownloadManager = EhApplication.getDownloadManager(getApplicationContext());
mDownloadManager.setDownloadListener(this);
}
@@ -208,14 +215,15 @@ public class DownloadService extends Service implements DownloadManager.Download
stopAllIntent.setAction(ACTION_STOP_ALL);
PendingIntent piStopAll = PendingIntent.getService(this, 0, stopAllIntent, 0);
mDownloadingBuilder = new NotificationCompat.Builder(getApplicationContext())
mDownloadingBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setOngoing(true)
.setAutoCancel(false)
.setCategory(NotificationCompat.CATEGORY_PROGRESS)
.setColor(getResources().getColor(R.color.colorPrimary))
.addAction(R.drawable.ic_pause_x24, getString(R.string.stat_download_action_stop_all), piStopAll)
.setShowWhen(false);
.setShowWhen(false)
.setChannelId(CHANNEL_ID);
mDownloadingDelay = new NotificationDelay(this, mNotifyManager, mDownloadingBuilder, ID_DOWNLOADING);
}
@@ -238,14 +246,15 @@ public class DownloadService extends Service implements DownloadManager.Download
PendingIntent piActivity = PendingIntent.getActivity(DownloadService.this, 0,
activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mDownloadedBuilder = new NotificationCompat.Builder(getApplicationContext())
mDownloadedBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_download_done)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle(getString(R.string.stat_download_done_title))
.setDeleteIntent(piClear)
.setOngoing(false)
.setAutoCancel(true)
.setContentIntent(piActivity);
.setContentIntent(piActivity)
.setChannelId(CHANNEL_ID);
mDownloadedDelay = new NotificationDelay(this, mNotifyManager, mDownloadedBuilder, ID_DOWNLOADED);
}
@@ -255,14 +264,15 @@ public class DownloadService extends Service implements DownloadManager.Download
return;
}
m509dBuilder = new NotificationCompat.Builder(getApplicationContext())
m509dBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_alert)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentText(getString(R.string.stat_509_alert_title))
.setContentText(getString(R.string.stat_509_alert_text))
.setAutoCancel(true)
.setOngoing(false)
.setCategory(NotificationCompat.CATEGORY_ERROR);
.setCategory(NotificationCompat.CATEGORY_ERROR)
.setChannelId(CHANNEL_ID);
m509Delay = new NotificationDelay(this, mNotifyManager, m509dBuilder, ID_509);
}
@@ -345,7 +355,9 @@ public class DownloadService extends Service implements DownloadManager.Download
return;
}
mDownloadingDelay.cancel();
if (null != mDownloadingDelay) {
mDownloadingDelay.cancel();
}
ensureDownloadedBuilder();
@@ -443,7 +455,10 @@ public class DownloadService extends Service implements DownloadManager.Download
return;
}
mDownloadingDelay.cancel();
if (null != mDownloadingDelay) {
mDownloadingDelay.cancel();
}
checkStopSelf();
}
@@ -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.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;
class A7ZipArchive implements Closeable {
private InArchive archive;
private A7ZipArchive(InArchive archive) {
this.archive = archive;
}
@Override
public void close() {
archive.close();
}
private static boolean isSupportedFilename(String name) {
for (String extension : GalleryProvider2.SUPPORT_IMAGE_EXTENSIONS) {
if (name.endsWith(extension)) {
return true;
}
}
return false;
}
List<A7ZipArchiveEntry> getArchiveEntries() {
List<A7ZipArchiveEntry> entries = new ArrayList<>();
for (int i = 0, n = archive.getNumberOfEntries(); i < n; i++) {
if (!archive.getEntryBooleanProperty(i, PropID.ENCRYPTED)
&& !archive.getEntryBooleanProperty(i, PropID.IS_DIR)
&& !archive.getEntryBooleanProperty(i, PropID.IS_VOLUME)
&& !archive.getEntryBooleanProperty(i, PropID.SOLID)) {
String path = archive.getEntryPath(i);
if (isSupportedFilename(path.toLowerCase())) {
entries.add(new A7ZipArchiveEntry(archive, i, path));
}
}
}
return entries;
}
static A7ZipArchive create(UniRandomAccessFile file) throws ArchiveException {
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))) {
throw new ArchiveException("Unsupported archive");
}
return new A7ZipArchive(archive);
}
static class A7ZipArchiveEntry {
private InArchive archive;
private int index;
private String path;
private A7ZipArchiveEntry(InArchive archive, int index, String path) {
this.archive = archive;
this.index = index;
this.path = path;
}
String getPath() {
return path;
}
void extract(OutputStream os) throws ArchiveException {
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();
}
}
}
@@ -0,0 +1,281 @@
/*
* 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.gallery;
import android.content.Context;
import android.net.Uri;
import android.os.Process;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.a7zip.ArchiveException;
import com.hippo.ehviewer.GetText;
import com.hippo.ehviewer.R;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.unifile.UniRandomAccessFile;
import com.hippo.util.NaturalComparator;
import com.hippo.yorozuya.thread.PriorityThread;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
public class ArchiveGalleryProvider extends GalleryProvider2 {
private static final AtomicInteger sIdGenerator = new AtomicInteger();
private final UniFile file;
private Thread archiveThread;
private Thread decodeThread;
private volatile int size = STATE_WAIT;
private String error;
private final Stack<Integer> requests = new Stack<>();
private final AtomicInteger extractingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
private final LinkedHashMap<Integer, InputStream> streams = new LinkedHashMap<>();
private final AtomicInteger decodingIndex = new AtomicInteger(GalleryPageView.INVALID_INDEX);
public ArchiveGalleryProvider(Context context, Uri uri) {
file = UniFile.fromUri(context, uri);
}
@Override
public void start() {
super.start();
int id = sIdGenerator.incrementAndGet();
archiveThread = new PriorityThread(
new ArchiveTask(), "ArchiveTask" + '-' + id, Process.THREAD_PRIORITY_BACKGROUND);
archiveThread.start();
decodeThread = new PriorityThread(
new DecodeTask(), "DecodeTask" + '-' + id, Process.THREAD_PRIORITY_BACKGROUND);
decodeThread.start();
}
@Override
public void stop() {
super.stop();
if (archiveThread != null) {
archiveThread.interrupt();
archiveThread = null;
}
if (decodeThread != null) {
decodeThread.interrupt();
decodeThread = null;
}
}
@Override
public int size() {
return size;
}
@Override
protected void onRequest(int index) {
boolean inDecodeTask;
synchronized (streams) {
inDecodeTask = streams.keySet().contains(index) || index == decodingIndex.get();
}
synchronized (requests) {
boolean inArchiveTask = requests.contains(index) || index == extractingIndex.get();
if (!inArchiveTask && !inDecodeTask) {
requests.add(index);
requests.notify();
}
}
notifyPageWait(index);
}
@Override
protected void onForceRequest(int index) {
onRequest(index);
}
@Override
protected void onCancelRequest(int index) {
synchronized (requests) {
requests.remove(Integer.valueOf(index));
}
}
@Override
public String getError() {
return error;
}
@NonNull
@Override
public String getImageFilename(int index) {
// TODO
return Integer.toString(index);
}
@Override
public boolean save(int index, @NonNull UniFile file) {
// TODO
return false;
}
@Nullable
@Override
public UniFile save(int index, @NonNull UniFile dir, @NonNull String filename) {
// TODO
return null;
}
private class ArchiveTask implements Runnable {
@Override
public void run() {
UniRandomAccessFile uraf = null;
if (file != null) {
try {
uraf = file.createRandomAccessFile("r");
} catch (IOException e) {
e.printStackTrace();
}
}
if (uraf == null) {
size = STATE_ERROR;
error = GetText.getString(R.string.error_reading_failed);
notifyDataChanged();
return;
}
A7ZipArchive archive = null;
try {
archive = A7ZipArchive.create(uraf);
} catch (ArchiveException e) {
e.printStackTrace();
}
if (archive == null) {
size = STATE_ERROR;
error = GetText.getString(R.string.error_invalid_archive);
notifyDataChanged();
return;
}
List<A7ZipArchive.A7ZipArchiveEntry> entries = archive.getArchiveEntries();
Collections.sort(entries, naturalComparator);
// Update size and notify changed
size = entries.size();
notifyDataChanged();
while (!Thread.currentThread().isInterrupted()) {
int index;
synchronized (requests) {
if (requests.isEmpty()) {
try {
requests.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
index = requests.pop();
extractingIndex.lazySet(index);
}
// Check index valid
if (index < 0 || index >= entries.size()) {
extractingIndex.lazySet(GalleryPageView.INVALID_INDEX);
notifyPageFailed(index, GetText.getString(R.string.error_out_of_range));
continue;
}
Pipe pipe = new Pipe(4 * 1024);
synchronized (streams) {
if (streams.get(index) != null) {
continue;
}
streams.put(index, pipe.getInputStream());
streams.notify();
}
try {
entries.get(index).extract(pipe.getOutputStream());
} catch (ArchiveException e) {
e.printStackTrace();
} finally {
extractingIndex.lazySet(GalleryPageView.INVALID_INDEX);
}
}
}
}
private class DecodeTask implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
int index;
InputStream stream;
synchronized (streams) {
if (streams.isEmpty()) {
try {
streams.wait();
} catch (InterruptedException e) {
// Interrupted
break;
}
continue;
}
Iterator<Map.Entry<Integer, InputStream>> iterator = streams.entrySet().iterator();
Map.Entry<Integer, InputStream> entry = iterator.next();
iterator.remove();
index = entry.getKey();
stream = entry.getValue();
decodingIndex.lazySet(index);
}
try {
Image image = Image.decode(stream, true);
if (image != null) {
notifyPageSucceed(index, image);
} else {
notifyPageFailed(index, GetText.getString(R.string.error_decoding_failed));
}
} finally {
decodingIndex.lazySet(GalleryPageView.INVALID_INDEX);
}
}
}
}
private static Comparator<A7ZipArchive.A7ZipArchiveEntry> naturalComparator = new Comparator<A7ZipArchive.A7ZipArchiveEntry>() {
private NaturalComparator comparator = new NaturalComparator();
@Override
public int compare(A7ZipArchive.A7ZipArchiveEntry o1, A7ZipArchive.A7ZipArchiveEntry o2) {
return comparator.compare(o1.getPath(), o2.getPath());
}
};
}
@@ -17,31 +17,30 @@
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.ehviewer.gallery.gl.GalleryPageView;
import com.hippo.glgallery.GalleryPageView;
import com.hippo.image.Image;
import com.hippo.unifile.FilenameFilter;
import com.hippo.unifile.UniFile;
import com.hippo.util.NaturalComparator;
import com.hippo.yorozuya.FileUtils;
import com.hippo.yorozuya.IOUtils;
import com.hippo.yorozuya.PriorityThread;
import com.hippo.yorozuya.StringUtils;
import java.io.File;
import java.io.FilenameFilter;
import com.hippo.yorozuya.thread.PriorityThread;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class DirGalleryProvider extends GalleryProvider implements Runnable {
public class DirGalleryProvider extends GalleryProvider2 implements Runnable {
private static final String TAG = DirGalleryProvider.class.getSimpleName();
private static final AtomicInteger sIdGenerator = new AtomicInteger();
@@ -84,7 +83,7 @@ public class DirGalleryProvider extends GalleryProvider implements Runnable {
}
@Override
public void request(int index) {
protected void onRequest(int index) {
synchronized (mRequests) {
if (!mRequests.contains(index) && index != mDecodingIndex.get()) {
mRequests.add(index);
@@ -95,7 +94,12 @@ public class DirGalleryProvider extends GalleryProvider implements Runnable {
}
@Override
public void cancelRequest(int index) {
protected void onForceRequest(int index) {
onRequest(index);
}
@Override
public void onCancelRequest(int index) {
synchronized (mRequests) {
mRequests.remove(Integer.valueOf(index));
}
@@ -168,7 +172,7 @@ public class DirGalleryProvider extends GalleryProvider implements Runnable {
@Override
public void run() {
// It may take a long time, so run it in new thread
UniFile[] files = mDir.listFiles();
UniFile[] files = mDir.listFiles(imageFilter);
if (files == null) {
mSize = STATE_ERROR;
@@ -182,7 +186,7 @@ public class DirGalleryProvider extends GalleryProvider implements Runnable {
}
// Sort it
Arrays.sort(files);
Arrays.sort(files, naturalComparator);
// Put file list
mFileList.lazySet(files);
@@ -239,11 +243,14 @@ public class DirGalleryProvider extends GalleryProvider implements Runnable {
Log.i(TAG, "ImageDecoder end");
}
private static class ImageFilter implements FilenameFilter {
private static FilenameFilter imageFilter =
(dir, name) -> StringUtils.endsWith(name.toLowerCase(), SUPPORT_IMAGE_EXTENSIONS);
private static Comparator<UniFile> naturalComparator = new Comparator<UniFile>() {
private NaturalComparator comparator = new NaturalComparator();
@Override
public boolean accept(File dir, String filename) {
return StringUtils.endsWith(filename.toLowerCase(), SUPPORT_IMAGE_EXTENSIONS);
public int compare(UniFile o1, UniFile o2) {
return comparator.compare(o1.getName(), o2.getName());
}
}
};
}
@@ -17,18 +17,17 @@
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 GalleryProvider implements SpiderQueen.OnSpiderListener {
public class EhGalleryProvider extends GalleryProvider2 implements SpiderQueen.OnSpiderListener {
private final Context mContext;
private final GalleryInfo mGalleryInfo;
@@ -54,15 +53,9 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
if (mSpiderQueen != null) {
mSpiderQueen.removeOnSpiderListener(this);
final SpiderQueen spiderQueen = mSpiderQueen;
// Activity recreate may called, so wait 3000s
SimpleHandler.getInstance().postDelayed(new ReleaseTask(mSpiderQueen), 3000);
mSpiderQueen = null;
// Activity recreate may called
SimpleHandler.getInstance().postDelayed(new Runnable() {
@Override
public void run() {
SpiderQueen.releaseSpiderQueen(spiderQueen, SpiderQueen.MODE_READ);
}
}, 3000);
}
}
@@ -78,7 +71,7 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
@NonNull
@Override
public String getImageFilename(int index) {
return String.format(Locale.US, "%d-%08d", mGalleryInfo.gid, index + 1);
return String.format(Locale.US, "%d-%s-%08d", mGalleryInfo.gid, mGalleryInfo.token, index + 1);
}
@Override
@@ -117,7 +110,7 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
}
@Override
public void request(int index) {
protected void onRequest(int index) {
if (mSpiderQueen != null) {
Object object = mSpiderQueen.request(index);
if (object instanceof Float) {
@@ -131,7 +124,7 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
}
@Override
public void forceRequest(int index) {
protected void onForceRequest(int index) {
if (mSpiderQueen != null) {
Object object = mSpiderQueen.forceRequest(index);
if (object instanceof Float) {
@@ -145,7 +138,7 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
}
@Override
public void cancelRequest(int index) {
protected void onCancelRequest(int index) {
if (mSpiderQueen != null) {
mSpiderQueen.cancelRequest(index);
}
@@ -200,4 +193,21 @@ public class EhGalleryProvider extends GalleryProvider implements SpiderQueen.On
public void onGetImageFailure(int index, String error) {
notifyPageFailed(index, error);
}
private static class ReleaseTask implements Runnable {
private SpiderQueen mSpiderQueen;
public ReleaseTask(SpiderQueen spiderQueen) {
mSpiderQueen = spiderQueen;
}
@Override
public void run() {
if (null != mSpiderQueen) {
SpiderQueen.releaseSpiderQueen(mSpiderQueen, SpiderQueen.MODE_READ);
mSpiderQueen = null;
}
}
}
}
@@ -1,223 +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.gallery;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import com.hippo.gl.glrenderer.GLCanvas;
import com.hippo.gl.view.GLRoot;
import com.hippo.image.Image;
import com.hippo.unifile.UniFile;
import com.hippo.yorozuya.ConcurrentPool;
import com.hippo.yorozuya.OSUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
public abstract class GalleryProvider {
public static final int STATE_WAIT = -1;
public static final int STATE_ERROR = -2;
// With dot
public static final String[] SUPPORT_IMAGE_EXTENSIONS = {
".jpg", // Joint Photographic Experts Group
".jpeg",
".png", // Portable Network Graphics
".gif", // Graphics Interchange Format
};
private final ConcurrentPool<NotifyTask> mNotifyTaskPool = new ConcurrentPool<>(5);
private volatile GalleryProviderListener mGalleryProviderListener;
private volatile GLRoot mGLRoot;
private boolean mStarted = false;
@UiThread
public void start() {
OSUtils.checkMainLoop();
if (mStarted) {
throw new IllegalStateException("Can't start it twice");
}
mStarted = true;
}
@UiThread
public void stop() {
OSUtils.checkMainLoop();
}
public void setGLRoot(GLRoot glRoot) {
mGLRoot = glRoot;
}
/**
* @return {@link #STATE_WAIT} for wait, 0 for empty
*/
public abstract int size();
public abstract void request(int index);
public void forceRequest(int index) {
request(index);
}
public abstract void cancelRequest(int index);
public abstract String getError();
public int getStartPage() {
return 0;
}
/**
* @return without extension
*/
@NonNull
public abstract String getImageFilename(int index);
public abstract boolean save(int index, @NonNull UniFile file);
/**
* @param filename without extension
*/
@Nullable
public abstract UniFile save(int index, @NonNull UniFile dir, @NonNull String filename);
public void putStartPage(int page) {}
public void setGalleryProviderListener(GalleryProviderListener listener) {
mGalleryProviderListener = listener;
}
public void notifyDataChanged() {
notify(NotifyTask.TYPE_DATA_CHANGED, -1, 0.0f, null, null);
}
public void notifyDataChanged(int index) {
notify(NotifyTask.TYPE_DATA_CHANGED, index, 0.0f, null, null);
}
public void notifyPageWait(int index) {
notify(NotifyTask.TYPE_WAIT, index, 0.0f, null, null);
}
public void notifyPagePercent(int index, float percent) {
notify(NotifyTask.TYPE_PERCENT, index, percent, null, null);
}
public void notifyPageSucceed(int index, Image image) {
notify(NotifyTask.TYPE_SUCCEED, index, 0.0f, image, null);
}
public void notifyPageFailed(int index, String error) {
notify(NotifyTask.TYPE_FAILED, index, 0.0f, null, error);
}
private void notify(@NotifyTask.Type int type, int index, float percent, Image image, String error) {
GalleryProviderListener listener = mGalleryProviderListener;
if (listener == null) {
return;
}
GLRoot glRoot = mGLRoot;
if (glRoot == null) {
return;
}
NotifyTask task = mNotifyTaskPool.pop();
if (task == null) {
task = new NotifyTask(listener, mNotifyTaskPool);
}
task.setData(type, index, percent, image, error);
glRoot.addOnGLIdleListener(task);
}
private static class NotifyTask implements GLRoot.OnGLIdleListener {
@IntDef({TYPE_DATA_CHANGED, NotifyTask.TYPE_WAIT, TYPE_PERCENT, TYPE_SUCCEED, TYPE_FAILED})
@Retention(RetentionPolicy.SOURCE)
public @interface Type {}
public static final int TYPE_DATA_CHANGED = 0;
public static final int TYPE_WAIT = 1;
public static final int TYPE_PERCENT = 2;
public static final int TYPE_SUCCEED = 3;
public static final int TYPE_FAILED = 4;
private final GalleryProviderListener mGalleryProviderListener;
private final ConcurrentPool<NotifyTask> mPool;
@Type
private int mType;
private int mIndex;
private float mPercent;
private Image mImage;
private String mError;
public NotifyTask(GalleryProviderListener galleryProviderListener, ConcurrentPool<NotifyTask> pool) {
mGalleryProviderListener = galleryProviderListener;
mPool = pool;
}
public void setData(@Type int type, int index, float percent, Image image, String error) {
mType = type;
mIndex = index;
mPercent = percent;
mImage = image;
mError = error;
}
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
switch (mType) {
case TYPE_DATA_CHANGED:
if (mIndex < 0) {
mGalleryProviderListener.onDataChanged();
} else {
mGalleryProviderListener.onDataChanged(mIndex);
}
break;
case TYPE_WAIT:
mGalleryProviderListener.onPageWait(mIndex);
break;
case TYPE_PERCENT:
mGalleryProviderListener.onPagePercent(mIndex, mPercent);
break;
case TYPE_SUCCEED:
mGalleryProviderListener.onPageSucceed(mIndex, mImage);
break;
case TYPE_FAILED:
mGalleryProviderListener.onPageFailed(mIndex, mError);
break;
}
// Clean data
mImage = null;
mError = null;
// Push back
mPool.push(this);
return false;
}
}
}
@@ -0,0 +1,53 @@
/*
* 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.gallery;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.hippo.glgallery.GalleryProvider;
import com.hippo.unifile.UniFile;
public abstract class GalleryProvider2 extends GalleryProvider {
// With dot
public static final String[] SUPPORT_IMAGE_EXTENSIONS = {
".jpg", // Joint Photographic Experts Group
".jpeg",
".png", // Portable Network Graphics
".gif", // Graphics Interchange Format
};
public int getStartPage() {
return 0;
}
public void putStartPage(int page) {}
/**
* @return without extension
*/
@NonNull
public abstract String getImageFilename(int index);
public abstract boolean save(int index, @NonNull UniFile file);
/**
* @param filename without extension
*/
@Nullable
public abstract UniFile save(int index, @NonNull UniFile dir, @NonNull String filename);
}
@@ -1,34 +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.gallery;
import com.hippo.image.Image;
public interface GalleryProviderListener {
void onDataChanged();
void onPageWait(int index);
void onPagePercent(int index, float percent);
void onPageSucceed(int index, Image image);
void onPageFailed(int index, String error);
void onDataChanged(int index);
}
@@ -0,0 +1,162 @@
/*
* 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.gallery;
import androidx.annotation.NonNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
class Pipe {
private final int capacity;
private final byte[] buffer;
private int head = 0;
private int tail = 0;
private boolean full = false;
private boolean inClosed = false;
private boolean outClosed = false;
private InputStream inputStream = new InputStream() {
@Override
public int read() throws IOException {
synchronized (Pipe.this) {
byte[] bytes = new byte[1];
if (read(bytes, 0, 1) != -1) {
return bytes[0];
} else {
return -1;
}
}
}
@Override
public int read(@NonNull byte[] b, int off, int len) throws IOException {
synchronized (Pipe.this) {
for (;;) {
if (inClosed) {
throw new IOException("The InputStream is closed");
}
if (len == 0) {
return 0;
}
if (head == tail && !full) {
if (outClosed) {
// No bytes available and the OutputStream is closed. So it's the end.
return -1;
} else {
// Wait for OutputStream write bytes
try {
Pipe.this.wait();
} catch (InterruptedException e) {
throw new IOException("The thread interrupted", e);
}
}
} else {
int read = Math.min(len, (head < tail ? tail : capacity) - head);
System.arraycopy(buffer, head, b, off, read);
head += read;
if (head == capacity) {
head = 0;
}
full = false;
Pipe.this.notifyAll();
return read;
}
}
}
}
@Override
public void close() {
synchronized (Pipe.this) {
inClosed = true;
Pipe.this.notifyAll();
}
}
};
private OutputStream outputStream = new OutputStream() {
@Override
public void write(int b) throws IOException {
synchronized (Pipe.this) {
byte[] bytes = new byte[] { (byte) b};
write(bytes, 0, 1);
}
}
@Override
public void write(@NonNull byte[] b, int off, int len) throws IOException {
synchronized (Pipe.this) {
while (len != 0) {
if (outClosed) {
throw new IOException("The OutputStream is closed");
}
if (inClosed) {
throw new IOException("The InputStream is closed");
}
if (head == tail && full) {
// The buffer is full, wait for InputStream read bytes
try {
Pipe.this.wait();
} catch (InterruptedException e) {
throw new IOException("The thread interrupted", e);
}
} else {
int write = Math.min(len, (head <= tail ? capacity : head) - tail);
System.arraycopy(b, off, buffer, tail, write);
off += write;
len -= write;
tail += write;
if (tail == capacity) {
tail = 0;
}
if (head == tail) {
full = true;
}
Pipe.this.notifyAll();
}
}
}
}
@Override
public void close() {
synchronized (Pipe.this) {
outClosed = true;
Pipe.this.notifyAll();
}
}
};
Pipe(int capacity) {
this.capacity = capacity;
this.buffer = new byte[capacity];
}
InputStream getInputStream() {
return inputStream;
}
OutputStream getOutputStream() {
return outputStream;
}
}
Loaded 100 of 871 files, more files were not shown because too many files have changed in this diff. Show more