Compare commits

..
286 Commits
Author SHA1 Message Date
seven332 12e9346862 Rename colorPrimary, colorPrimaryDark, colorAccent in colors.xml 2017-05-19 19:16:04 +08:00
seven332 dd8342ac3e Add missing fields in GalleryInfo to GalleryInfoContainerMapping 2017-05-19 18:18:09 +08:00
seven332 b39ebaf710 Add GalleryDetailScene 2017-05-19 17:08:04 +08:00
seven332 488be0b9eb Use FlexboxLayout for CategoryTable 2017-05-18 21:06:25 +08:00
seven332 0084cb0872 Fix GalleryDetailParser title parsing 2017-05-18 16:40:55 +08:00
seven332 216aed93fc Add EhClient.getGalleryDetail() 2017-05-18 15:08:24 +08:00
seven332 7f58621d46 Add comments about EhClient.getGalleryMetadata() 2017-05-18 14:42:08 +08:00
seven332 1241b6aba0 Add GalleryDetailParser.parseComments() 2017-05-18 13:40:23 +08:00
seven332 b95a8eec09 Add toString() and hashCode() to GalleryInfo 2017-05-18 00:34:06 +08:00
seven332 d0ade42a19 Add GalleryDetailParser 2017-05-18 00:33:15 +08:00
seven332 64cfd79478 Make converter single instance 2017-05-17 21:48:06 +08:00
seven332 32b496c72c Add parser 2017-05-17 21:39:10 +08:00
seven332 a7b7f14cfb Add parent and child to GalleryInfo 2017-05-16 17:08:03 +08:00
seven332 ae376fc5d1 Add card background drawable 2017-05-15 19:57:55 +08:00
seven332 0a939bc264 Add prefix to category in EhUtils
Add EhUtils.getCategoryTheme(), EhUtils.getLangNotNull()
2017-05-15 19:57:09 +08:00
seven332 de14e055a5 Add TagSet 2017-05-15 19:53:43 +08:00
seven332 0213cb50ba Rename md_colors.xml to colors_md.xml 2017-05-15 13:10:29 +08:00
seven332 0c0f91c73e Add ThemedView 2017-05-15 13:06:40 +08:00
seven332 c9f9cde8c7 Change EhvView.whetherShowLeftDrawer() default value to false 2017-05-15 12:52:28 +08:00
seven332 29fb4a3f9d Use separated theme instead of night mode 2017-05-14 23:22:31 +08:00
seven332 a74577cd91 Improve GalleryListView title 2017-05-14 14:46:52 +08:00
seven332 4ac157f7eb Fix missing western category 2017-05-14 14:38:20 +08:00
seven332 292dfea252 Change EhUtils.getCategory() behavior
Returns null if can't recognize the category.
2017-05-14 14:29:17 +08:00
seven332 cd68e6cafd Make return value of EhUtils.getCategory() readable 2017-05-14 11:47:19 +08:00
seven332 5e710d7960 Add BoringFloatingSearchView 2017-05-14 11:35:03 +08:00
seven332 002ed6d077 EhvPresenter and EhvView add a EhvScene generic type 2017-05-13 21:55:19 +08:00
seven332 5e11cb856f Add GallerySearchScene 2017-05-13 21:44:35 +08:00
seven332 24da35d8b4 Add saving and restoring state in SceneView 2017-05-13 20:28:35 +08:00
seven332 2c2a2c2598 Rename d_x8.xml to divider_x8.xml 2017-05-13 17:04:32 +08:00
seven332 c87382b089 EhvPresenter extends RxPresenter, EhvView extends RxView 2017-05-12 22:55:25 +08:00
seven332 b97eb568bd Remove cross fade stuff 2017-05-12 18:46:10 +08:00
seven332 3f31b12218 Use worker in EhvPresenter 2017-05-12 18:44:06 +08:00
seven332 4d859de57d Unsubscribe client request after presenter destroyed 2017-05-12 18:22:05 +08:00
seven332 462b598739 Remove useless files 2017-05-12 16:19:32 +08:00
seven332 ea5e30bd80 Use stage instead of controller 2017-05-12 16:17:16 +08:00
seven332 07cff484f3 Update gradle library 2017-05-12 16:16:22 +08:00
seven332 06bce20a7b Fix .gitignore 2017-04-12 23:32:44 +08:00
seven332 9facd4457f Add StatusBarView 2017-04-12 23:29:56 +08:00
seven332 4756f938e9 Add ContentLayout.setOnItem(Long)ClickListener() 2017-04-09 13:04:38 +08:00
seven332 cdef5d8ad2 Use android-dialog library 2017-04-09 13:01:41 +08:00
seven332 0f46a46eb0 Update libraries 2017-04-01 00:01:10 +08:00
seven332 49f111fbc2 Tap cover to retry 2017-03-31 21:45:18 +08:00
seven332 3bdf7bcb5a Add cover failure image 2017-03-31 21:24:30 +08:00
seven332 66b89969d1 Add resources 2017-03-31 21:23:04 +08:00
seven332 b87429761a Change dark mode button color to primary color 2017-03-31 21:09:30 +08:00
seven332 d4b507c125 Move files 2017-03-29 22:05:17 +08:00
seven332 15e4471fd4 Adjust EhvView 2017-03-29 20:46:42 +08:00
seven332 14dece039d Remove ThemeUtils 2017-03-20 19:43:07 +08:00
seven332 01963b2165 Rename AppTheme.Main to AppTheme.Ehv 2017-03-20 19:42:10 +08:00
seven332 450d6b6da5 Add EhvDB 2017-03-20 14:51:03 +08:00
seven332 49d9de2f9e Add get favourites 2017-03-20 14:41:44 +08:00
seven332 c8224b2015 Make GalleryInfo implement Parcelable 2017-03-20 13:21:59 +08:00
seven332 d13e09cf12 Add a theme switch in left drawer 2017-03-20 00:34:42 +08:00
seven332 acad8691b3 Add OpenSupplier 2017-03-20 00:16:46 +08:00
seven332 2d4f282002 Add EhvActivity supplier 2017-03-18 18:49:01 +08:00
seven332 d59082d45b Add DBUtils 2017-03-18 18:45:46 +08:00
seven332 b0657e0b07 Add ControllerActivity.showDialog() 2017-03-17 23:44:28 +08:00
seven332 36b335db1a Change Toolbar popup dialog theme 2017-03-17 20:25:03 +08:00
seven332 52ca686ab2 Fix DialogController NPE in onAttach() 2017-03-07 21:09:50 +08:00
seven332 2d93d61689 Add GalleryInfoContainerMapping 2017-03-06 23:08:27 +08:00
seven332 0756051845 Fix GalleryInfo merge different gid and token 2017-03-06 22:00:54 +08:00
seven332 61c388a6f9 Add an INVALID GalleryInfo static instance 2017-03-06 21:58:07 +08:00
seven332 d769eb274d Remove GalleryInfo.note 2017-03-06 21:57:29 +08:00
seven332 b0aabd06e1 Add GalleryInfoDetailHolder and GalleryInfoBriefHolder 2017-03-04 22:48:56 +08:00
seven332 e0f3fb26bc Make GalleryListResult extend GalleryInfoListResult 2017-03-04 17:11:04 +08:00
seven332 195fa602ce Remove Float.NaN 2017-03-04 14:53:14 +08:00
seven332 54ff4f4108 Update GalleryInfo doc 2017-03-04 14:47:04 +08:00
seven332 36b22ce903 Make GalleryInfo.tags nullable 2017-03-04 00:51:28 +08:00
seven332 e39983fd79 Add MSQLite custom primary key 2017-03-03 16:28:22 +08:00
seven332 10d93afa9f Add favourites controller 2017-03-02 16:20:03 +08:00
seven332 57573fcda8 Fix GLUrlBuilder encode error 2017-03-02 16:18:01 +08:00
seven332 065d302cfc Add favourites 2017-03-02 16:10:01 +08:00
seven332 35d118786e Add favourite note 2017-03-02 14:49:33 +08:00
seven332 d6472c8e7f Fix NumberRatingView 0.0f rating not showing 2017-03-02 14:32:47 +08:00
seven332 6447eb8055 Rename GalleryInfoListXXX to GalleryInfoXXX 2017-03-02 13:57:36 +08:00
seven332 cd52d0dbd3 Add GalleryInfoData 2017-03-02 13:43:21 +08:00
seven332 7e2114e4d3 Update libraries and gradle 2017-03-02 01:39:10 +08:00
seven332 db13f1226b Update import 2017-03-02 01:31:21 +08:00
seven332 1b4fb63947 Add ScaleDrawable 2017-03-02 01:30:51 +08:00
seven332 ab0e0ea226 Update 2017-03-02 01:30:32 +08:00
seven332 ec0d0682d7 Add resources 2017-03-02 01:29:30 +08:00
seven332 f31b3ebd85 GalleryInfo implements JsonStore.Item 2017-03-02 01:28:54 +08:00
seven332 8497735749 Add menu 2017-03-02 01:28:04 +08:00
seven332 787627cd72 Update layout resources 2017-03-02 01:27:41 +08:00
seven332 0d46cfecc6 Add EhvActivity 2017-03-02 01:27:16 +08:00
seven332 571561a095 Add widgets 2017-03-02 01:26:35 +08:00
seven332 aba87a1c09 Update import 2017-03-02 01:25:40 +08:00
seven332 41d740d3e6 Add sign in and gallery list and whats hot 2017-03-02 01:25:00 +08:00
seven332 27f3f627a8 Add gallery list item xml resources 2017-03-02 01:21:19 +08:00
seven332 330dc1d7ae Add ContentLayout xml resource 2017-03-02 01:20:21 +08:00
seven332 527b16e0a7 Add ehv widgets 2017-03-02 01:19:44 +08:00
seven332 2890cbd732 Add getTopController() and popTopController() to ControllerActivity 2017-03-02 01:17:32 +08:00
seven332 fffa300d47 Add ToolbarChangeHandler 2017-03-02 01:15:24 +08:00
seven332 8cba313572 Avoid empty message in EhReactiveX 2017-03-02 01:14:15 +08:00
seven332 bdfc07802c Add Adapter and ViewHolder 2017-03-01 23:15:55 +08:00
seven332 a300b8eccc Update Overlay doc 2017-03-01 14:57:32 +08:00
seven332 ba65da9523 Load next page when get bottom 2017-03-01 14:43:13 +08:00
seven332 5d2531d04d Update test 2017-03-01 12:11:21 +08:00
seven332 e1813fa375 Improve ContentData notify data 2017-03-01 12:10:42 +08:00
seven332 de8400c48f Make EhSubscriber support lambda 2017-03-01 00:59:27 +08:00
seven332 e9c27af602 Avoid NPE in RefWatchingController 2017-03-01 00:45:49 +08:00
seven332 9bdfeb031f Add ChangeHandlerAnimators.getMenuItemViews() 2017-03-01 00:43:17 +08:00
seven332 8a45cc7978 Add Overlay.getOverlay(View, int); 2017-03-01 00:35:57 +08:00
seven332 68dbcf6aa4 Add ChangeHandlerAnimators.crossFade() 2017-02-28 21:53:11 +08:00
seven332 1cb0bc09e1 JsonStore.onFetch() return value indicates validity 2017-02-28 16:40:50 +08:00
seven332 2f859d6a56 Catch SSLException in ExceptionExplainer.explain() 2017-02-28 12:52:01 +08:00
seven332 b6c00cdb74 Typo 2017-02-28 00:07:02 +08:00
seven332 6d525cdc86 Backup and restore first page in ContentData 2017-02-27 23:42:58 +08:00
seven332 a6bba26fdf Add Thrower and Catcher 2017-02-27 23:20:39 +08:00
seven332 7fbc94f327 Add JsonStore 2017-02-27 22:11:34 +08:00
seven332 251d517992 Use Properties in transitionseverywhere library 2017-02-27 00:51:18 +08:00
seven332 bee0c6f7c0 Add ChangeHandlerAnimators.changeBounds() 2017-02-27 00:41:29 +08:00
seven332 bc324dc94c Add ChangeHandlerAnimators 2017-02-26 19:50:19 +08:00
seven332 d96f92d7b4 Don't show cross fade animator if data equal to each other 2017-02-26 19:18:54 +08:00
seven332 259a892369 Remove odd interpolator in cross fade animator 2017-02-26 19:17:41 +08:00
seven332 0d56ddcc93 Add ContentData.solidify() 2017-02-26 01:28:34 +08:00
seven332 c973af4228 Unescape xml 2017-02-25 21:27:41 +08:00
seven332 cdacdb2805 Add MutableObject constructor with no parameter 2017-02-25 20:14:14 +08:00
seven332 1117221383 Add EhvApp.get() 2017-02-25 20:12:22 +08:00
seven332 bb94acd61b Add EhClient.getWhatsHot() and EhClient.getGalleryMetadata() 2017-02-25 20:11:47 +08:00
seven332 3aff3635f1 Fix timestamp in GalleryMetadataConverter 2017-02-25 19:59:26 +08:00
seven332 501d61de4c Guess language in WhatHotConverter 2017-02-25 19:23:52 +08:00
seven332 b6e862bec9 Fix ReadableTime.getTimeAgo(0) 2017-02-25 13:41:58 +08:00
seven332 3c29f22017 Add GalleryMetadataConverter 2017-02-25 01:13:03 +08:00
seven332 a5ecf9c1ea Remove GalleryInfo.complete() 2017-02-25 01:12:27 +08:00
seven332 bb34d938f2 Add EhUtils.LANG_UNKNOWN 2017-02-25 01:11:48 +08:00
seven332 2e4f763e17 Add more fields to GalleryInfo 2017-02-25 01:09:31 +08:00
seven332 7820c184f5 Add JSONArray JSONUtils 2017-02-25 00:33:25 +08:00
seven332 9da68564c5 Add JSONObjectUtils 2017-02-24 23:41:40 +08:00
seven332 68259c0b8d Add GalleryInfoListResult 2017-02-24 17:06:56 +08:00
seven332 65dccb11c7 Add whats hot 2017-02-24 16:48:11 +08:00
seven332 aed3098733 Check EhvView memory leak 2017-02-23 20:46:47 +08:00
seven332 0de5204a6e Add AnalyticsContract 2017-02-23 20:04:59 +08:00
seven332 2f950a3e79 Add ForumsResult and ProfileResult 2017-02-23 19:48:00 +08:00
seven332 a0e1306c92 Set ContentData.isDuplicate() protected 2017-02-23 19:44:33 +08:00
seven332 50e3f3cc75 Remove duplicate items in ContentData 2017-02-23 19:36:29 +08:00
seven332 4045f53e2a Add AutoGridLayoutManager 2017-02-23 18:17:23 +08:00
seven332 906eea0246 Add DividerItemDecoration 2017-02-23 18:17:00 +08:00
seven332 20e4ee5482 Add EhvView.schedule() and EhvView.schedulePeriodically() 2017-02-22 22:56:40 +08:00
seven332 59fd345123 Add EhvView.isHeaderView() 2017-02-22 22:19:03 +08:00
seven332 9719134e31 Call notifyDataSetChanged() in ContentData.onGoTo() 2017-02-22 16:46:31 +08:00
seven332 a8b830cecb Add ContentContract.ViewState and ContentContract.AbsPresenter 2017-02-22 16:34:57 +08:00
seven332 6f3e846dc1 Make HeaderLayout draw content before header 2017-02-22 14:33:22 +08:00
seven332 f4c1c41139 Add ControllerActivity 2017-02-22 01:17:18 +08:00
seven332 7caf115693 Add SafeCoordinatorLayout 2017-02-21 22:59:38 +08:00
seven332 79ea59ad4c Add NumberRatingView 2017-02-21 22:59:12 +08:00
seven332 12e8ad71c2 Update SmallRatingView doc 2017-02-21 22:05:24 +08:00
seven332 a7e5513067 Improve SheetChangeHandler 2017-02-21 19:42:39 +08:00
seven332 c9e8231863 Change place_holder_image_light to grey_300 2017-02-21 19:17:08 +08:00
seven332 324c903f9e Add ObservedScrollView 2017-02-21 19:14:09 +08:00
seven332 4d9840432d Add IndicatingScrollView 2017-02-21 19:13:42 +08:00
seven332 9e086d4272 Add ControllerContainer 2017-02-21 19:13:16 +08:00
seven332 17820d1ab6 Add SmallRatingView 2017-02-21 19:07:45 +08:00
seven332 63cbb1af91 Add AutoHideTextView 2017-02-21 19:06:04 +08:00
seven332 246ad8f6b6 Add ContentLayout.setRecyclerViewPadding() 2017-02-21 19:02:52 +08:00
seven332 1b269d9b46 Improve SheetChangeHandler 2017-02-21 19:01:57 +08:00
seven332 11e17931fc Update strings.xml 2017-02-21 18:54:35 +08:00
seven332 aa448bd504 Use HeaderLayout in HeaderChangeHandler 2017-02-21 18:48:49 +08:00
seven332 431140badf Add TransitionChangeHandler.resetFromView() 2017-02-21 18:46:40 +08:00
seven332 8c3cba4c3e Use HeaderLayout in xml 2017-02-21 18:45:49 +08:00
seven332 97227b24f6 Use HeaderLayout 2017-02-21 18:44:53 +08:00
seven332 5e8fa53fa8 Add SignInContract and WarningContract 2017-02-20 20:00:24 +08:00
seven332 ebc80c927b Add GalleryInfo.invalid 2017-02-20 19:59:09 +08:00
seven332 1765edca9a Add language and favouriteSlot to GalleryInfo 2017-02-20 19:37:15 +08:00
seven332 93e8446c7e Add DialogChangeHandler 2017-02-20 19:16:35 +08:00
seven332 12c1914e12 Add DialogController 2017-02-20 19:16:07 +08:00
seven332 db410f7fa7 Add RefWatchingController 2017-02-20 19:12:03 +08:00
seven332 10f4bde754 Add header layout 2017-02-20 16:52:20 +08:00
seven332 d6cd81ec4f Add HeaderChangeHandler 2017-02-20 16:51:25 +08:00
seven332 913308a5c5 Return null if from or to is null 2017-02-20 16:49:09 +08:00
seven332 9420b6673d Add NullableTransitionChangeHandler 2017-02-20 16:47:36 +08:00
seven332 49c27907e4 Don't show recolor animator if no other animators 2017-02-20 16:39:35 +08:00
seven332 8248ca9be5 Rename AnimatorChangeHandler to NullableAnimatorChangeHandler 2017-02-20 16:33:56 +08:00
seven332 a963aee391 Add some ChangeHandler 2017-02-20 00:59:21 +08:00
seven332 7809d11f4c Add RecolorStatusBar ChangeHandler 2017-02-20 00:57:58 +08:00
seven332 cddc78516c Add base ChangeHandler 2017-02-20 00:57:30 +08:00
seven332 b88df2a0aa Add AnalyticsController 2017-02-20 00:56:51 +08:00
seven332 d26ded7781 Add WarningController 2017-02-20 00:55:28 +08:00
seven332 a25e7c679a Add EhvController 2017-02-20 00:55:03 +08:00
seven332 42e7368293 Add EhClient.touchEHentai() 2017-02-19 21:37:12 +08:00
seven332 ad1d0c7835 Get favourite cookie in EhClient.touchExHentai() 2017-02-19 21:32:23 +08:00
seven332 e19efd8ba6 Add ExceptionExplainer 2017-02-19 19:56:42 +08:00
seven332 2d1f67c6c2 Add ReadableTime 2017-02-19 19:56:31 +08:00
seven332 a59657a805 Add TextUtils2.addLeadingMarginSpan() 2017-02-19 19:56:10 +08:00
seven332 4fb1205d9c Add resources 2017-02-19 19:55:44 +08:00
seven332 0c3c531a47 Add EhvBusTags 2017-02-19 19:55:00 +08:00
seven332 802be327d0 Use LazySupplier simple constructor 2017-02-19 19:54:48 +08:00
seven332 29e8e56c5f Add FloatProperty 2017-02-19 19:53:46 +08:00
seven332 7d2beba272 Add ByteDns and PresetDns, remove ClimbOverDns 2017-02-19 19:53:17 +08:00
seven332 b990e80251 Add ToolbarView and MixbarView 2017-02-19 19:51:51 +08:00
seven332 b306a36105 Add SheetView and MessageSheetView 2017-02-19 19:51:25 +08:00
seven332 7424006082 Move views 2017-02-19 19:50:31 +08:00
seven332 97c650681a Add EmptyTransition 2017-02-19 19:15:59 +08:00
seven332 2d7dd0ae4d Fix CrossFade import 2017-02-19 19:14:58 +08:00
seven332 a514650d2e Move cross fade view 2017-02-19 18:36:44 +08:00
seven332 8ac533e40e Move MvpController to base package 2017-02-19 16:21:49 +08:00
seven332 1627b13f56 Add adjust UI in ContentData.requireData() 2017-02-19 15:17:00 +08:00
seven332 b4caf36476 Get language abbreviation from resources 2017-02-19 15:05:00 +08:00
seven332 b81394babe Strip username in SignInConverter 2017-02-19 15:03:58 +08:00
seven332 1ac99128b7 Add GalleryListConverterTest 2017-02-19 15:01:00 +08:00
seven332 f7362f84bb Add GalleryListConverter parsing favourite slot 2017-02-19 14:58:45 +08:00
seven332 f278b7724e Fix time zone of ConverterUtils.DATE_FORMAT 2017-02-19 14:57:39 +08:00
seven332 6aec0a8fc1 Remove EhUtilsTest.testGetLangAbbr() 2017-02-19 14:56:39 +08:00
seven332 bba13febd2 Fix GalleryListConverter 2017-02-19 14:26:15 +08:00
seven332 206e20e65a Add EhUrl.getThumbnailUrl() 2017-02-18 17:13:16 +08:00
seven332 fed7ee5e7e Remove EhClient.recaptcha() 2017-02-18 17:12:00 +08:00
seven332 afaca40de9 Add EhClient.profile() 2017-02-18 17:09:31 +08:00
seven332 4f59925a5c Add ConverterUtils.completeUrl 2017-02-18 17:08:00 +08:00
seven332 7ea517c12d Add return value to ContentData setData() and setError() to indicate whether affected 2017-02-18 00:26:31 +08:00
seven332 5ee3edba0b Fix ContentData and ContentLayout 2017-02-18 00:21:36 +08:00
seven332 63b4fd7e9f Add ControllerPresenter.terminate() 2017-02-18 00:13:15 +08:00
seven332 69aaf34680 Add IntProperty 2017-02-17 22:50:20 +08:00
seven332 e913dc9e26 Add Triple 2017-02-17 22:48:01 +08:00
seven332 936562e8cf Add MutableObject 2017-02-17 22:47:46 +08:00
seven332 eb490ac9cd Add Controller mvp stuff 2017-02-17 22:47:25 +08:00
seven332 f91dcc4417 Add EhvPreferencesImpl 2017-02-17 22:42:11 +08:00
seven332 e512e0b8a8 Add SimpleTask and ComplexTask 2017-02-17 22:41:23 +08:00
seven332 206d31455b Remove EmptyViewState 2017-02-17 22:40:41 +08:00
seven332 d35a7902b5 Remove ViewState 2017-02-17 22:40:11 +08:00
seven332 069fe3338f Add guessing language from gallery title 2017-02-17 22:13:54 +08:00
seven332 a26f2a3d24 Fix ContentDataTest 2017-02-17 22:08:52 +08:00
seven332 c730e00c51 Add Eh category colors 2017-02-17 19:54:14 +08:00
seven332 9b499a7abf Add android-preferences 2017-02-15 01:04:12 +08:00
seven332 75adecd21b Don't long live session cookie 2017-02-13 16:29:28 +08:00
seven332 c96528ebf6 Different application id and name for debug 2017-02-13 15:56:27 +08:00
seven332 3bac9df3ef Add android-chinese-string 2017-02-13 15:48:34 +08:00
seven332 73d992049e Update libraries 2017-02-13 15:42:23 +08:00
seven332 39a4ccf7f3 Add LazySupplier.from() 2017-02-12 16:58:22 +08:00
seven332 58f5e2b007 Add Supplier 2017-02-12 16:57:45 +08:00
seven332 2d9a06fab7 Add CuteTextInputLayout 2017-02-11 21:58:25 +08:00
seven332 41967b61fb Add EmptyViewState 2017-02-11 01:14:37 +08:00
seven332 4a1a620c2b Add ViewState 2017-02-10 23:08:46 +08:00
seven332 92dd5078e2 Make ContentLayout and ContentData follow MVP 2017-02-10 23:08:22 +08:00
seven332 194a4fa3c7 Add PresenterInterface and ViewInterface 2017-02-10 23:02:13 +08:00
seven332 74e61ec885 Rename App to EhvApp 2017-02-10 19:23:09 +08:00
seven332 fdf343362f Hide ContentData.RecordView 2017-02-09 23:34:41 +08:00
seven332 5714aba9dc ContentData doesn't implement ContentView anymore 2017-02-09 23:33:29 +08:00
seven332 78f99ec9f5 Fix null crashes ContentData.setContentView() 2017-02-07 21:16:46 +08:00
seven332 d0f35fa959 Add RunAnimator 2017-02-07 16:37:54 +08:00
seven332 d1c1abb372 Add getTransitionProperties() for CrossFade 2017-02-07 13:40:00 +08:00
seven332 326d46e1c7 Add Preferences 2017-02-07 13:22:45 +08:00
seven332 46cd62ec03 Add PreferencesTest 2017-02-06 21:29:19 +08:00
seven332 d05da33dcd Add ContentDataTest 2017-02-06 20:52:31 +08:00
seven332 c291aa91ed Move RecordingApplication to content package 2017-02-06 19:55:58 +08:00
seven332 b7040b968d Add from-view and to-view separately 2017-02-06 12:38:04 +08:00
seven332 6e9aebb109 Use transitions everywhere 2017-02-06 12:16:21 +08:00
seven332 d753576c64 Add ContentLayout 2017-02-05 23:12:05 +08:00
seven332 22f0ed6eb0 Avoid initialize Fresco twice 2017-02-05 20:07:27 +08:00
seven332 6b0095be35 Fix parse gallery cover url 2017-02-04 00:59:45 +08:00
seven332 d7c76becc0 Add EhCacheKeyFactory 2017-02-03 22:10:06 +08:00
seven332 36c3b6dc73 Add EhUrl.getFingerprint() and EhUrl.getThumbnailFingerprint() 2017-02-03 21:15:24 +08:00
seven332 d157a1a96e Remove EmptyException 2017-02-03 15:00:44 +08:00
seven332 3130bd0a00 Add LeakCanary 2017-02-01 18:20:30 +08:00
seven332 dbbccad9a2 Add dependencies 2017-02-01 17:04:45 +08:00
seven332 40adb9c23c Combines proguard-rules files 2017-01-30 22:34:04 +08:00
seven332 142044e930 Add proguard files 2017-01-30 22:27:44 +08:00
seven332 71249539e0 Add get gallery list 2017-01-30 20:39:55 +08:00
seven332 2776fccb16 Use lambda expressions and method references 2017-01-29 18:14:22 +08:00
seven332 b745e66337 Rename EhEngine.recaptcha() to EhEngine.recaptchaReload() 2017-01-29 17:11:26 +08:00
seven332 8011e79733 Add RecordingApplication 2017-01-27 12:05:38 +08:00
seven332 0e2a867064 Add CrossFade transition 2017-01-27 00:54:27 +08:00
seven332 dfc0afba27 Add dependencies 2017-01-26 22:27:13 +08:00
seven332 6d61997824 Add EhCookieJar 2017-01-25 15:09:13 +08:00
seven332 6d2b329e7c Add EhClient.touchExHentai() 2017-01-24 22:37:24 +08:00
seven332 5ad77598c4 Add printing all cookies 2017-01-24 22:28:44 +08:00
seven332 03210661ca Rename EhApp to App 2017-01-20 13:18:51 +08:00
seven332 e085438b9c Add reason and language for recaptcha to make it work 2017-01-20 01:48:13 +08:00
seven332 f59d9b947d Add recaptcha getter 2017-01-19 20:39:35 +08:00
seven332 20f0c6a0bd Add ClimbOverDns 2017-01-19 16:35:49 +08:00
seven332 ca3ec64b9a Fix EhSubscriber's mechanism
Ensure only one of EhSubscriber.onSuccess() and EhSubscriber.onFailure() can be called.
2017-01-19 15:13:20 +08:00
seven332 13337d9a66 Add EhClient 2017-01-19 00:51:10 +08:00
seven332 da0741e2fc Sort cookie list in CookieRepository 2017-01-17 20:27:37 +08:00
seven332 4b6c836282 Add public suffix support to CookieRepository 2017-01-17 19:40:18 +08:00
seven332 8cb5dcda3e Fix MSQLiteTest.javaTypeToSQLiteType() 2017-01-17 16:27:43 +08:00
seven332 73f0087bfa Add CookieRepository.clear() 2017-01-17 16:26:37 +08:00
seven332 0976c98e16 Test MSQLite.insertColumn() 2017-01-17 00:46:01 +08:00
seven332 41b71b6b99 Exclude com.squareup.okio:okio 2017-01-17 00:30:13 +08:00
seven332 1b3d859ffb Remove useless CookieTest 2017-01-17 00:29:31 +08:00
seven332 121cae4f26 Remove useless test files 2017-01-17 00:27:54 +08:00
seven332 a201777a86 Add CookieRepository 2017-01-17 00:27:17 +08:00
seven332 1a9830cb7f Add missing doc for MSQLite.version() 2017-01-17 00:25:35 +08:00
seven332 7bc7c4e300 Add MSQLite.COLUMN_ID 2017-01-17 00:21:58 +08:00
seven332 3e9299e476 Add default value to non null db type 2017-01-17 00:21:34 +08:00
seven332 85a9521801 Remove NOT NULL in MSQLite TEXT type 2017-01-16 20:21:40 +08:00
seven332 8933fb1ee9 Add MSQLiteOpenHelper 2017-01-16 00:52:00 +08:00
seven332 1394e89c47 Init 2016-12-28 15:39:19 +08:00
1190 changed files with 28532 additions and 171935 deletions

No files matched your search

+4 -3
View File
@@ -1,8 +1,9 @@
*.iml
.gradle
/local.properties
/.idea
.DS_Store
/build
/captures
.externalNativeBuild
/src
*.iml
.idea
/captures
-19
View File
@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id="EhViewer" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="java-gradle" name="Java-Gradle">
<configuration>
<option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
<option name="BUILDABLE" value="false" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.gradle" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
-70
View File
@@ -1,70 +0,0 @@
# EhViewer
这是一个 Android 平台上的 E-Hentai 阅读应用。访问 [EhViewer](http://www.ehviewer.com/) 网站以获取更多信息。<br>
EhViewer is an E-Hentai Application for Android. Visit [EhViewer](http://www.ehviewer.com/)(Chinese Only) website for more information.
# Build
导入 Android Studio 即可。<br>
Just import into Android Studio.
# Thanks
- [android-gif-drawable](https://github.com/koral--/android-gif-drawable)
- 参考 gif 解码
- [ActionBar-PullToRefresh](https://github.com/chrisbanes/ActionBar-PullToRefresh)
- 曾作为刷新控件
- [ActionBarSherlocke](https://github.com/JakeWharton/ActionBarSherlock)
- 曾用来对 4.0 一些系统兼容
- [Android-PullToRefresh](https://github.com/chrisbanes/Android-PullToRefresh)
- 曾作为刷新控件
- [AndroidStaggeredGrid](https://github.com/etsy/AndroidStaggeredGrid)
- 列表控件
- [Apollo-CM](https://github.com/adneal/Apollo-CM)
- 缓存机制
- [DiskLruCache](https://github.com/JakeWharton/DiskLruCache)
- 缓存机制
- [FloatingActionButton](https://github.com/FaizMalkani/FloatingActionButton)
- 按钮控件
- [GIFLIB](http://giflib.sourceforge.net)
- gif 解码
- [Gloria Hallelujah](https://www.google.com/fonts/specimen/Gloria+Hallelujah)
- 启动界面字体
- [ImageLoadingPattern](https://github.com/rnrneverdies/ImageLoadingPattern)
- 图片过渡效果
- [libjpeg-turbo](http://www.libjpeg-turbo.org)
- jpge 解码
- [libpng](http://www.libpng.org/pub/png/libpng.html)
- png 解码
- [material-menu](https://github.com/balysv/material-menu)
- 抽屉指示器
- [OpenCC](https://github.com/BYVoid/OpenCC)
- 繁化工作
- [Slabo](https://github.com/TiroTypeworks/Slabo)
- 图标字体
- [SlidingMenu](https://github.com/jfeinstein10/SlidingMenu)
- 曾作为抽屉控件
- [source-code-pro](https://github.com/adobe/source-code-pro)
- 刷新控件字体
- [svg-android](https://code.google.com/p/svg-android/)
- svg 解析
- [SystemBarTint](https://github.com/jgilfelt/SystemBarTint)
- 状态栏背景设置
- [twoway-view](https://github.com/lucasr/twoway-view)
- RecyclerView 使用方法
- [zlib](http://www.zlib.net)
- 辅助 png 解码
- [Android Open Source Project](http://source.android.com)
- 很多很多
- [commons-lang](http://commons.apache.org/proper/commons-lang)
- 很多很多
# License
本项目内容采用 [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) 授权,
部分文件采用 [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/) 授权([列表](rc/list1)),
部分文件采用 [SIL Open Font License, 1.1](http://scripts.sil.org/OFL) 授权([列表](rc/list2))。
<br>
The content of this project itself is licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0),
some files are licensed under the [Creative Commons Attribution 3.0 Unported License](http://creativecommons.org/licenses/by/3.0/) ([list](rc/list1)),
some files are licensed under the [SIL Open Font License, 1.1](http://scripts.sil.org/OFL) ([list](rc/list2)).
-2
View File
@@ -1,3 +1 @@
/build
/src/main/obj
/src/main/libs
-111
View File
@@ -1,111 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="EhViewer" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android-gradle" name="Android-Gradle">
<configuration>
<option name="GRADLE_PROJECT_PATH" value=":app" />
</configuration>
</facet>
<facet type="android" name="Android">
<configuration>
<option name="SELECTED_BUILD_VARIANT" value="debug" />
<option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
<option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
<option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
<afterSyncTasks>
<task>generateDebugSources</task>
</afterSyncTasks>
<option name="ALLOW_USER_CONFIGURATION" value="false" />
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
<option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
<output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/shaders" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/shaders" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/blame" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/recyclerview-v7/22.2.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/com.android.support/support-v4/22.2.1/jars" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental-safeguard" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/instant-run-support" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/shaders" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
<excludeFolder url="file://$MODULE_DIR$/build/intermediates/transforms" />
<excludeFolder url="file://$MODULE_DIR$/build/outputs" />
<excludeFolder url="file://$MODULE_DIR$/build/tmp" />
</content>
<orderEntry type="jdk" jdkName="Android API 22 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" exported="" name="libGoogleAnalyticsServices" level="project" />
<orderEntry type="library" exported="" name="support-v4-22.2.1" level="project" />
<orderEntry type="library" exported="" name="recyclerview-v7-22.2.1" level="project" />
<orderEntry type="library" exported="" name="support-annotations-22.2.1" level="project" />
<orderEntry type="module" module-name="vector" exported="" />
</component>
</module>
+100 -48
View File
@@ -1,72 +1,124 @@
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'android-chinese-string'
apply plugin: 'com.hippo.android-preferences'
android {
compileSdkVersion 22
buildToolsVersion '22.0.1'
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
targetSdkVersion 22
versionCode 47
versionName "0.6.16.3"
targetSdkVersion 25
versionCode 1
versionName "1.0"
vectorDrawables.useSupportLibrary = true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
debug {
applicationIdSuffix ".debug"
buildConfigField "String", "APPLICATION_NAME", "\"${APPLICATION_NAME}\""
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
minifyEnabled true
buildConfigField "String", "APPLICATION_NAME", "\"${APPLICATION_NAME}\""
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
checkReleaseBuilds false
// Or, if you prefer, you can continue to check for errors in release builds,
// but continue the build even when errors are found:
abortOnError false
}
// Disable default NdkCompile task
// Set new jni lib dir
sourceSets.main {
jni.srcDirs = []
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()
def ndkBuilder
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
ndkBuilder = 'ndk-build.cmd'
} else {
ndkBuilder = 'ndk-build'
}
commandLine "$ndkDir\\$ndkBuilder",
'-C', file('src/main').absolutePath,
'NDK_DEBUG=0',
'NDK_TOOLCHAIN_VERSION=clang',
'-j4'
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
}
clean {
delete file('src/main/obj').absolutePath
delete file('src/main/libs').absolutePath
androidPreferences {
preference from: 'com.hippo.ehviewer.EhvPreferencesImpl', to: 'com.hippo.ehviewer.EhvPreferences'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':vector')
compile 'com.android.support:support-v4:22.2.1'
compile 'com.android.support:recyclerview-v7:22.2.1'
compile "com.android.support:appcompat-v7:$supportLibrary"
compile "com.android.support:cardview-v7:$supportLibrary"
compile "com.android.support:gridlayout-v7:$supportLibrary"
compile "com.android.support:design:$supportLibrary"
// ReactiveX
compile 'io.reactivex:rxjava:1.2.9'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.jakewharton.rxbinding:rxbinding:1.0.1'
compile 'com.hwangjr.rxbus:rxbus:1.0.5'
// Modified okio
compile 'com.github.seven332.okio:okio:1.11.0'
// Http
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.2.0'
// Parses HTML
compile 'org.jsoup:jsoup:1.10.2'
// HTML to CharSequence
compile 'com.github.seven332:android-html:0.1.1'
// Json
compile 'com.google.code.gson:gson:2.8.0'
// SQL
compile 'com.pushtorefresh.storio:sqlite:1.12.3'
// Stage
compile 'com.github.seven332.stage:stage:0.1.1'
compile 'com.github.seven332.stage:stage-dialog:0.1.1'
compile 'com.github.seven332.android-dialog:base:0.1.0'
// Backport of Android Transitions API
compile "com.andkulikov:transitionseverywhere:1.7.0"
compile 'com.github.seven332:android-animator:0.1.0'
// Loads thumbs, only JPEG and PNG
compile 'com.facebook.fresco:fresco:1.2.0'
compile 'com.facebook.fresco:imagepipeline-okhttp3:1.2.0'
// Preferences
compile 'com.github.seven332.android-preferences:preferences:0.1.1'
compile 'com.github.arimorty:floatingsearchview:2.0.4'
compile 'com.github.seven332.easyrecyclerview:easyrecyclerview:1.2.1'
compile 'com.github.seven332.easyrecyclerview:easyrecyclerview-rxjava:1.2.1'
compile 'com.github.seven332:refreshlayout:0.2.1'
compile 'com.github.seven332:drawerlayout:0.2.2'
compile 'com.google.android:flexbox:0.2.6'
compile 'me.zhanghai.android.materialprogressbar:library:1.3.0'
// Utilities
compile 'com.github.seven332.yorozuya:yorozuya:1.1.2'
compile 'com.github.seven332.yorozuya:yorozuya-android:1.1.2'
compile 'com.github.seven332.yorozuya:yorozuya-preconditions:1.1.2'
// Memory leak detection
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile 'junit:junit:4.12'
testCompile "org.robolectric:robolectric:3.3.2"
}
configurations.all {
// Use modified okio instead
exclude group: 'com.squareup.okio', module: 'okio'
}
Binary file not shown.
+69 -26
View File
@@ -15,41 +15,84 @@
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
-keepattributes SourceFile,LineNumberTable
-keep class com.hippo.ehviewer.widget.SearchView {*;}
# Don't obfuscate
-dontobfuscate
-keep class com.hippo.ehviewer.gallery.image.Image {*;}
-keep class com.hippo.ehviewer.gallery.image.GifImage {*;}
###########################################################################
## Fresco
###########################################################################
-keepclassmembers class com.hippo.ehviewer.drawable.MaterialProgressDrawable$Ring {
void set*(***);
*** get*();
# Keep our interfaces so they can be used by other ProGuard rules.
# See http://sourceforge.net/p/proguard/bugs/466/
-keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip
# Do not strip any method/class that is annotated with @DoNotStrip
-keep @com.facebook.common.internal.DoNotStrip class *
-keepclassmembers class * {
@com.facebook.common.internal.DoNotStrip *;
}
-keepclassmembers class * extends com.hippo.ehviewer.windowsanimate.Sprite {
void set*(***);
*** get*();
-dontwarn javax.annotation.**
###########################################################################
## OkHttp3
###########################################################################
-dontwarn okhttp3.**
###########################################################################
## okio
###########################################################################
-dontwarn okio.**
###########################################################################
## Retrofit2
###########################################################################
# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on RoboVM on iOS. Will not be used at runtime.
-dontnote retrofit2.Platform$IOS$MainThreadExecutor
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions
###########################################################################
## Retrofit2-Adapter-RxJava
###########################################################################
# RxJava 1.2.0 has some backward-incompatible changes
# https://github.com/square/retrofit/issues/2034
-dontwarn retrofit2.adapter.rxjava.CompletableHelper$**
###########################################################################
## RxJava
###########################################################################
# https://github.com/artem-zinnatullin/RxJavaProGuardRules
-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
long producerIndex;
long consumerIndex;
}
-keepclassmembers class * extends android.graphics.drawable.Drawable {
void set*(***);
*** get*();
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
rx.internal.util.atomic.LinkedQueueNode producerNode;
}
-keepclassmembers class com.hippo.ehviewer.effect.ripple.Ripple {
void set*(***);
*** get*();
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueConsumerNodeRef {
rx.internal.util.atomic.LinkedQueueNode consumerNode;
}
-keepclassmembers class com.hippo.ehviewer.effect.ripple.RippleBackground {
void set*(***);
*** get*();
}
# For VectorResources
-keep class android.content.res.VectorResources {*;}
# I want to track the error in them
-keep class android.support.v7.widget.StaggeredGridLayoutManager {*;}
-dontwarn sun.misc.Unsafe
@@ -1,13 +0,0 @@
package com.hippo.ehviewer;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
@@ -1,22 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2012 The Android Open Source Project
~ 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
~ 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
~ limitations under the License.
-->
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:valueFrom="1.0"
android:valueTo="0.0"
android:propertyName="alpha"
android:interpolator="@android:interpolator/decelerate_quad"
android:duration="250" />
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
@@ -1,22 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2012 The Android Open Source Project
~ 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
~ 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
~ limitations under the License.
-->
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:valueFrom="0.0"
android:valueTo="1.0"
android:propertyName="alpha"
android:interpolator="@android:interpolator/decelerate_quad"
android:duration="250" />
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+36 -164
View File
@@ -1,173 +1,45 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2014 Hippo Seven
~ 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.
-->
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.
-->
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hippo.ehviewer">
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hippo.ehviewer">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:name=".AppContext"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:largeHeap="true"
android:supportsRtl="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme.Normal">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:name=".EhvApp"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".StartActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar.Transparent.Translucent" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ui.GalleryListActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/app_name"
android:launchMode="singleTop"
android:screenOrientation="behind"
android:theme="@style/AppTheme.Main.ListActivity" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
<activity
android:name=".ui.WebViewLoginActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/login"
android:screenOrientation="behind"
android:windowSoftInputMode="stateAlwaysHidden|adjustResize"
android:theme="@style/AppTheme.NoActionBar">
</activity>
<activity
android:name=".ui.GalleryDetailActivity"
android:configChanges="orientation|screenSize|uiMode"
android:screenOrientation="behind"
android:windowSoftInputMode="adjustPan|adjustUnspecified|stateHidden" >
<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="g.e-hentai.org" />
<data android:host="lofi.e-hentai.org" />
<data android:pathPrefix="/g/" />
</intent-filter>
</activity>
<activity
android:name=".ui.GalleryActivity"
android:configChanges="orientation|screenSize|uiMode"
android:screenOrientation="behind"
android:theme="@style/AppTheme.Dark.NoActionBar" >
</activity>
<activity
android:name=".ui.SettingsActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/preference_settings_title"
android:screenOrientation="behind" >
</activity>
<activity
android:name=".ui.FavouriteActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/favourite"
android:screenOrientation="behind"
android:theme="@style/AppTheme.ListActivity" >
</activity>
<activity
android:name=".ui.HistoryActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/history"
android:screenOrientation="behind"
android:theme="@style/AppTheme.ListActivity" >
</activity>
<activity
android:name=".ui.DownloadActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/download"
android:launchMode="singleTask"
android:screenOrientation="behind"
android:theme="@style/AppTheme.ListActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ui.GalleryListActivity" />
</activity>
<activity
android:name=".ui.SecretActivity"
android:configChanges="orientation|screenSize|uiMode"
android:screenOrientation="behind"
android:theme="@style/AppTheme.NoActionBar.Transparent" >
</activity>
<activity
android:name=".ui.PatternProtectionActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme" >
</activity>
<activity
android:name=".ui.EnterPatternActivity"
android:configChanges="orientation|screenSize|uiMode"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme" >
</activity>
<service
android:name=".service.DownloadService"
android:label="DownloadService" />
<provider
android:name=".SimpleSuggestionProvider"
android:authorities="com.hippo.ehviewer.SimpleSuggestionProvider"
android:exported="false" />
<receiver android:name=".receiver.RestPatternReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SECRET_CODE"/>
<data android:scheme="android_secret_code" android:host="110722"/>
</intent-filter>
</receiver>
</application>
<activity
android:name=".activity.EhvActivity"
android:theme="@style/AppTheme.Ehv"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Binary file not shown.
Binary file not shown.
@@ -1,62 +0,0 @@
/*
* Copyright (C) 2014 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.content.Context;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;
import com.hippo.ehviewer.util.Config;
import org.json.JSONObject;
public class Analytics {
private static final String KEY_GALLERY = "gallery";
private static final String KEY_OPEN = "open";
private static final String KEY_READ = "read";
private static final String KEY_DOWNLOAD = "download";
private static final String KEY_ADD_TO_FAVORITE = "add_to_favorite";
private static void doGallery(Context context, int gid, String token, String method) {
if (!Config.getAllowAnalyics())
return;
try {
JSONObject js = new JSONObject();
js.put("gid", gid).put("token", token);
EasyTracker easyTracker = EasyTracker.getInstance(context);
easyTracker.send(MapBuilder.createEvent(KEY_GALLERY, method, js.toString(), null).build());
} catch (Exception e) {}
}
public static void openGallery(Context context, int gid, String token) {
doGallery(context, gid, token, KEY_OPEN);
}
public static void readGallery(Context context, int gid, String token) {
doGallery(context, gid, token, KEY_READ);
}
public static void downloadGallery(Context context, int gid, String token) {
doGallery(context, gid, token, KEY_DOWNLOAD);
}
public static void addToFavoriteGallery(Context context, int gid, String token) {
doGallery(context, gid, token, KEY_ADD_TO_FAVORITE);
}
}
@@ -1,179 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Typeface;
import android.view.ContextThemeWrapper;
import com.hippo.ehviewer.cache.ImageCache;
import com.hippo.ehviewer.data.Data;
import com.hippo.ehviewer.ehclient.EhClient;
import com.hippo.ehviewer.ehclient.EhInfo;
import com.hippo.ehviewer.ehclient.ExDownloaderManager;
import com.hippo.ehviewer.miscellaneous.FavoriteHelper;
import com.hippo.ehviewer.network.HttpHelper;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Crash;
import com.hippo.ehviewer.util.EhUtils;
import com.hippo.ehviewer.util.Log;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.util.Utils;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.widget.MaterialToast;
import com.hippo.ehviewer.widget.SlidingDrawerLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
public class AppContext extends Application implements UncaughtExceptionHandler {
@SuppressWarnings("unused")
private static final String TAG = AppContext.class.getSimpleName();
private Thread.UncaughtExceptionHandler mDefaultHandler;
private Typeface mFaceTypeface;
@Override
public void onCreate() {
super.onCreate();
// Do catch error prepare
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
Context mContextThemeWrapper = new ContextThemeWrapper(this, R.style.AppTheme);
ViewUtils.initDialogViewInflater(this);
// Init everything
Ui.init(mContextThemeWrapper);
Config.init(mContextThemeWrapper);
Log.init(mContextThemeWrapper);
Crash.init(mContextThemeWrapper);
EhClient.createInstance(mContextThemeWrapper);
FavoriteHelper.init(mContextThemeWrapper);
Data.createInstance(mContextThemeWrapper);
ExDownloaderManager.createInstance(mContextThemeWrapper);
MaterialToast.setContext(mContextThemeWrapper);
mFaceTypeface = Typeface.createFromAsset(getAssets(),"fonts/face.ttf");
// Set drawer margin
SlidingDrawerLayout.setDefaultMinDrawerMargin(Ui.ACTION_BAR_HEIGHT * 2);
// Add .nomedia or delete it
File nomedia = new File(Config.getDownloadPath(), ".nomedia");
if (Config.getMediaScan()) {
nomedia.delete();
} else {
try {
new FileOutputStream(nomedia).close();
} catch (IOException e) {}
}
// Update proxy urls
HttpHelper.updateProxyUrls(mContextThemeWrapper);
String keyVersionCode = "version_code";
int oldVersion = Config.getInt(keyVersionCode, Integer.MAX_VALUE);
// Fix <=22 login error
if (oldVersion <= 22)
EhInfo.getInstance(mContextThemeWrapper).logout();
// Fix <=25 Update
if (oldVersion <= 25) {
File downloadDir = new File(Config.getDownloadPath());
String cachePath = getExternalCacheDir() != null
? getExternalCacheDir().getPath()
: getCacheDir().getPath();
File oldEdInfoDir = new File(cachePath, "ExDownloaderManager");
String[] list = downloadDir.list();
if (list != null && list.length != 0) {
for (String str : list) {
int index = str.indexOf('-');
if (index == -1)
continue;
String gid = str.substring(0, index);
File gDir = new File(downloadDir, str);
// Move download info file
File oldInfoFile = new File(oldEdInfoDir, gid);
File newInfoFile = new File(gDir, EhUtils.EH_DOWNLOAD_FILENAME);
if (!oldInfoFile.exists())
continue;
try {
FileOutputStream fos = new FileOutputStream(newInfoFile);
// Add last page
byte[] bs = {'0', '0', '0', '0', '0', '0', '0', '0', '\n'};
fos.write(bs);
Utils.copy(new FileInputStream(oldInfoFile), fos);
} catch (Throwable e) {
continue;
}
}
}
// Delete old exdownload info dir
Utils.deleteDirInThread(oldEdInfoDir);
}
// Update version code
try {
PackageInfo pi= getPackageManager().getPackageInfo(getPackageName(), 0);
Config.setInt(keyVersionCode, pi.versionCode);
} catch (NameNotFoundException e) {}
}
/**
* {@inheritDoc}
*/
@Override
public void onLowMemory() {
ImageCache.getImageCache(this).clearMemory();
super.onLowMemory();
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
try {
Crash.saveCrashInfo2File(ex);
return true;
} catch (Throwable tr) {
return false;
}
}
public Typeface getFaceTypeface() {
return mFaceTypeface;
}
}
@@ -1,60 +0,0 @@
/*
* Copyright (C) 2014 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.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.hippo.ehviewer.network.HttpHelper;
import com.hippo.ehviewer.util.Constants;
public class AppHandler extends Handler {
public static final int HTTP_HELPER_TAG = 0x1;
private static Handler sInstance;
public AppHandler(Looper mainLooper) {
super(mainLooper);
}
public final static Handler getInstance() {
if (sInstance == null)
sInstance = new AppHandler(Looper.getMainLooper());
return sInstance;
}
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case HTTP_HELPER_TAG:
HttpHelper.Package p = (HttpHelper.Package)msg.obj;
HttpHelper.OnRespondListener listener = p.listener;
Object obj = p.obj;
if (msg.arg1 == Constants.TRUE) {
listener.onSuccess(obj);
} else {
listener.onFailure((String)obj);
}
break;
}
}
}
@@ -0,0 +1,177 @@
/*
* 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.ehviewer;
/*
* Created by Hippo on 1/14/2017.
*/
import android.content.Context;
import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.util.Log;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hippo.ehviewer.client.EhCacheKeyFactory;
import com.hippo.ehviewer.client.EhClient;
import com.hippo.ehviewer.client.EhCookieJar;
import com.hippo.ehviewer.content.RecordingApplication;
import com.hippo.ehviewer.network.PresetDns;
import com.hippo.ehviewer.network.UserAgentInterceptor;
import com.hippo.ehviewer.util.LazySupplier;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class EhvApp extends RecordingApplication {
private static final String LOG_TAG = EhvApp.class.getSimpleName();
private static final String BASE_USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/55.0.2883.87 "
+ "Safari/537.36";
private static final String DB_COOKIE = "okhttp3-cookie.db";
private static final String DB_EHVIEWER = "eh2.db";
private RefWatcher refWatcher;
private LazySupplier<OkHttpClient> okHttpClientSupplier = new LazySupplier<OkHttpClient>() {
@Override
public OkHttpClient onGet() {
return new OkHttpClient.Builder()
.addInterceptor(chain -> {
Request request = chain.request();
// TODO Switch it is app settings
Log.d(LOG_TAG, request.url().toString());
return chain.proceed(request);
})
.addInterceptor(new UserAgentInterceptor(getUserAgent()))
.cookieJar(getCookieJar())
.dns(getDns())
.build();
}
};
private LazySupplier<EhCookieJar> cookieJarSupplier =
LazySupplier.from(() -> new EhCookieJar(EhvApp.this, DB_COOKIE));
private LazySupplier<PresetDns> dnsSupplier = LazySupplier.from(PresetDns::new);
private LazySupplier<EhClient> ehClientLazySupplier =
LazySupplier.from(() -> EhClient.create(EhvApp.this));
private LazySupplier<EhvPreferences> preferencesSupplier =
LazySupplier.from(() -> new EhvPreferences(EhvApp.this));
private LazySupplier<Gson> gsonSupplier =
LazySupplier.from(() -> new GsonBuilder().serializeSpecialFloatingPointValues().create());
private LazySupplier<EhvDB> dbSupplier =
LazySupplier.from(() -> new EhvDB(this, DB_EHVIEWER));
@Override
public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
if (!Fresco.hasBeenInitialized()) {
ImagePipelineConfig config = OkHttpImagePipelineConfigFactory
.newBuilder(this, getOkHttpClient())
.setCacheKeyFactory(new EhCacheKeyFactory())
.build();
Fresco.initialize(this, config);
}
}
public String getUserAgent() {
// Add EhViewer segment to user agent
return BASE_USER_AGENT + " " + BuildConfig.APPLICATION_NAME + "/" + BuildConfig.VERSION_NAME;
}
public RefWatcher getRefWatcher() {
return refWatcher;
}
public OkHttpClient getOkHttpClient() {
return okHttpClientSupplier.get();
}
public EhCookieJar getCookieJar() {
return cookieJarSupplier.get();
}
public PresetDns getDns() {
return dnsSupplier.get();
}
public EhClient getEhClient() {
return ehClientLazySupplier.get();
}
public EhvPreferences getPreferences() {
return preferencesSupplier.get();
}
public Gson getGson() {
return gsonSupplier.get();
}
public EhvDB getDb() {
return dbSupplier.get();
}
/**
* Set night mode for each activity.
*/
public void setNightMode(int mode) {
// Set default night mode
AppCompatDelegate.setDefaultNightMode(mode);
// Apply night mode to each activity
foreach(activity -> {
if (activity instanceof AppCompatActivity) {
((AppCompatActivity) activity).getDelegate().setLocalNightMode(mode);
}
});
// TODO Start a activity with current screenshot and fade, to cover screen flash
}
/**
* Returns {@code true} if the {@code context} is in night theme.
* <p>
* Only work for {@link android.support.v7.app.AppCompatDelegate}.
*/
public static boolean isNightTheme(Context context) {
Configuration conf = context.getResources().getConfiguration();
return (conf.uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
}
/**
* Gets {@code EhvApp} from a {@code Context}.
*/
public static EhvApp get(Context context) {
return (EhvApp) context.getApplicationContext();
}
}
@@ -1,11 +1,11 @@
/*
* Copyright (C) 2014 Hippo Seven
* 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
* 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,
@@ -16,7 +16,24 @@
package com.hippo.ehviewer;
public class NotificationId {
public static final int UPDATE_ID = -1;
public static final int DOWNLOAD_ID = -2;
/*
* Created by Hippo on 2/14/2017.
*/
public final class EhvBusTags {
private EhvBusTags() {}
/**
* Sign in.
*
* Pair<String, String>(name, avatar)
*/
public static final String TAG_SIGN_IN = "sign_in";
/**
* Sign out.
*
* Void
*/
public static final String TAG_SIGN_OUT = "sign_out";
}
@@ -0,0 +1,127 @@
/*
* 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.ehviewer;
/*
* Created by Hippo on 3/3/2017.
*/
import android.content.Context;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import com.hippo.ehviewer.client.data.FavouritesItem;
import com.hippo.ehviewer.dao.FavouritesItemMapping;
import com.hippo.ehviewer.dao.GalleryInfoContainerMapping;
import com.hippo.ehviewer.database.MSQLite;
import com.hippo.ehviewer.database.MSQLiteOpenHelper;
import com.pushtorefresh.storio.sqlite.StorIOSQLite;
import com.pushtorefresh.storio.sqlite.impl.DefaultStorIOSQLite;
import com.pushtorefresh.storio.sqlite.operations.put.PutResult;
import com.pushtorefresh.storio.sqlite.queries.Query;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
import rx.Observable;
public class EhvDB {
private static final int VERSION = 1;
@StringDef({FAVOURITES_ITEM_NOTE, FAVOURITES_ITEM_DATE})
@Retention(RetentionPolicy.SOURCE)
public @interface FavouritesItemOrder {}
public static final String FAVOURITES_ITEM_NOTE = FavouritesItemMapping.COLUMN_NOTE;
public static final String FAVOURITES_ITEM_DATE = FavouritesItemMapping.COLUMN_DATE;
private StorIOSQLite sql;
public EhvDB(EhvApp app, String dbName) {
sql = DefaultStorIOSQLite.builder()
.sqliteOpenHelper(new EhvDBOpenHelper(app, dbName, VERSION))
.addTypeMapping(FavouritesItem.class, new FavouritesItemMapping(app.getGson()))
.build();
}
/**
* Puts a {@link FavouritesItem} to database.
*/
@NonNull
public Observable<PutResult> putFavouritesItem(FavouritesItem item) {
if (item != null) {
return sql.put()
.object(item)
.prepare()
.asRxObservable();
} else {
return Observable.error(new NullPointerException("item == null"));
}
}
/**
* Gets a {@link FavouritesItem} to database.
*/
@Nullable
public FavouritesItem getFavouritesItem(int gid) {
return sql.get()
.object(FavouritesItem.class)
.withQuery(Query.builder()
.table(FavouritesItemMapping.TABLE_NAME)
.where(GalleryInfoContainerMapping.COLUMN_GID + " = ?")
.whereArgs(gid)
.build()
)
.prepare()
.executeAsBlocking();
}
/**
* Gets favourites.
*/
public List<FavouritesItem> getFavourites(
@FavouritesItemOrder String order,
@IntRange(from = 1) int pageSize,
@IntRange(from = 0) int page
) {
return sql.get()
.listOfObjects(FavouritesItem.class)
.withQuery(Query.builder()
.table(FavouritesItemMapping.TABLE_NAME)
.orderBy(order)
.limit(page * pageSize, pageSize)
.build()
)
.prepare()
.executeAsBlocking();
}
private static class EhvDBOpenHelper extends MSQLiteOpenHelper {
public EhvDBOpenHelper(Context context, String name, int version) {
super(context, name, version);
}
@Override
public void onInit(MSQLite ms) {
ms.version(1);
GalleryInfoContainerMapping.galleryInfoTableVersion1(ms);
FavouritesItemMapping.version1(ms);
}
}
}
@@ -0,0 +1,69 @@
/*
* 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.ehviewer;
/*
* Created by Hippo on 1/20/2017.
*/
import static com.hippo.ehviewer.EhvPreferencesImpl.LIST_MODE_DETAIL;
import android.content.Context;
import android.preference.PreferenceManager;
import com.hippo.preferences.Preferences;
import com.hippo.preferences.annotation.BooleanItem;
import com.hippo.preferences.annotation.DecimalIntItem;
import com.hippo.preferences.annotation.IntItem;
import com.hippo.preferences.annotation.Items;
import com.hippo.preferences.annotation.StringItem;
@Items(
booleanItems = {
@BooleanItem(key = "show_warning", defValue = true),
@BooleanItem(key = "ask_analytics", defValue = true),
@BooleanItem(key = "enable_analytics", defValue = false),
@BooleanItem(key = "need_sign_in", defValue = true),
@BooleanItem(key = "select_site", defValue = true),
},
intItems = {
@IntItem(key = "gallery_site", defValue = com.hippo.ehviewer.client.EhUrl.SITE_E),
},
stringItems = {
@StringItem(key = "display_name", defValue = {}),
@StringItem(key = "avatar", defValue = {}),
},
decimalIntItems = {
// 0: detail, 1: brief
@DecimalIntItem(key = "list_mode", defValue = LIST_MODE_DETAIL),
// unit dp
@DecimalIntItem(key = "list_detail_size", defValue = 320),
// unit dp
@DecimalIntItem(key = "list_brief_size", defValue = 120),
}
)
abstract class EhvPreferencesImpl extends Preferences {
public static final int LIST_MODE_DETAIL = 0;
public static final int LIST_MODE_BRIEF = 1;
private EhvApp app;
public EhvPreferencesImpl(Context context) {
super(PreferenceManager.getDefaultSharedPreferences(context));
app = (EhvApp) context.getApplicationContext();
}
}
@@ -1,182 +0,0 @@
/*
* Copyright (C) 2014 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.content.Context;
import android.graphics.Bitmap;
import com.hippo.ehviewer.network.HttpHelper;
import com.hippo.ehviewer.cache.AnyCache;
import com.hippo.ehviewer.cache.ImageCache;
import com.hippo.ehviewer.util.BgThread;
import java.util.Stack;
public class ImageLoader {
@SuppressWarnings("unused")
private static final String TAG = ImageLoader.class.getSimpleName();
public static final int STATE_NONE = 0;
public static final int STATE_FROM_MEMORY = 1;
public static final int STATE_FROM_DISK = 2;
public static final int STATE_FROM_NETWORK = 3;
private static ImageLoader sInstance;
class LoadTask {
public String url;
public String key;
public OnGetImageListener listener;
public Bitmap bitmap;
public int state;
public LoadTask(String url, String key, OnGetImageListener listener) {
this.url = url;
this.key = key;
this.listener = listener;
}
}
private final Context mContext;
private final Stack<LoadTask> mLoadTasks;
private final AnyCache<Bitmap> mImageCache;
private final ImageDownloader mImageDownloader;
private ImageLoader(Context context) {
mLoadTasks = new Stack<LoadTask>();
mImageDownloader = new ImageDownloader();
mContext = context;
mImageCache = ImageCache.getImageCache(mContext);
new BgThread(new LoadFromCacheTask()).start();
}
public final static ImageLoader getInstance(final Context context) {
if (sInstance == null) {
sInstance = new ImageLoader(context.getApplicationContext());
}
return sInstance;
}
public void add(String url, String key, OnGetImageListener listener) {
synchronized (mLoadTasks) {
mLoadTasks.push(new LoadTask(url, key, listener));
mLoadTasks.notify();
}
}
private class LoadImageCallback implements Runnable {
private final LoadTask mLoadTask;
private LoadImageCallback(LoadTask task) {
mLoadTask = task;
}
@Override
public void run() {
mLoadTask.listener.onGetImage(mLoadTask.key, mLoadTask.bitmap, mLoadTask.state);
}
}
private class LoadFromCacheTask implements Runnable {
@Override
public void run() {
LoadTask loadTask;
while (true) {
synchronized (mLoadTasks) {
if (mLoadTasks.isEmpty()) {
try {
mLoadTasks.wait();
} catch (InterruptedException e) {}
continue;
}
loadTask = mLoadTasks.pop();
}
int[] state = new int[1];
String key = loadTask.key;
loadTask.bitmap = mImageCache.get(key);
loadTask.state = state[0];
if (loadTask.bitmap != null)
AppHandler.getInstance().post(new LoadImageCallback(loadTask));
else
mImageDownloader.add(loadTask);
}
}
}
private class ImageDownloader {
private static final int MAX_DOWNLOAD_THREADS = 5;
private final Stack<LoadTask> mDownloadTasks;
private int mWorkingThreadNum = 0;
public ImageDownloader() {
mDownloadTasks = new Stack<LoadTask>();
}
public void add(LoadTask loadTask) {
synchronized (mDownloadTasks) {
mDownloadTasks.push(loadTask);
if (mWorkingThreadNum < MAX_DOWNLOAD_THREADS) {
new BgThread(new DownloadImageTask()).start();
mWorkingThreadNum++;
}
}
}
private class DownloadImageTask implements Runnable {
@Override
public void run() {
LoadTask loadTask;
HttpHelper httpHelper = new HttpHelper(mContext);
while (true) {
synchronized (mDownloadTasks) {
if (mDownloadTasks.isEmpty()) {
loadTask = null;
mWorkingThreadNum--;
break;
}
loadTask = mDownloadTasks.pop();
}
// TODO use proxy to get image
loadTask.bitmap = httpHelper.getImage(loadTask.url);
if (loadTask.bitmap != null) {
mImageCache.put(loadTask.key, loadTask.bitmap);
loadTask.state = STATE_FROM_NETWORK;
} else {
loadTask.state = STATE_NONE;
}
AppHandler.getInstance().post(new LoadImageCallback(loadTask));
}
}
}
}
public interface OnGetImageListener {
/**
* bmp is null for fail
* @param key
* @param bmp
*/
void onGetImage(String key, Bitmap bmp, int state);
}
}
@@ -1,28 +0,0 @@
/*
* Copyright (C) 2014 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.content.SearchRecentSuggestionsProvider;
public class SimpleSuggestionProvider extends SearchRecentSuggestionsProvider {
public final static String AUTHORITY = "com.hippo.ehviewer.SimpleSuggestionProvider";
public final static int MODE = DATABASE_MODE_QUERIES;
public SimpleSuggestionProvider() {
setupSuggestions(AUTHORITY, MODE);
}
}
@@ -1,281 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.hippo.ehviewer.app.MaterialAlertDialog;
import com.hippo.ehviewer.miscellaneous.ActivityHelper;
import com.hippo.ehviewer.network.Network;
import com.hippo.ehviewer.ui.AbsActivity;
import com.hippo.ehviewer.ui.EnterPatternActivity;
import com.hippo.ehviewer.ui.GalleryListActivity;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Crash;
import com.hippo.ehviewer.util.Secret;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.widget.LockPatternUtils;
import com.hippo.ehviewer.widget.SimpleImageView;
import com.hippo.vector.VectorDrawable;
public class StartActivity extends AbsActivity {
@SuppressWarnings("unused")
private static final String TAG = StartActivity.class.getSimpleName();
private static final int REQUEST_CODE_PATTERN = 0;
private static final int CHECK_WARING = 0;
private static final int CHECK_ANALYTICS = 1;
private static final int CHECK_NETWORK = 2;
private static final int CHECK_CRASH = 3;
private static final String KEY_ALLOWED = "allowed";
private static final String KEY_SET_ANALYTICS = "set_analyics";
private String lastCrash;
private boolean isEnterPattern = false;
private boolean isAnimationOver = false;
private boolean isCheckOver = false;
private MaterialAlertDialog createWarningDialog() {
return new MaterialAlertDialog.Builder(this).setCancelable(false)
.setTitle(R.string.dailog_waring_title)
.setMessage(R.string.dailog_waring_plain)
.setPositiveButton(android.R.string.ok)
.setNegativeButton(android.R.string.cancel)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
switch (which) {
case MaterialAlertDialog.POSITIVE:
Config.setBoolean(KEY_ALLOWED, true);
check(CHECK_ANALYTICS);
break;
case MaterialAlertDialog.NEGATIVE:
finish();
break;
}
return true;
}
}).create();
}
private AlertDialog createAllowAnalyicsDialog() {
return new MaterialAlertDialog.Builder(this).setCancelable(false)
.setTitle(R.string.dailog_analyics_title)
.setMessageAutoLink(Linkify.WEB_URLS)
.setMessage(R.string.dailog_analyics_plain)
.setPositiveButton(android.R.string.ok)
.setNegativeButton(android.R.string.cancel)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
switch (which) {
case MaterialAlertDialog.POSITIVE:
Config.setAllowAnalyics(true);
check(CHECK_NETWORK);
break;
case MaterialAlertDialog.NEGATIVE:
Config.setAllowAnalyics(false);
check(CHECK_NETWORK);
break;
}
return true;
}
}).create();
}
private AlertDialog createNetworkDialog(int state) {
int mesgId;
switch (state) {
case Network.NETWORK_STATE_MOBILE:
mesgId = R.string.dailog_network_mobile_title;
break;
case Network.NETWORK_STATE_NONE:
default:
mesgId = R.string.dailog_network_none_title;
break;
}
return new MaterialAlertDialog.Builder(this).setCancelable(false)
.setTitle(R.string.warning).setMessage(mesgId)
.setPositiveButton(android.R.string.ok)
.setNegativeButton(android.R.string.cancel)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
switch (which) {
case MaterialAlertDialog.POSITIVE:
check(CHECK_CRASH);
break;
case MaterialAlertDialog.NEGATIVE:
finish();
break;
}
return true;
}
}).create();
}
private AlertDialog createSendCrashDialog() {
View view = ViewUtils.inflateDialogView(R.layout.send_crash, false);
final EditText et = (EditText) view.findViewById(R.id.description_of_user);
return new MaterialAlertDialog.Builder(this).setCancelable(false)
.setTitle(R.string.dialog_send_crash_title)
.setView(view, true)
.setDefaultButton(MaterialAlertDialog.POSITIVE | MaterialAlertDialog.NEGATIVE)
.setButtonListener(new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
switch (which) {
case MaterialAlertDialog.POSITIVE:
// A wait dialog
new MaterialAlertDialog.Builder(StartActivity.this)
.setCancelable(false)
.setTitle(R.string.wait)
.setMessage(R.string.dialog_wait_send_crash_msg)
.setPositiveButton(android.R.string.ok)
.setButtonListener(
new MaterialAlertDialog.OnClickListener() {
@Override
public boolean onClick(MaterialAlertDialog dialog, int which) {
checkOver();
return true;
}
}).show();
ActivityHelper.sendEmail(StartActivity.this, "ehviewersu@gmail.com", "I found a bug in EhViewer !", lastCrash + "======== Description ========\n" + et.getText().toString());
lastCrash = null;
break;
case MaterialAlertDialog.NEGATIVE:
lastCrash = null;
checkOver();
break;
}
return true;
}
}).create();
}
@Override
public void onCreate(Bundle savedInstanceState) {
// Disable animate
overridePendingTransition(0, 0);
super.onCreate(savedInstanceState);
setContentView(R.layout.start_activity);
TextView text = (TextView) findViewById(R.id.text);
text.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/GloriaHallelujah.ttf"));
SimpleImageView image = (SimpleImageView) findViewById(R.id.image);
image.setDrawable(VectorDrawable.create(this, R.drawable.sad_pandroid));
// Update secret image here
int state = Network.getNetworkState(this);
if (state == Network.NETWORK_STATE_WIFI) {
Secret.updateSecretImage(this);
}
AppHandler.getInstance().postDelayed(new Runnable() {
@Override
public void run() {
if (!StartActivity.this.isFinishing()) {
if (isCheckOver && isEnterPattern)
redirectTo();
isAnimationOver = true;
}
}
}, 3000);
check(CHECK_WARING);
// Enter Pattern
String pattern = Config.getPatternProtection();
if (LockPatternUtils.isPatternVaild(pattern)) {
// Start activity to enter pattern
Intent intent = new Intent(this, EnterPatternActivity.class);
startActivityForResult(intent, REQUEST_CODE_PATTERN);
} else {
isEnterPattern = true;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PATTERN) {
if (resultCode == RESULT_OK) {
if (isAnimationOver && isCheckOver)
redirectTo();
isEnterPattern = true;
} else {
finish();
}
}
}
/**
* Order is 1. check waring 2. check analyics 3. check network 4. check
* crash 5. check external storage
*
* @param order
*/
private void check(int order) {
switch (order) {
case CHECK_WARING:
if (!Config.getBoolean(KEY_ALLOWED, false)) {
createWarningDialog().show();
return;
}
case CHECK_ANALYTICS:
if (!Config.getBoolean(KEY_SET_ANALYTICS, false)) {
Config.setBoolean(KEY_SET_ANALYTICS, true);
createAllowAnalyicsDialog().show();
return;
}
case CHECK_NETWORK:
int state = Network.getNetworkState(this);
if (state != Network.NETWORK_STATE_WIFI) {
createNetworkDialog(state).show();
return;
}
case CHECK_CRASH:
if ((lastCrash = Crash.getLastCrash()) != null) {
createSendCrashDialog().show();
return;
}
}
checkOver();
}
private void checkOver() {
if (isAnimationOver && isEnterPattern)
redirectTo();
isCheckOver = true;
}
private void redirectTo() {
Intent intent = new Intent(this, GalleryListActivity.class);
startActivity(intent);
finish();
}
}
@@ -1,263 +0,0 @@
/*
* Copyright (C) 2014 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.ehviewer;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import com.hippo.ehviewer.ehclient.EhClient;
import com.hippo.ehviewer.network.HttpHelper;
import com.hippo.ehviewer.util.BgThread;
import com.hippo.ehviewer.util.Config;
import com.hippo.ehviewer.util.Utils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
// TODO return onFailure when downloading update or check update
// TODO add disable to achieve
public class UpdateHelper implements Runnable {
@SuppressWarnings("unused")
private static final String TAG = "UpdateHelper";
private static final String HEADER = "Ehviewer-";
private static final String FOOTER = ".apk";
private final AppContext mAppContext;
private OnCheckUpdateListener mListener;
private static boolean mEnabled = true;
public interface OnCheckUpdateListener {
public void onSuccess(String version, long size, String url, String fileName, String info);
public void onNoUpdate();
public void onFailure(String eMsg);
}
public UpdateHelper(AppContext appContext) {
mAppContext = appContext;
}
public UpdateHelper SetOnCheckUpdateListener(OnCheckUpdateListener listener) {
this.mListener = listener;
return this;
}
public void autoCheckUpdate() {
if (Config.getUpdateDate() < Utils.getDate())
checkUpdate();
}
public static void setEnabled(boolean enabled) {
mEnabled = enabled;
}
class CheckUpdatePackage {
public OnCheckUpdateListener listener;
public String body;
public String emesg;
}
private void send(CheckUpdatePackage _package) {
AppHandler.getInstance().post(new Respond(_package));
}
@Override
public void run() {
CheckUpdatePackage _package = new CheckUpdatePackage();
_package.listener = mListener;
final HttpHelper hp = new HttpHelper(mAppContext);
if (!mEnabled) {
_package.body = "working";
send(_package);
return;
}
mEnabled = false;
PackageManager pm = mAppContext.getPackageManager();
PackageInfo pi = null;
try {
pi = pm.getPackageInfo(mAppContext.getPackageName(), PackageManager.GET_ACTIVITIES);
JSONObject jo = new JSONObject();
jo.put("method", "update");
JSONObject detailJO = new JSONObject();
detailJO.put("version", pi.versionName);
detailJO.put("server", Config.getUpdateServer());
jo.put("detail", detailJO);
_package.body = hp.postJson(EhClient.API_EHVIEWER, jo);
_package.emesg = hp.getEMsg();
send(_package);
} catch (NameNotFoundException e) {
e.printStackTrace();
_package.body = "NameNotFound";
send(_package);
} catch (JSONException e) {
e.printStackTrace();
_package.body = "JSONException";
send(_package);
}
}
public void checkUpdate() {
new BgThread(this).start();
}
private class Respond implements Runnable {
CheckUpdatePackage mPackage;
public Respond(CheckUpdatePackage _package) {
mPackage = _package;
}
@Override
public void run() {
OnCheckUpdateListener listener = mPackage.listener;
String body = mPackage.body;
if (body != null) {
Config.setUpdateDate();
if (listener == null)
return;
if (body.equals("working")) {
listener.onFailure("正在检查更新或者下载更新"); // TODO
} else if (body.equals("NameNotFound")) {
listener.onFailure("NameNotFound"); // TODO
} else if (body.equals("JSONException")) {
listener.onFailure("JSONException"); // TODO
} else {
try {
JSONObject jo = new JSONObject(body);
JSONObject updateJO = jo.getJSONObject("update");
if (updateJO.has("error")) {
listener.onFailure(updateJO.getString("error"));
} else {
String version = updateJO.getString("version");
if (version.equals("none")) {
listener.onNoUpdate();
} else {
long size = updateJO.getLong("size");
String url = updateJO.getString("url");
String info = updateJO.getString("info");
listener.onSuccess(version, size, url, HEADER + version + FOOTER, info);
}
}
} catch (JSONException e) {
e.printStackTrace();
listener.onFailure("JSONException");
}
}
}
}
}
public static class UpdateListener implements HttpHelper.OnDownloadListener {
private final Context mContext;
private final String mFileName;
private final NotificationManager mNotifyManager;
public UpdateListener(Context context, String fileName) {
mContext = context;
mFileName = fileName;
mNotifyManager = (NotificationManager)
mContext.getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public void onDownloadStartConnect() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(mContext)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle(mContext.getString(R.string.start_update))
.setProgress(0, 0, true)
.setOngoing(true)
.setTicker(mContext.getString(R.string.start_update));
mNotifyManager.notify(NotificationId.UPDATE_ID, builder.build());
}
@Override
public void onDownloadStartDownload(int totalSize) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(mContext)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle(mContext.getString(R.string.download_update))
.setContentText(String.format("%.2f / %.2f KB", 0/1024.0f, totalSize/1024.0f))
.setProgress(totalSize, 0, false)
.setOngoing(true);
mNotifyManager.notify(NotificationId.UPDATE_ID, builder.build());
}
@Override
public void onDownloadStatusUpdate(
int downloadSize, int totalSize) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(mContext)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle(mContext.getString(R.string.download_update))
.setContentText(String.format("%.2f / %.2f KB", downloadSize/1024.0f, totalSize/1024.0f))
.setProgress(totalSize, downloadSize, false)
.setOngoing(true);
mNotifyManager.notify(NotificationId.UPDATE_ID, builder.build());
}
@Override
public void onDownloadOver(int status, String eMsg) {
if (status == HttpHelper.DOWNLOAD_OK_CODE) {
mNotifyManager.cancel(NotificationId.UPDATE_ID);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Config.getDownloadPath(), mFileName)),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
} else {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(mContext)
.setSmallIcon(android.R.drawable.stat_sys_warning)
.setContentTitle(mContext.getString(R.string.update_failed))
.setContentText(eMsg)
.setOngoing(false);
mNotifyManager.notify(NotificationId.UPDATE_ID, builder.build());
}
setEnabled(true);
}
@Override
public void onUpdateFilename(String newFilename) {
}
}
}
@@ -0,0 +1,294 @@
/*
* 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.ehviewer.activity;
/*
* Created by Hippo on 1/14/2017.
*/
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatDelegate;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import com.hippo.drawerlayout.DrawerLayout;
import com.hippo.ehviewer.EhvApp;
import com.hippo.ehviewer.EhvPreferences;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.scene.analytics.AnalyticsScene;
import com.hippo.ehviewer.scene.gallerylist.GalleryListScene;
import com.hippo.ehviewer.scene.signin.SignInScene;
import com.hippo.ehviewer.scene.warning.WarningScene;
import com.hippo.ehviewer.util.OpenSupplier;
import com.hippo.ehviewer.util.Supplier;
import com.hippo.ehviewer.widget.EhvLeftDrawer;
import com.hippo.stage.Scene;
/**
* Show warning and statistics.
*/
public class EhvActivity extends StageActivity implements
NavigationView.OnNavigationItemSelectedListener {
private static final int TYPE_NONE = 0;
private static final int TYPE_WARNING = 1;
private static final int TYPE_ANALYTICS = 2;
private static final int TYPE_SIGN_IN = 3;
public static final int OVERLAY_CONTENT_ID = R.id.drawer_content;
@Nullable private CoordinatorLayout coordinatorLayout;
@Nullable private DrawerLayout drawerLayout;
@Nullable private NavigationView navigationView;
private int checkedItemId = 0;
private boolean destroyed;
@Nullable private OpenSupplier<EhvActivity> selfSupplier;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (savedInstanceState == null) {
//getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
super.onCreate(savedInstanceState);
}
@Override
protected void onDestroy() {
super.onDestroy();
destroyed = true;
// Clear self supplier
if (selfSupplier != null) {
selfSupplier.set(null);
}
}
@Override
public void onBackPressed() {
if (drawerLayout != null &&
(drawerLayout.isDrawerOpen(Gravity.LEFT) || drawerLayout.isDrawerOpen(Gravity.RIGHT))) {
drawerLayout.closeDrawers();
} else {
super.onBackPressed();
}
}
@Override
protected void onSetContentView() {
setContentView(R.layout.activity_ehv);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
drawerLayout = (DrawerLayout) findViewById(R.id.draw_layout);
// Don't let DrawerLayout draw status bar background
drawerLayout.setStatusBarColor(Color.TRANSPARENT);
EhvLeftDrawer leftDrawer = (EhvLeftDrawer) findViewById(R.id.left_drawer);
// Navigation onItemClickListener
navigationView = leftDrawer.getNavigationView();
navigationView.setNavigationItemSelectedListener(this);
// Night mode button
Button button = leftDrawer.getBottomButton();
button.setText(EhvApp.isNightTheme(button.getContext())
? R.string.let_there_be_light
: R.string.let_there_be_dark);
button.setOnClickListener(v -> {
Context context = v.getContext();
EhvApp.get(context).setNightMode(EhvApp.isNightTheme(context)
? AppCompatDelegate.MODE_NIGHT_NO
: AppCompatDelegate.MODE_NIGHT_YES);
});
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == checkedItemId) {
// Check again
return true;
}
closeLeftDrawer();
switch (id) {
case R.id.nav_homepage:
// TODO
return true;
case R.id.nav_whats_hot:{
// Push whats hot controller
// TODO
return true;
}
case R.id.nav_favourites: {
// Push favourites controller
// TODO
return true;
}
case R.id.nav_invalid:
// Do nothing
return true;
default:
return false;
}
}
@NonNull
@Override
protected ViewGroup onGetStageLayout() {
return (ViewGroup) findViewById(R.id.drawer_content);
}
@NonNull
@Override
protected Scene onCreateRootScene() {
return createScene(null);
}
public void nextScene() {
Class<?> topSceneClass = null;
Scene topScene = getTopScene();
if (topScene != null) {
topSceneClass = getTopScene().getClass();
}
replaceTopScene(createScene(topSceneClass));
}
@NonNull
private Scene createScene(@Nullable Class<?> currentSceneClass) {
int type;
if (currentSceneClass == WarningScene.class) {
type = TYPE_WARNING;
} else if (currentSceneClass == AnalyticsScene.class) {
type = TYPE_ANALYTICS;
} else if (currentSceneClass == SignInScene.class) {
type = TYPE_SIGN_IN;
} else {
type = TYPE_NONE;
}
EhvPreferences preferences = ((EhvApp) getApplication()).getPreferences();
switch (type) {
default:
case TYPE_NONE:
if (preferences.getShowWarning()) {
return new WarningScene();
}
case TYPE_WARNING:
if (preferences.getAskAnalytics()) {
return new AnalyticsScene();
}
case TYPE_ANALYTICS:
if (preferences.getNeedSignIn()) {
return new SignInScene();
}
case TYPE_SIGN_IN:
return new GalleryListScene();
}
}
/**
* Closes and locks left drawer.
*/
public void lockLeftDrawer() {
if (drawerLayout != null) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT);
}
}
/**
* Unlocks left drawer.
*/
public void unlockLeftDrawer() {
if (drawerLayout != null) {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
}
}
/**
* Opens left drawer.
*/
public void openLeftDrawer() {
if (drawerLayout != null) {
drawerLayout.openDrawer(Gravity.LEFT);
}
}
/**
* Closes left drawer.
*/
public void closeLeftDrawer() {
if (drawerLayout != null) {
drawerLayout.closeDrawer(Gravity.LEFT);
}
}
/**
* Sets checked item for left drawer.
* {@code 0} to clear checked state.
*/
public void setLeftDrawerCheckedItem(int id) {
if (navigationView != null) {
navigationView.setCheckedItem(id == 0 ? R.id.nav_invalid : id);
}
}
/**
* Show a message as {@code Snackbar}.
*/
public void showMessage(String text) {
if (coordinatorLayout != null) {
Snackbar.make(coordinatorLayout, text, Snackbar.LENGTH_SHORT).show();
}
}
/**
* Show a message as {@code Snackbar}.
*/
public void showMessage(int resId) {
if (coordinatorLayout != null) {
Snackbar.make(coordinatorLayout, resId, Snackbar.LENGTH_SHORT).show();
}
}
/**
* Returns a {@link Supplier} to get itself.
* <p>
* The {@link Supplier} returns after the {@link EhvActivity} destroyed.
* <p>
* Use it to avoid memory leak.
*/
public Supplier<EhvActivity> getSelfSupplier() {
if (selfSupplier == null) {
selfSupplier = new OpenSupplier<>();
if (!destroyed) {
selfSupplier.set(this);
}
}
return selfSupplier;
}
}
@@ -0,0 +1,121 @@
/*
* 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.ehviewer.activity;
/*
* Created by Hippo on 5/12/2017.
*/
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import com.hippo.stage.Director;
import com.hippo.stage.Scene;
import com.hippo.stage.Stage;
public abstract class StageActivity extends AppCompatActivity {
private static final int STAGE_ID = 0;
private Director director;
private Stage stage;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onSetContentView();
director = Director.hire(this, savedInstanceState);
boolean needRoot = !director.contains(STAGE_ID);
stage = director.direct(onGetStageLayout(), STAGE_ID);
if (needRoot) {
stage.pushScene(onCreateRootScene());
}
}
/**
* Sets content view for this {@code Activity}.
* <p>
* Please call {@link #setContentView(int)}, {@link #setContentView(View)} or
* {@link #setContentView(View, ViewGroup.LayoutParams)} here.
* <p>
* Called in {@link #onCreate(Bundle)}.
*/
protected abstract void onSetContentView();
/**
* Returns a container for scenes.
*/
@NonNull
protected abstract ViewGroup onGetStageLayout();
/**
* Returns root scene for this {@code StageActivity}.
*/
@NonNull
protected abstract Scene onCreateRootScene();
@Override
protected void onDestroy() {
super.onDestroy();
director = null;
stage = null;
}
@Override
public void onBackPressed() {
if (director == null || !director.handleBack()) {
super.onBackPressed();
}
}
/**
* Pushes a scene to the stage.
* It's a no-op if the activity is destroyed.
*/
public void pushScene(@NonNull Scene scene) {
if (stage != null) {
stage.pushScene(scene);
}
}
/**
* Replace the top scene.
* It's a no-op if the activity is destroyed.
*/
protected void replaceTopScene(@NonNull Scene scene) {
if (stage != null) {
stage.replaceTopScene(scene);
}
}
/**
* Returns the top scene.
* Always returns {@code null} if the activity is destroyed.
*/
@Nullable
protected Scene getTopScene() {
if (stage != null) {
return stage.getTopScene();
} else {
return null;
}
}
}
@@ -0,0 +1,39 @@
/*
* 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.ehviewer.annotation;
/*
* Created by Hippo on 2/27/2017.
*/
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates the field is only available since the version.
* <p>
* No operation associated to this annotation.
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.FIELD})
public @interface Since {
int value();
}
@@ -0,0 +1,41 @@
/*
* 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.ehviewer.annotation;
/*
* Created by Hippo on 2/27/2017.
*/
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates the field is only available until the version.
* <p>
* No operation associated to this annotation.
* <p>
* Always add {@link Deprecated} along with it.
*/
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.FIELD})
public @interface Until {
int value();
}
@@ -1,82 +0,0 @@
/*
* Copyright (C) 2014 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.app;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.util.Ui;
import com.hippo.ehviewer.util.ViewUtils;
import com.hippo.ehviewer.widget.FileExplorerView;
public class DirSelectDialog extends MaterialAlertDialog {
private final FileExplorerView mFileExplorerView;
protected DirSelectDialog(Builder builder, FileExplorerView fileExplorerView) {
super(builder);
mFileExplorerView = fileExplorerView;
}
public static DirSelectDialog create(Builder builder, String path) {
View view = ViewUtils.inflateDialogView(R.layout.dir_selection, builder.mDarkTheme);
final FileExplorerView fileExplorerView = (FileExplorerView) view.findViewById(R.id.file_list);
final TextView warningTextView = (TextView) view.findViewById(R.id.warning);
final TextView pathTextView = (TextView) view.findViewById(R.id.path);
if (path != null)
fileExplorerView.setPath(path);
fileExplorerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
fileExplorerView.onItemClick(parent, view, position, id);
pathTextView.setText(fileExplorerView.getCurPath());
if (fileExplorerView.canWrite())
warningTextView.setVisibility(View.GONE);
else
warningTextView.setVisibility(View.VISIBLE);
}
});
pathTextView.setText(fileExplorerView.getCurPath());
if (fileExplorerView.canWrite())
warningTextView.setVisibility(View.GONE);
else
warningTextView.setVisibility(View.VISIBLE);
builder.setView(view, false,
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Ui.dp2pix(360)));
return new DirSelectDialog(builder, fileExplorerView);
}
public String getCurrentPath() {
return mFileExplorerView.getCurPath();
}
public void refresh() {
mFileExplorerView.refresh();
}
public boolean canWrite() {
return mFileExplorerView.canWrite();
}
}
@@ -1,504 +0,0 @@
/*
* Copyright (C) 2014 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.app;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.util.ViewUtils;
public class MaterialAlertDialog extends AlertDialog implements
View.OnClickListener, AdapterView.OnItemClickListener {
public final static int ACTION = 0x1;
public final static int POSITIVE = 0x2;
public final static int NEGATIVE = 0x4;
public final static int NEUTRAL = 0x8;
private final Context mContext;
private final Builder mBuilder;
private View mRootView;
private TextView mTitle;
private Button mActionButton;
private Button mPositiveButton;
private Button mNegativeButton;
private Button mNeutralButton;
protected MaterialAlertDialog(Builder builder) {
super(builder.mContext);
mContext = builder.mContext;
mBuilder = builder;
init();
}
@SuppressLint("InflateParams")
private void init() {
LayoutInflater inflater = LayoutInflater.from(mContext);
mRootView = inflater.inflate(R.layout.alert_dialog_material, null);
// Check in scroll view or not
boolean inScrollView;
if (mBuilder.mCustomView != null)
inScrollView = mBuilder.mInScrollView;
else if (mBuilder.mAdapter != null)
inScrollView = false;
else
inScrollView = true;
// Get widget
LinearLayout topPanel;
TextView message = null;
ListView list = null;
if (inScrollView) {
mRootView.findViewById(R.id.top_panel_noscroll).setVisibility(
View.GONE);
mTitle = (TextView) mRootView.findViewById(R.id.title);
topPanel = (LinearLayout) mRootView.findViewById(R.id.top_panel);
message = (TextView) mRootView.findViewById(R.id.message);
} else {
mRootView.findViewById(R.id.scroll_view).setVisibility(View.GONE);
mTitle = (TextView) mRootView.findViewById(R.id.title2);
topPanel = (LinearLayout) mRootView
.findViewById(R.id.top_panel_noscroll);
list = (ListView) mRootView.findViewById(R.id.list);
}
// Title
if (mBuilder.mTitle == null)
mTitle.setVisibility(View.GONE);
else
mTitle.setText(mBuilder.mTitle);
// Content
if (mBuilder.mCustomView != null) {
// CustomView
if (message != null)
message.setVisibility(View.GONE);
if (list != null)
list.setVisibility(View.GONE);
LinearLayout.LayoutParams lp = mBuilder.mCustomLp;
if (lp == null)
lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mBuilder.mCustomView.setId(R.id.custom);
topPanel.addView(mBuilder.mCustomView, lp);
} else if (mBuilder.mAdapter != null) {
// List
if (message != null)
message.setVisibility(View.GONE);
list.setAdapter(mBuilder.mAdapter);
list.setOnItemClickListener(this);
if (mBuilder.mIsSingleChoice) {
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
if (mBuilder.mCheckedItem > -1) {
list.setItemChecked(mBuilder.mCheckedItem, true);
list.setSelection(mBuilder.mCheckedItem);
}
}
} else {
// Message
if (list != null)
list.setVisibility(View.GONE);
if (mBuilder.mAutoLinkMask != -1)
message.setAutoLinkMask(mBuilder.mAutoLinkMask);
message.setText(mBuilder.mMessage);
}
// Buttons
View buttonPanel = mRootView.findViewById(R.id.button_panel);
View nonActionPanel = mRootView.findViewById(R.id.non_action_panel);
mActionButton = (Button) mRootView.findViewById(R.id.button_action);
mPositiveButton = (Button) mRootView.findViewById(R.id.button_positive);
mNegativeButton = (Button) mRootView.findViewById(R.id.button_negative);
mNeutralButton = (Button) mRootView.findViewById(R.id.button_neutral);
boolean hasAction = mBuilder.mActionButtonText != null;
boolean hasNonAction = mBuilder.mPositiveButtonText != null
|| mBuilder.mNegativeButtonText != null
|| mBuilder.mNeutralButtonText != null;
boolean hasButton = hasAction || hasNonAction;
if (hasButton) {
if (hasAction) {
mActionButton.setText(mBuilder.mActionButtonText);
mActionButton.setOnClickListener(this);
} else {
mActionButton.setVisibility(View.GONE);
}
if (hasNonAction) {
// Positive
if (mBuilder.mPositiveButtonText != null) {
mPositiveButton.setText(mBuilder.mPositiveButtonText);
mPositiveButton.setOnClickListener(this);
} else {
mPositiveButton.setVisibility(View.GONE);
}
// Negative
if (mBuilder.mNegativeButtonText != null) {
mNegativeButton.setText(mBuilder.mNegativeButtonText);
mNegativeButton.setOnClickListener(this);
} else {
mNegativeButton.setVisibility(View.GONE);
}
// Neutral
if (mBuilder.mNeutralButtonText != null) {
mNeutralButton.setText(mBuilder.mNeutralButtonText);
mNeutralButton.setOnClickListener(this);
} else {
mNeutralButton.setVisibility(View.GONE);
}
} else {
nonActionPanel.setVisibility(View.GONE);
}
} else {
buttonPanel.setVisibility(View.GONE);
}
setView(mRootView);
setCancelable(mBuilder.mCancelable);
if (mBuilder.mOnCancelListener != null)
setOnCancelListener(mBuilder.mOnCancelListener);
if (mBuilder.mOnDismissListener != null)
setOnDismissListener(mBuilder.mOnDismissListener);
}
@Override
public void setTitle(CharSequence title) {
mTitle.setText(title);
}
@Override
public void setTitle(int resId) {
setTitle(getContext().getString(resId));
}
public void setView(View view, boolean inScrollView) {
setView(view, inScrollView, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
}
public void setView(View view, boolean inScrollView,
LinearLayout.LayoutParams lp) {
mRootView.findViewById(inScrollView ? R.id.top_panel_noscroll : R.id.scroll_view).setVisibility(View.GONE);
mRootView.findViewById(inScrollView ? R.id.scroll_view : R.id.top_panel_noscroll).setVisibility(View.VISIBLE);
mRootView.findViewById(R.id.message).setVisibility(View.GONE);
mRootView.findViewById(R.id.list).setVisibility(View.GONE);
LinearLayout topPanel = (LinearLayout) mRootView.findViewById(inScrollView ? R.id.top_panel : R.id.top_panel_noscroll);
topPanel.addView(view, lp);
// Title
TextView oldTitle = mTitle;
mTitle = (TextView) mRootView.findViewById(inScrollView ? R.id.title : R.id.title2);
if (mTitle != oldTitle && oldTitle != null)
mTitle.setText(oldTitle.getText());
}
@Override
public void onClick(View v) {
boolean close = true;
if (mBuilder.mButtonListener != null) {
if (v == mActionButton)
close = mBuilder.mButtonListener.onClick(this, ACTION);
else if (v == mPositiveButton)
close = mBuilder.mButtonListener.onClick(this, POSITIVE);
else if (v == mNegativeButton)
close = mBuilder.mButtonListener.onClick(this, NEGATIVE);
else if (v == mNeutralButton)
close = mBuilder.mButtonListener.onClick(this, NEUTRAL);
}
if (close)
dismiss();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
boolean close = false;
if (mBuilder.mOnClickListener != null)
close = mBuilder.mOnClickListener.onClick(this, position);
if (close)
dismiss();
}
public static interface OnClickListener {
public boolean onClick(MaterialAlertDialog dialog, int which);
}
public static class Builder {
protected Context mContext;
protected boolean mDarkTheme = false;
protected CharSequence mTitle;
protected CharSequence mMessage;
protected CharSequence mActionButtonText;
protected CharSequence mPositiveButtonText;
protected CharSequence mNegativeButtonText;
protected CharSequence mNeutralButtonText;
protected OnClickListener mButtonListener;
protected View mCustomView;
protected LinearLayout.LayoutParams mCustomLp;
protected boolean mInScrollView = true;
protected boolean mCancelable = true;
protected int mAutoLinkMask = -1;
protected OnCancelListener mOnCancelListener;
protected ListAdapter mAdapter;
protected OnClickListener mOnClickListener;
protected int mCheckedItem;
protected boolean mIsSingleChoice;
protected DialogInterface.OnDismissListener mOnDismissListener;
public Builder(Context context) {
mContext = context;
}
public Builder setDrakTheme(boolean darkTheme) {
mDarkTheme = darkTheme;
return this;
}
public Builder setTitle(CharSequence title) {
mTitle = title;
return this;
}
public Builder setTitle(int resId) {
return setTitle(mContext.getString(resId));
}
public Builder setMessage(CharSequence message) {
mMessage = message;
return this;
}
public Builder setMessage(int resId) {
return setMessage(mContext.getString(resId));
}
public Builder setActionButton(CharSequence text) {
mActionButtonText = text;
return this;
}
public Builder setActionButton(int resId) {
return setActionButton(mContext.getString(resId));
}
public Builder setPositiveButton(CharSequence text) {
mPositiveButtonText = text;
return this;
}
public Builder setPositiveButton(int resId) {
return setPositiveButton(mContext.getString(resId));
}
public Builder setNegativeButton(CharSequence text) {
mNegativeButtonText = text;
return this;
}
public Builder setNegativeButton(int resId) {
return setNegativeButton(mContext.getString(resId));
}
public Builder setNeutralButton(CharSequence text) {
mNeutralButtonText = text;
return this;
}
public Builder setNeutralButton(int resId) {
return setNeutralButton(mContext.getString(resId));
}
public Builder setDefaultButton(int b) {
if ((b & POSITIVE) == POSITIVE)
mPositiveButtonText = mContext.getString(android.R.string.ok);
if ((b & NEGATIVE) == NEGATIVE)
mNegativeButtonText = mContext.getString(android.R.string.cancel);
return this;
}
public Builder setButtonListener(OnClickListener l) {
mButtonListener = l;
return this;
}
/**
* Custom view id will be R.id.custom
*
* @param view
* @param inScrollView
* @return
*/
public Builder setView(View view, boolean inScrollView) {
mCustomView = view;
mInScrollView = inScrollView;
return this;
}
/**
* Custom view id will be R.id.custom
*
* @param view
* @param inScrollView
* @param lp
* @return
*/
public Builder setView(View view, boolean inScrollView,
LinearLayout.LayoutParams lp) {
mCustomView = view;
mInScrollView = inScrollView;
mCustomLp = lp;
return this;
}
public Builder setView(int resId, boolean inScrollView, ViewHolder vh) {
mCustomView = ViewUtils.inflateDialogView(resId, mDarkTheme);
mInScrollView = inScrollView;
if (vh != null)
vh.setView(mCustomView);
return this;
}
public Builder setCancelable(boolean cancelable) {
mCancelable = cancelable;
return this;
}
public Builder setOnCancelListener(OnCancelListener onCancelListener) {
mOnCancelListener = onCancelListener;
return this;
}
public Builder setMessageAutoLink(int mask) {
mAutoLinkMask = mask;
return this;
}
public Builder setItems(int itemsId, final OnClickListener listener) {
mAdapter = new ArrayAdapter<CharSequence>(
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
R.layout.select_dialog_item, android.R.id.text1, mContext
.getResources().getTextArray(itemsId));
mOnClickListener = listener;
mIsSingleChoice = false;
return this;
}
public Builder setItems(CharSequence[] items,
final OnClickListener listener) {
mAdapter = new ArrayAdapter<CharSequence>(
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
R.layout.select_dialog_item, android.R.id.text1, items);
mOnClickListener = listener;
mIsSingleChoice = false;
return this;
}
public Builder setAdapter(final ListAdapter adapter,
final OnClickListener listener) {
mAdapter = adapter;
mOnClickListener = listener;
mIsSingleChoice = false;
return this;
}
public Builder setSingleChoiceItems(int itemsId, int checkedItem,
final OnClickListener listener) {
mAdapter = new ArrayAdapter<CharSequence>(
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
R.layout.select_dialog_singlechoice, android.R.id.text1,
mContext.getResources().getTextArray(itemsId));
mOnClickListener = listener;
mCheckedItem = checkedItem;
mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(CharSequence[] items,
int checkedItem, final OnClickListener listener) {
mAdapter = new ArrayAdapter<CharSequence>(
mDarkTheme ? ViewUtils.sDarkContextThemeWrapper : ViewUtils.sContextThemeWrapper,
R.layout.select_dialog_singlechoice, android.R.id.text1,
items);
mOnClickListener = listener;
mCheckedItem = checkedItem;
mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(ListAdapter adapter,
int checkedItem, final OnClickListener listener) {
mAdapter = adapter;
mOnClickListener = listener;
mCheckedItem = checkedItem;
mIsSingleChoice = true;
return this;
}
public Builder setOnDismissListener(DialogInterface.OnDismissListener l) {
mOnDismissListener = l;
return this;
}
public MaterialAlertDialog create() {
mContext = new ContextThemeWrapper(mContext, mDarkTheme ?
R.style.AppTheme_Dark_Dialog : R.style.AppTheme_Dialog);
return new MaterialAlertDialog(this);
}
public MaterialAlertDialog show() {
MaterialAlertDialog dialog = create();
dialog.show();
return dialog;
}
}
public static class ViewHolder {
private View mView;
private void setView(View v) {
mView = v;
}
public View getView() {
return mView;
}
}
}
@@ -1,289 +0,0 @@
/*
* Copyright (C) 2014 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.app;
import java.text.NumberFormat;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hippo.ehviewer.R;
public class MaterialProgressDialog extends MaterialAlertDialog {
/** Creates a ProgressDialog with a circular, spinning progress
* bar. This is the default.
*/
public static final int STYLE_SPINNER = 0;
/** Creates a ProgressDialog with a horizontal progress bar.
*/
public static final int STYLE_HORIZONTAL = 1;
private ProgressBar mProgress;
private TextView mMessageView;
private int mProgressStyle = STYLE_HORIZONTAL;
private TextView mProgressNumber;
private String mProgressNumberFormat;
private TextView mProgressPercent;
private NumberFormat mProgressPercentFormat;
private int mMax;
private int mProgressVal;
private int mSecondaryProgressVal;
private boolean mIndeterminate;
private boolean mHasStarted;
private Handler mViewUpdateHandler;
@SuppressLint({ "InflateParams", "HandlerLeak" })
protected MaterialProgressDialog(Builder builder) {
super(builder);
initFormats();
LayoutInflater inflater = LayoutInflater.from(builder.mContext);
if (mProgressStyle == STYLE_HORIZONTAL) {
/* Use a separate handler to update the text views as they
* must be updated on the same thread that created them.
*/
mViewUpdateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
/* Update the number and percent */
int progress = mProgress.getProgress();
int max = mProgress.getMax();
if (mProgressNumberFormat != null) {
String format = mProgressNumberFormat;
mProgressNumber.setText(String.format(format, progress, max));
} else {
mProgressNumber.setText("");
}
if (mProgressPercentFormat != null) {
double percent = (double) progress / (double) max;
SpannableString tmp = new SpannableString(mProgressPercentFormat.format(percent));
tmp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),
0, tmp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mProgressPercent.setText(tmp);
} else {
mProgressPercent.setText("");
}
}
};
View view = inflater.inflate(R.layout.alert_dialog_progress, null);
mProgress = (ProgressBar) view.findViewById(R.id.progress);
mProgressNumber = (TextView) view.findViewById(R.id.progress_number);
mProgressPercent = (TextView) view.findViewById(R.id.progress_percent);
setView(view, false);
} else {
View view = inflater.inflate(R.layout.progress_dialog, null);
mProgress = (ProgressBar) view.findViewById(R.id.progress);
mMessageView = (TextView) view.findViewById(R.id.message);
setView(view, false);
}
}
private void initFormats() {
mProgressNumberFormat = "%1d/%2d";
mProgressPercentFormat = NumberFormat.getPercentInstance();
mProgressPercentFormat.setMaximumFractionDigits(0);
}
public static MaterialProgressDialog create(Context context, CharSequence title) {
return create(context, title, false, null);
}
public static MaterialProgressDialog create(Context context, CharSequence title,
boolean cancelable) {
return create(context, title, cancelable, null);
}
public static MaterialProgressDialog create(Context context, CharSequence title,
boolean cancelable, OnCancelListener cancelListener) {
MaterialProgressDialog.Builder builder = new MaterialProgressDialog.Builder(context);
builder.setTitle(title);
builder.setCancelable(cancelable);
builder.setOnCancelListener(cancelListener);
return new MaterialProgressDialog(builder);
}
@Override
public void onStart() {
super.onStart();
mHasStarted = true;
}
@Override
protected void onStop() {
super.onStop();
mHasStarted = false;
}
public void setProgress(int value) {
if (mHasStarted) {
mProgress.setProgress(value);
onProgressChanged();
} else {
mProgressVal = value;
}
}
public void setSecondaryProgress(int secondaryProgress) {
if (mProgress != null) {
mProgress.setSecondaryProgress(secondaryProgress);
onProgressChanged();
} else {
mSecondaryProgressVal = secondaryProgress;
}
}
public int getProgress() {
if (mProgress != null) {
return mProgress.getProgress();
}
return mProgressVal;
}
public int getSecondaryProgress() {
if (mProgress != null) {
return mProgress.getSecondaryProgress();
}
return mSecondaryProgressVal;
}
public int getMax() {
if (mProgress != null) {
return mProgress.getMax();
}
return mMax;
}
public void setMax(int max) {
if (mProgress != null) {
mProgress.setMax(max);
onProgressChanged();
} else {
mMax = max;
}
}
public void incrementProgressBy(int diff) {
if (mProgress != null) {
mProgress.incrementProgressBy(diff);
onProgressChanged();
}
}
public void incrementSecondaryProgressBy(int diff) {
if (mProgress != null) {
mProgress.incrementSecondaryProgressBy(diff);
onProgressChanged();
}
}
public void setProgressDrawable(Drawable d) {
if (mProgress != null) {
mProgress.setProgressDrawable(d);
}
}
public void setIndeterminateDrawable(Drawable d) {
if (mProgress != null) {
mProgress.setIndeterminateDrawable(d);
}
}
public void setIndeterminate(boolean indeterminate) {
if (mProgress != null) {
mProgress.setIndeterminate(indeterminate);
}
}
public boolean isIndeterminate() {
if (mProgress != null) {
return mProgress.isIndeterminate();
}
return mIndeterminate;
}
@Override
public void setMessage(CharSequence message) {
if (mProgress != null) {
if (mProgressStyle == STYLE_HORIZONTAL) {
super.setMessage(message);
} else {
mMessageView.setText(message);
}
}
}
public void setProgressStyle(int style) {
mProgressStyle = style;
}
/**
* Change the format of the small text showing current and maximum units
* of progress. The default is "%1d/%2d".
* Should not be called during the number is progressing.
* @param format A string passed to {@link String#format String.format()};
* use "%1d" for the current number and "%2d" for the maximum. If null,
* nothing will be shown.
*/
public void setProgressNumberFormat(String format) {
mProgressNumberFormat = format;
onProgressChanged();
}
/**
* Change the format of the small text showing the percentage of progress.
* The default is
* {@link NumberFormat#getPercentInstance() NumberFormat.getPercentageInstnace().}
* Should not be called during the number is progressing.
* @param format An instance of a {@link NumberFormat} to generate the
* percentage text. If null, nothing will be shown.
*/
public void setProgressPercentFormat(NumberFormat format) {
mProgressPercentFormat = format;
onProgressChanged();
}
private void onProgressChanged() {
if (mProgressStyle == STYLE_HORIZONTAL) {
if (mViewUpdateHandler != null && !mViewUpdateHandler.hasMessages(0)) {
mViewUpdateHandler.sendEmptyMessage(0);
}
}
}
}
-501
View File
@@ -1,501 +0,0 @@
/*
* Copyright (C) 2015 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.cache;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import com.hippo.ehviewer.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public abstract class AnyCache<V> {
private static final String TAG = AnyCache.class.getSimpleName();
private LruCache<String, V> mMemoryCache;
private @Nullable DiskCache<V> mDiskCache;
private final boolean mHasMemoryCache;
private final boolean mHasDiskCache;
/**
* Used to temporarily pause the disk cache while scrolling
*/
public boolean mPauseDiskAccess = false;
private final Object mPauseLock = new Object();
private final Object mDiskCacheLock = new Object();
public AnyCache(AnyCacheParams params) {
params.isValid();
mHasMemoryCache = params.hasMemoryCache;
mHasDiskCache = params.hasDiskCache;
if (mHasMemoryCache) {
initMemoryCache(params.memoryCacheMaxSize);
}
if (mHasDiskCache) {
initDiskCache(params.diskCacheDir, params.diskCacheMaxSize);
}
}
private void initMemoryCache(int maxSize) {
mMemoryCache = new MemoryCahce<>(maxSize, this);
}
private void initDiskCache(File cacheDir, int maxSize) {
// Set up disk cache
synchronized (mDiskCacheLock) {
try {
mDiskCache = new DiskCache<>(cacheDir, maxSize, this);
} catch (IOException e) {
Log.e(TAG, "Can't create disk cache", e);
}
}
}
protected abstract int sizeOf(String key, V value);
protected abstract V read(InputStream is);
protected abstract boolean write(OutputStream os, V value);
/**
* Check if have memory cache
*
* @return true if have memory cache
*/
public boolean hasMemoryCache() {
return mHasMemoryCache;
}
/**
* Check if have disk cache
*
* @return true if have disk cache
*/
public boolean hasDiskCache() {
return mHasDiskCache;
}
/**
* Get value from memory cache
*
* @param key the key to get value
* @return the value you get, null for miss or no memory cache
*/
public V getFromMemory(String key) {
if (mHasMemoryCache) {
return mMemoryCache.get(key);
} else {
return null;
}
}
/**
* Get value from memory cache
*
* @param key the key to get value
* @return the value you get, null for miss or no memory cache or get error
*/
public V getFromDisk(String key) {
if (mHasDiskCache) {
// Wait for pause
waitUntilUnpaused();
String diskKey = hashKeyForDisk(key);
synchronized (mDiskCacheLock) {
if (mDiskCache != null) {
return mDiskCache.get(diskKey);
} else {
return null;
}
}
} else {
return null;
}
}
/**
* Get value from memory cache and disk cache. If miss in memory cache and
* get in disk cache, it will put value from disk cache to memory cache.
*
* @param key the key to get value
* @return the value you get
*/
public V get(String key) {
V value = getFromMemory(key);
if (value != null) {
// Get it in memory cache
return value;
}
value = getFromDisk(key);
if (value != null) {
// Get it in disk cache
putToMemory(key, value);
return value;
}
return null;
}
/**
* Put value to memory cache
*
* @param key the key
* @param value the value
* @return false if no memory cache
*/
public boolean putToMemory(String key, V value) {
if (mHasMemoryCache) {
mMemoryCache.put(key, value);
return true;
} else {
return false;
}
}
/**
* Put value to disk cache
*
* @param key the key
* @param value the value
* @return false if no disk cache or get error
*/
public boolean putToDisk(String key, V value) {
if (mHasDiskCache) {
// Wait for pause
waitUntilUnpaused();
String diskKey = hashKeyForDisk(key);
synchronized (mDiskCacheLock) {
if (mDiskCache != null) {
mDiskCache.put(diskKey, value);
return true;
} else {
return false;
}
}
} else {
return false;
}
}
/**
* Put value to memory cache and disk cache
*
* @param key the key
* @param value the value
*/
public void put(String key, V value) {
putToMemory(key, value);
putToDisk(key, value);
}
/**
* Used to temporarily pause the disk cache while the user is scrolling to
* improve scrolling.
*
* @param pause True to temporarily pause the disk cache, false otherwise.
*/
public void setPauseDiskCache(final boolean pause) {
synchronized (mPauseLock) {
if (mPauseDiskAccess != pause) {
mPauseDiskAccess = pause;
if (!pause) {
mPauseLock.notify();
}
}
}
}
private void waitUntilUnpaused() {
synchronized (mPauseLock) {
if (Looper.myLooper() != Looper.getMainLooper()) {
while (mPauseDiskAccess) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
// ignored, we'll start waiting again
}
}
}
}
}
/**
* Evicts all of the items from the memory cache
*/
public void clearMemory() {
if (mHasMemoryCache) {
mMemoryCache.evictAll();
}
}
/**
* Clear disk cache
*/
public void clearDisk() {
if (mHasDiskCache) {
synchronized (mDiskCacheLock) {
if (mDiskCache != null && !mDiskCache.isClosed()) {
try {
mDiskCache.delete();
} catch (IOException e) {
Log.e(TAG, "AnyCache clearCache", e);
}
File cacheDir = mDiskCache.getCacheDir();
int maxSize = mDiskCache.getMaxSize();
mDiskCache = null;
initDiskCache(cacheDir, maxSize);
}
}
}
}
public void flush() {
if (mHasDiskCache) {
synchronized (mDiskCacheLock) {
if (mDiskCache != null) {
try {
mDiskCache.flush();
} catch (IOException e) {
Log.e(TAG, "AnyCache flush", e);
}
}
}
}
}
/**
* Evicts all of the items from the memory cache and lets the system know
* now would be a good time to garbage collect
*/
public void clear() {
clearMemory();
clearDisk();
}
/**
* A hashing method that changes a string (like a URL) into a hash suitable
* for using as a disk filename.
*
* @param key The key used to store the file
*/
private static String hashKeyForDisk(final String key) {
String cacheKey;
try {
final MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(key.getBytes());
cacheKey = bytesToHexString(digest.digest());
} catch (final NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
/**
* http://stackoverflow.com/questions/332079
*
* @param bytes The bytes to convert.
* @return A {@link String} converted from the bytes of a hashable key used
* to store a filename on the disk, to hex digits.
*/
private static String bytesToHexString(final byte[] bytes) {
final StringBuilder builder = new StringBuilder();
for (final byte b : bytes) {
final String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
builder.append('0');
}
builder.append(hex);
}
return builder.toString();
}
/**
* A holder class that contains cache parameters.
*/
public static class AnyCacheParams {
public boolean hasMemoryCache = false;
public int memoryCacheMaxSize = 0;
public boolean hasDiskCache = false;
public File diskCacheDir = null;
public int diskCacheMaxSize = 0;
/**
* Check AnyCacheParams is valid
*
* @throws IllegalStateException
*/
public void isValid() throws IllegalStateException {
if (!hasMemoryCache && !hasDiskCache) {
throw new IllegalStateException("No memory cache and no disk cache. What can I do for you?");
}
if (hasMemoryCache && memoryCacheMaxSize <= 0) {
throw new IllegalStateException("Memory cache max size must be bigger than 0.");
}
if (hasDiskCache) {
if (diskCacheDir == null) {
throw new IllegalStateException("Disk cache dir can't be null.");
}
if (diskCacheMaxSize <= 0) {
throw new IllegalStateException("Disk cache max size must be bigger than 0.");
}
}
}
}
public class MemoryCahce<E> extends LruCache<String, E> {
public AnyCache<E> mParent;
public MemoryCahce(int maxSize, AnyCache<E> parent) {
super(maxSize);
mParent = parent;
}
@Override
protected int sizeOf(String key, E value) {
return mParent.sizeOf(key, value);
}
}
public static class DiskCache<E> {
private static final int IO_BUFFER_SIZE = 8 * 1024;
private DiskLruCache mDiskLruCache;
private AnyCache<E> mParent;
private File mCacheDir;
private int mMaxSize;
public DiskCache(File cacheDir, int size, AnyCache<E> parent) throws IOException {
mDiskLruCache = DiskLruCache.open(cacheDir, 1, 1, size);
mParent = parent;
mCacheDir = cacheDir;
mMaxSize = size;
}
public File getCacheDir() {
return mCacheDir;
}
public int getMaxSize() {
return mMaxSize;
}
public boolean isClosed() {
return mDiskLruCache.isClosed();
}
public void delete() throws IOException {
mDiskLruCache.delete();
}
public void flush() throws IOException {
mDiskLruCache.flush();
}
public E get(String key) {
DiskLruCache.Snapshot snapshot = null;
try {
snapshot = mDiskLruCache.get(key);
if ( snapshot == null ) {
// Miss
return null;
}
final InputStream in = snapshot.getInputStream(0);
if (in != null) {
final BufferedInputStream buffIn =
new BufferedInputStream(in, IO_BUFFER_SIZE);
return mParent.read(buffIn);
} else {
// Can't get InputStream
return null;
}
} catch (IOException e) {
// e.printStackTrace();
return null;
} finally {
Util.closeQuietly(snapshot);
}
}
public boolean put(String key, E value) {
DiskLruCache.Editor editor = null;
OutputStream os = null;
boolean completeEdit = false;
try {
editor = mDiskLruCache.edit(key);
if (editor == null) {
// The editor is in progress
return false;
}
os = editor.newOutputStream(0);
if (os != null) {
final BufferedOutputStream buffOut =
new BufferedOutputStream(os, IO_BUFFER_SIZE);
boolean result = mParent.write(buffOut, value);
completeEdit = true;
editor.commit();
return result;
} else {
// Can't get OutputStream
completeEdit = true;
editor.abort();
return false;
}
} catch (IOException e) {
Util.closeQuietly(os);
try {
if (!completeEdit && editor != null) {
editor.abort();
}
} catch (IOException ignored) {
}
return false;
}
}
}
}
@@ -1,943 +0,0 @@
/*
* Copyright (C) 2011 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.ehviewer.cache;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A cache that uses a bounded amount of space on a filesystem. Each cache
* entry has a string key and a fixed number of values. Each key must match
* the regex <strong>[a-z0-9_-]{1,120}</strong>. Values are byte sequences,
* accessible as streams or files. Each value must be between {@code 0} and
* {@code Integer.MAX_VALUE} bytes in length.
*
* <p>The cache stores its data in a directory on the filesystem. This
* directory must be exclusive to the cache; the cache may delete or overwrite
* files from its directory. It is an error for multiple processes to use the
* same cache directory at the same time.
*
* <p>This cache limits the number of bytes that it will store on the
* filesystem. When the number of stored bytes exceeds the limit, the cache will
* remove entries in the background until the limit is satisfied. The limit is
* not strict: the cache may temporarily exceed it while waiting for files to be
* deleted. The limit does not include filesystem overhead or the cache
* journal so space-sensitive applications should set a conservative limit.
*
* <p>Clients call {@link #edit} to create or update the values of an entry. An
* entry may have only one editor at one time; if a value is not available to be
* edited then {@link #edit} will return null.
* <ul>
* <li>When an entry is being <strong>created</strong> it is necessary to
* supply a full set of values; the empty value should be used as a
* placeholder if necessary.
* <li>When an entry is being <strong>edited</strong>, it is not necessary
* to supply data for every value; values default to their previous
* value.
* </ul>
* Every {@link #edit} call must be matched by a call to {@link Editor#commit}
* or {@link Editor#abort}. Committing is atomic: a read observes the full set
* of values as they were before or after the commit, but never a mix of values.
*
* <p>Clients call {@link #get} to read a snapshot of an entry. The read will
* observe the value at the time that {@link #get} was called. Updates and
* removals after the call do not impact ongoing reads.
*
* <p>This class is tolerant of some I/O errors. If files are missing from the
* filesystem, the corresponding entries will be dropped from the cache. If
* an error occurs while writing a cache value, the edit will fail silently.
* Callers should handle other problems by catching {@code IOException} and
* responding appropriately.
*/
public final class DiskLruCache implements Closeable {
static final String JOURNAL_FILE = "journal";
static final String JOURNAL_FILE_TEMP = "journal.tmp";
static final String JOURNAL_FILE_BACKUP = "journal.bkp";
static final String MAGIC = "libcore.io.DiskLruCache";
static final String VERSION_1 = "1";
static final long ANY_SEQUENCE_NUMBER = -1;
static final String STRING_KEY_PATTERN = "[a-z0-9_-]{1,120}";
static final Pattern LEGAL_KEY_PATTERN = Pattern.compile(STRING_KEY_PATTERN);
private static final String CLEAN = "CLEAN";
private static final String DIRTY = "DIRTY";
private static final String REMOVE = "REMOVE";
private static final String READ = "READ";
/*
* This cache uses a journal file named "journal". A typical journal file
* looks like this:
* libcore.io.DiskLruCache
* 1
* 100
* 2
*
* CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
* DIRTY 335c4c6028171cfddfbaae1a9c313c52
* CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
* REMOVE 335c4c6028171cfddfbaae1a9c313c52
* DIRTY 1ab96a171faeeee38496d8b330771a7a
* CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
* READ 335c4c6028171cfddfbaae1a9c313c52
* READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
*
* The first five lines of the journal form its header. They are the
* constant string "libcore.io.DiskLruCache", the disk cache's version,
* the application's version, the value count, and a blank line.
*
* Each of the subsequent lines in the file is a record of the state of a
* cache entry. Each line contains space-separated values: a state, a key,
* and optional state-specific values.
* o DIRTY lines track that an entry is actively being created or updated.
* Every successful DIRTY action should be followed by a CLEAN or REMOVE
* action. DIRTY lines without a matching CLEAN or REMOVE indicate that
* temporary files may need to be deleted.
* o CLEAN lines track a cache entry that has been successfully published
* and may be read. A publish line is followed by the lengths of each of
* its values.
* o READ lines track accesses for LRU.
* o REMOVE lines track entries that have been deleted.
*
* The journal file is appended to as cache operations occur. The journal may
* occasionally be compacted by dropping redundant lines. A temporary file named
* "journal.tmp" will be used during compaction; that file should be deleted if
* it exists when the cache is opened.
*/
private final File directory;
private final File journalFile;
private final File journalFileTmp;
private final File journalFileBackup;
private final int appVersion;
private long maxSize;
private final int valueCount;
private long size = 0;
private Writer journalWriter;
private final LinkedHashMap<String, Entry> lruEntries =
new LinkedHashMap<String, Entry>(0, 0.75f, true);
private int redundantOpCount;
/**
* To differentiate between old and current snapshots, each entry is given
* a sequence number each time an edit is committed. A snapshot is stale if
* its sequence number is not equal to its entry's sequence number.
*/
private long nextSequenceNumber = 0;
/** This cache uses a single background thread to evict entries. */
final ThreadPoolExecutor executorService =
new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
private final Callable<Void> cleanupCallable = new Callable<Void>() {
public Void call() throws Exception {
synchronized (DiskLruCache.this) {
if (journalWriter == null) {
return null; // Closed.
}
trimToSize();
if (journalRebuildRequired()) {
rebuildJournal();
redundantOpCount = 0;
}
}
return null;
}
};
private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) {
this.directory = directory;
this.appVersion = appVersion;
this.journalFile = new File(directory, JOURNAL_FILE);
this.journalFileTmp = new File(directory, JOURNAL_FILE_TEMP);
this.journalFileBackup = new File(directory, JOURNAL_FILE_BACKUP);
this.valueCount = valueCount;
this.maxSize = maxSize;
}
/**
* Opens the cache in {@code directory}, creating a cache if none exists
* there.
*
* @param directory a writable directory
* @param valueCount the number of values per cache entry. Must be positive.
* @param maxSize the maximum number of bytes this cache should use to store
* @throws IOException if reading or writing the cache directory fails
*/
public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
throws IOException {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
if (valueCount <= 0) {
throw new IllegalArgumentException("valueCount <= 0");
}
// If a bkp file exists, use it instead.
File backupFile = new File(directory, JOURNAL_FILE_BACKUP);
if (backupFile.exists()) {
File journalFile = new File(directory, JOURNAL_FILE);
// If journal file also exists just delete backup file.
if (journalFile.exists()) {
backupFile.delete();
} else {
renameTo(backupFile, journalFile, false);
}
}
// Prefer to pick up where we left off.
DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
if (cache.journalFile.exists()) {
try {
cache.readJournal();
cache.processJournal();
return cache;
} catch (IOException journalIsCorrupt) {
System.out
.println("DiskLruCache "
+ directory
+ " is corrupt: "
+ journalIsCorrupt.getMessage()
+ ", removing");
cache.delete();
}
}
// Create a new empty cache.
directory.mkdirs();
cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
cache.rebuildJournal();
return cache;
}
private void readJournal() throws IOException {
StrictLineReader reader = new StrictLineReader(new FileInputStream(journalFile), Util.US_ASCII);
try {
String magic = reader.readLine();
String version = reader.readLine();
String appVersionString = reader.readLine();
String valueCountString = reader.readLine();
String blank = reader.readLine();
if (!MAGIC.equals(magic)
|| !VERSION_1.equals(version)
|| !Integer.toString(appVersion).equals(appVersionString)
|| !Integer.toString(valueCount).equals(valueCountString)
|| !"".equals(blank)) {
throw new IOException("unexpected journal header: [" + magic + ", " + version + ", "
+ valueCountString + ", " + blank + "]");
}
int lineCount = 0;
while (true) {
try {
readJournalLine(reader.readLine());
lineCount++;
} catch (EOFException endOfJournal) {
break;
}
}
redundantOpCount = lineCount - lruEntries.size();
// If we ended on a truncated line, rebuild the journal before appending to it.
if (reader.hasUnterminatedLine()) {
rebuildJournal();
} else {
journalWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(journalFile, true), Util.US_ASCII));
}
} finally {
Util.closeQuietly(reader);
}
}
private void readJournalLine(String line) throws IOException {
int firstSpace = line.indexOf(' ');
if (firstSpace == -1) {
throw new IOException("unexpected journal line: " + line);
}
int keyBegin = firstSpace + 1;
int secondSpace = line.indexOf(' ', keyBegin);
final String key;
if (secondSpace == -1) {
key = line.substring(keyBegin);
if (firstSpace == REMOVE.length() && line.startsWith(REMOVE)) {
lruEntries.remove(key);
return;
}
} else {
key = line.substring(keyBegin, secondSpace);
}
Entry entry = lruEntries.get(key);
if (entry == null) {
entry = new Entry(key);
lruEntries.put(key, entry);
}
if (secondSpace != -1 && firstSpace == CLEAN.length() && line.startsWith(CLEAN)) {
String[] parts = line.substring(secondSpace + 1).split(" ");
entry.readable = true;
entry.currentEditor = null;
entry.setLengths(parts);
} else if (secondSpace == -1 && firstSpace == DIRTY.length() && line.startsWith(DIRTY)) {
entry.currentEditor = new Editor(entry);
} else if (secondSpace == -1 && firstSpace == READ.length() && line.startsWith(READ)) {
// This work was already done by calling lruEntries.get().
} else {
throw new IOException("unexpected journal line: " + line);
}
}
/**
* Computes the initial size and collects garbage as a part of opening the
* cache. Dirty entries are assumed to be inconsistent and will be deleted.
*/
private void processJournal() throws IOException {
deleteIfExists(journalFileTmp);
for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) {
Entry entry = i.next();
if (entry.currentEditor == null) {
for (int t = 0; t < valueCount; t++) {
size += entry.lengths[t];
}
} else {
entry.currentEditor = null;
for (int t = 0; t < valueCount; t++) {
deleteIfExists(entry.getCleanFile(t));
deleteIfExists(entry.getDirtyFile(t));
}
i.remove();
}
}
}
/**
* Creates a new journal that omits redundant information. This replaces the
* current journal if it exists.
*/
private synchronized void rebuildJournal() throws IOException {
if (journalWriter != null) {
journalWriter.close();
}
Writer writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII));
try {
writer.write(MAGIC);
writer.write("\n");
writer.write(VERSION_1);
writer.write("\n");
writer.write(Integer.toString(appVersion));
writer.write("\n");
writer.write(Integer.toString(valueCount));
writer.write("\n");
writer.write("\n");
for (Entry entry : lruEntries.values()) {
if (entry.currentEditor != null) {
writer.write(DIRTY + ' ' + entry.key + '\n');
} else {
writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
}
}
} finally {
writer.close();
}
if (journalFile.exists()) {
renameTo(journalFile, journalFileBackup, true);
}
renameTo(journalFileTmp, journalFile, false);
journalFileBackup.delete();
journalWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(journalFile, true), Util.US_ASCII));
}
private static void deleteIfExists(File file) throws IOException {
if (file.exists() && !file.delete()) {
throw new IOException();
}
}
private static void renameTo(File from, File to, boolean deleteDestination) throws IOException {
if (deleteDestination) {
deleteIfExists(to);
}
if (!from.renameTo(to)) {
throw new IOException();
}
}
/**
* Returns a snapshot of the entry named {@code key}, or null if it doesn't
* exist is not currently readable. If a value is returned, it is moved to
* the head of the LRU queue.
*/
public synchronized Snapshot get(String key) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (entry == null) {
return null;
}
if (!entry.readable) {
return null;
}
// Open all streams eagerly to guarantee that we see a single published
// snapshot. If we opened streams lazily then the streams could come
// from different edits.
InputStream[] ins = new InputStream[valueCount];
try {
for (int i = 0; i < valueCount; i++) {
ins[i] = new FileInputStream(entry.getCleanFile(i));
}
} catch (FileNotFoundException e) {
// A file must have been deleted manually!
for (int i = 0; i < valueCount; i++) {
if (ins[i] != null) {
Util.closeQuietly(ins[i]);
} else {
break;
}
}
return null;
}
redundantOpCount++;
journalWriter.append(READ + ' ' + key + '\n');
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
return new Snapshot(key, entry.sequenceNumber, ins, entry.lengths);
}
/**
* Returns an editor for the entry named {@code key}, or null if another
* edit is in progress.
*/
public Editor edit(String key) throws IOException {
return edit(key, ANY_SEQUENCE_NUMBER);
}
private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null
|| entry.sequenceNumber != expectedSequenceNumber)) {
return null; // Snapshot is stale.
}
if (entry == null) {
entry = new Entry(key);
lruEntries.put(key, entry);
} else if (entry.currentEditor != null) {
return null; // Another edit is in progress.
}
Editor editor = new Editor(entry);
entry.currentEditor = editor;
// Flush the journal before creating files to prevent file leaks.
journalWriter.write(DIRTY + ' ' + key + '\n');
journalWriter.flush();
return editor;
}
/** Returns the directory where this cache stores its data. */
public File getDirectory() {
return directory;
}
/**
* Returns the maximum number of bytes that this cache should use to store
* its data.
*/
public synchronized long getMaxSize() {
return maxSize;
}
/**
* Changes the maximum number of bytes the cache can store and queues a job
* to trim the existing store, if necessary.
*/
public synchronized void setMaxSize(long maxSize) {
this.maxSize = maxSize;
executorService.submit(cleanupCallable);
}
/**
* Returns the number of bytes currently being used to store the values in
* this cache. This may be greater than the max size if a background
* deletion is pending.
*/
public synchronized long size() {
return size;
}
private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
Entry entry = editor.entry;
if (entry.currentEditor != editor) {
throw new IllegalStateException();
}
// If this edit is creating the entry for the first time, every index must have a value.
if (success && !entry.readable) {
for (int i = 0; i < valueCount; i++) {
if (!editor.written[i]) {
editor.abort();
throw new IllegalStateException("Newly created entry didn't create value for index " + i);
}
if (!entry.getDirtyFile(i).exists()) {
editor.abort();
return;
}
}
}
for (int i = 0; i < valueCount; i++) {
File dirty = entry.getDirtyFile(i);
if (success) {
if (dirty.exists()) {
File clean = entry.getCleanFile(i);
dirty.renameTo(clean);
long oldLength = entry.lengths[i];
long newLength = clean.length();
entry.lengths[i] = newLength;
size = size - oldLength + newLength;
}
} else {
deleteIfExists(dirty);
}
}
redundantOpCount++;
entry.currentEditor = null;
if (entry.readable | success) {
entry.readable = true;
journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
if (success) {
entry.sequenceNumber = nextSequenceNumber++;
}
} else {
lruEntries.remove(entry.key);
journalWriter.write(REMOVE + ' ' + entry.key + '\n');
}
journalWriter.flush();
if (size > maxSize || journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
}
/**
* We only rebuild the journal when it will halve the size of the journal
* and eliminate at least 2000 ops.
*/
private boolean journalRebuildRequired() {
final int redundantOpCompactThreshold = 2000;
return redundantOpCount >= redundantOpCompactThreshold //
&& redundantOpCount >= lruEntries.size();
}
/**
* Drops the entry for {@code key} if it exists and can be removed. Entries
* actively being edited cannot be removed.
*
* @return true if an entry was removed.
*/
public synchronized boolean remove(String key) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (entry == null || entry.currentEditor != null) {
return false;
}
for (int i = 0; i < valueCount; i++) {
File file = entry.getCleanFile(i);
if (file.exists() && !file.delete()) {
throw new IOException("failed to delete " + file);
}
size -= entry.lengths[i];
entry.lengths[i] = 0;
}
redundantOpCount++;
journalWriter.append(REMOVE + ' ' + key + '\n');
lruEntries.remove(key);
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
return true;
}
/** Returns true if this cache has been closed. */
public synchronized boolean isClosed() {
return journalWriter == null;
}
private void checkNotClosed() {
if (journalWriter == null) {
throw new IllegalStateException("cache is closed");
}
}
/** Force buffered operations to the filesystem. */
public synchronized void flush() throws IOException {
checkNotClosed();
trimToSize();
journalWriter.flush();
}
/** Closes this cache. Stored values will remain on the filesystem. */
public synchronized void close() throws IOException {
if (journalWriter == null) {
return; // Already closed.
}
for (Entry entry : new ArrayList<Entry>(lruEntries.values())) {
if (entry.currentEditor != null) {
entry.currentEditor.abort();
}
}
trimToSize();
journalWriter.close();
journalWriter = null;
}
private void trimToSize() throws IOException {
while (size > maxSize) {
Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next();
remove(toEvict.getKey());
}
}
/**
* Closes the cache and deletes all of its stored values. This will delete
* all files in the cache directory including files that weren't created by
* the cache.
*/
public void delete() throws IOException {
close();
Util.deleteContents(directory);
}
private void validateKey(String key) {
Matcher matcher = LEGAL_KEY_PATTERN.matcher(key);
if (!matcher.matches()) {
throw new IllegalArgumentException("keys must match regex "
+ STRING_KEY_PATTERN + ": \"" + key + "\"");
}
}
private static String inputStreamToString(InputStream in) throws IOException {
return Util.readFully(new InputStreamReader(in, Util.UTF_8));
}
/** A snapshot of the values for an entry. */
public final class Snapshot implements Closeable {
private final String key;
private final long sequenceNumber;
private final InputStream[] ins;
private final long[] lengths;
private Snapshot(String key, long sequenceNumber, InputStream[] ins, long[] lengths) {
this.key = key;
this.sequenceNumber = sequenceNumber;
this.ins = ins;
this.lengths = lengths;
}
/**
* Returns an editor for this snapshot's entry, or null if either the
* entry has changed since this snapshot was created or if another edit
* is in progress.
*/
public Editor edit() throws IOException {
return DiskLruCache.this.edit(key, sequenceNumber);
}
/** Returns the unbuffered stream with the value for {@code index}. */
public InputStream getInputStream(int index) {
return ins[index];
}
/** Returns the string value for {@code index}. */
public String getString(int index) throws IOException {
return inputStreamToString(getInputStream(index));
}
/** Returns the byte length of the value for {@code index}. */
public long getLength(int index) {
return lengths[index];
}
public void close() {
for (InputStream in : ins) {
Util.closeQuietly(in);
}
}
}
private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() {
@Override
public void write(int b) throws IOException {
// Eat all writes silently. Nom nom.
}
};
/** Edits the values for an entry. */
public final class Editor {
private final Entry entry;
private final boolean[] written;
private boolean hasErrors;
private boolean committed;
private Editor(Entry entry) {
this.entry = entry;
this.written = (entry.readable) ? null : new boolean[valueCount];
}
/**
* Returns an unbuffered input stream to read the last committed value,
* or null if no value has been committed.
*/
public InputStream newInputStream(int index) throws IOException {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
if (!entry.readable) {
return null;
}
try {
return new FileInputStream(entry.getCleanFile(index));
} catch (FileNotFoundException e) {
return null;
}
}
}
/**
* Returns the last committed value as a string, or null if no value
* has been committed.
*/
public String getString(int index) throws IOException {
InputStream in = newInputStream(index);
return in != null ? inputStreamToString(in) : null;
}
/**
* Returns a new unbuffered output stream to write the value at
* {@code index}. If the underlying output stream encounters errors
* when writing to the filesystem, this edit will be aborted when
* {@link #commit} is called. The returned output stream does not throw
* IOExceptions.
*/
public OutputStream newOutputStream(int index) throws IOException {
if (index < 0 || index >= valueCount) {
throw new IllegalArgumentException("Expected index " + index + " to "
+ "be greater than 0 and less than the maximum value count "
+ "of " + valueCount);
}
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
if (!entry.readable) {
written[index] = true;
}
File dirtyFile = entry.getDirtyFile(index);
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(dirtyFile);
} catch (FileNotFoundException e) {
// Attempt to recreate the cache directory.
directory.mkdirs();
try {
outputStream = new FileOutputStream(dirtyFile);
} catch (FileNotFoundException e2) {
// We are unable to recover. Silently eat the writes.
return NULL_OUTPUT_STREAM;
}
}
return new FaultHidingOutputStream(outputStream);
}
}
/** Sets the value at {@code index} to {@code value}. */
public void set(int index, String value) throws IOException {
Writer writer = null;
try {
writer = new OutputStreamWriter(newOutputStream(index), Util.UTF_8);
writer.write(value);
} finally {
Util.closeQuietly(writer);
}
}
/**
* Commits this edit so it is visible to readers. This releases the
* edit lock so another edit may be started on the same key.
*/
public void commit() throws IOException {
if (hasErrors) {
completeEdit(this, false);
remove(entry.key); // The previous entry is stale.
} else {
completeEdit(this, true);
}
committed = true;
}
/**
* Aborts this edit. This releases the edit lock so another edit may be
* started on the same key.
*/
public void abort() throws IOException {
completeEdit(this, false);
}
public void abortUnlessCommitted() {
if (!committed) {
try {
abort();
} catch (IOException ignored) {
}
}
}
private class FaultHidingOutputStream extends FilterOutputStream {
private FaultHidingOutputStream(OutputStream out) {
super(out);
}
@Override public void write(int oneByte) {
try {
out.write(oneByte);
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void write(byte[] buffer, int offset, int length) {
try {
out.write(buffer, offset, length);
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void close() {
try {
out.close();
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void flush() {
try {
out.flush();
} catch (IOException e) {
hasErrors = true;
}
}
}
}
private final class Entry {
private final String key;
/** Lengths of this entry's files. */
private final long[] lengths;
/** True if this entry has ever been published. */
private boolean readable;
/** The ongoing edit or null if this entry is not being edited. */
private Editor currentEditor;
/** The sequence number of the most recently committed edit to this entry. */
private long sequenceNumber;
private Entry(String key) {
this.key = key;
this.lengths = new long[valueCount];
}
public String getLengths() throws IOException {
StringBuilder result = new StringBuilder();
for (long size : lengths) {
result.append(' ').append(size);
}
return result.toString();
}
/** Set lengths using decimal numbers like "10123". */
private void setLengths(String[] strings) throws IOException {
if (strings.length != valueCount) {
throw invalidLengths(strings);
}
try {
for (int i = 0; i < strings.length; i++) {
lengths[i] = Long.parseLong(strings[i]);
}
} catch (NumberFormatException e) {
throw invalidLengths(strings);
}
}
private IOException invalidLengths(String[] strings) throws IOException {
throw new IOException("unexpected journal line: " + java.util.Arrays.toString(strings));
}
public File getCleanFile(int i) {
return new File(directory, key + "." + i);
}
public File getDirtyFile(int i) {
return new File(directory, key + "." + i + ".tmp");
}
}
}
@@ -1,113 +0,0 @@
/*
* Copyright (C) 2015 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.cache;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
public class ImageCache extends AnyCache<Bitmap>{
private static final String TAG = "ImageCache";
/**
* Default memory cache size as a percent of device memory class
*/
private static final float MEM_CACHE_DIVIDER = 0.25f;
/**
* Compression settings when writing images to disk cache
*/
private static final Bitmap.CompressFormat COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG;
/**
* Image compression quality
*/
private static final int COMPRESS_QUALITY = 98;
private static ImageCache sImageCache;
public static @NonNull ImageCache getImageCache(@NonNull Context context) {
if (sImageCache == null) {
final ActivityManager activityManager = (ActivityManager)context
.getSystemService(Context.ACTIVITY_SERVICE);
final int memoryCacheMax = Math.round(MEM_CACHE_DIVIDER * activityManager.getMemoryClass()
* 1024 * 1024);
AnyCacheParams params = new AnyCacheParams();
params.hasMemoryCache = true;
params.memoryCacheMaxSize = memoryCacheMax;
params.hasDiskCache = true;
params.diskCacheDir = getDiskCacheDir(context, TAG);
params.diskCacheMaxSize = 20 * 1024 * 1024;
sImageCache = new ImageCache(params);
}
return sImageCache;
}
public ImageCache(AnyCacheParams params) {
super(params);
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
@Override
protected Bitmap read(InputStream is) {
return BitmapFactory.decodeStream(is);
}
@Override
protected boolean write(OutputStream os, Bitmap value) {
return value.compress(COMPRESS_FORMAT, COMPRESS_QUALITY, os);
}
/**
* Get the external app cache directory
*
* @param context The {@link Context} to use
* @return The external cache directory
*/
private static File getExternalCacheDir(final Context context) {
return context.getExternalCacheDir();
}
/**
* Get a usable cache directory (external if available, internal otherwise)
*
* @param context The {@link Context} to use
* @param uniqueName A unique directory name to append to the cache
* directory
* @return The cache directory
*/
private static File getDiskCacheDir(final Context context, final String uniqueName) {
// getExternalCacheDir(context) returns null if external storage is not ready
final String cachePath = getExternalCacheDir(context) != null
? getExternalCacheDir(context).getPath()
: context.getCacheDir().getPath();
return new File(cachePath, uniqueName);
}
}
@@ -1,196 +0,0 @@
/*
* Copyright (C) 2012 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.ehviewer.cache;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
/**
* Buffers input from an {@link InputStream} for reading lines.
*
* <p>This class is used for buffered reading of lines. For purposes of this class, a line ends
* with "\n" or "\r\n". End of input is reported by throwing {@code EOFException}. Unterminated
* line at end of input is invalid and will be ignored, the caller may use {@code
* hasUnterminatedLine()} to detect it after catching the {@code EOFException}.
*
* <p>This class is intended for reading input that strictly consists of lines, such as line-based
* cache entries or cache journal. Unlike the {@link java.io.BufferedReader} which in conjunction
* with {@link java.io.InputStreamReader} provides similar functionality, this class uses different
* end-of-input reporting and a more restrictive definition of a line.
*
* <p>This class supports only charsets that encode '\r' and '\n' as a single byte with value 13
* and 10, respectively, and the representation of no other character contains these values.
* We currently check in constructor that the charset is one of US-ASCII, UTF-8 and ISO-8859-1.
* The default charset is US_ASCII.
*/
class StrictLineReader implements Closeable {
private static final byte CR = (byte) '\r';
private static final byte LF = (byte) '\n';
private final InputStream in;
private final Charset charset;
/*
* Buffered data is stored in {@code buf}. As long as no exception occurs, 0 <= pos <= end
* and the data in the range [pos, end) is buffered for reading. At end of input, if there is
* an unterminated line, we set end == -1, otherwise end == pos. If the underlying
* {@code InputStream} throws an {@code IOException}, end may remain as either pos or -1.
*/
private byte[] buf;
private int pos;
private int end;
/**
* Constructs a new {@code LineReader} with the specified charset and the default capacity.
*
* @param in the {@code InputStream} to read data from.
* @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
* supported.
* @throws NullPointerException if {@code in} or {@code charset} is null.
* @throws IllegalArgumentException if the specified charset is not supported.
*/
public StrictLineReader(InputStream in, Charset charset) {
this(in, 8192, charset);
}
/**
* Constructs a new {@code LineReader} with the specified capacity and charset.
*
* @param in the {@code InputStream} to read data from.
* @param capacity the capacity of the buffer.
* @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
* supported.
* @throws NullPointerException if {@code in} or {@code charset} is null.
* @throws IllegalArgumentException if {@code capacity} is negative or zero
* or the specified charset is not supported.
*/
public StrictLineReader(InputStream in, int capacity, Charset charset) {
if (in == null || charset == null) {
throw new NullPointerException();
}
if (capacity < 0) {
throw new IllegalArgumentException("capacity <= 0");
}
if (!(charset.equals(Util.US_ASCII))) {
throw new IllegalArgumentException("Unsupported encoding");
}
this.in = in;
this.charset = charset;
buf = new byte[capacity];
}
/**
* Closes the reader by closing the underlying {@code InputStream} and
* marking this reader as closed.
*
* @throws IOException for errors when closing the underlying {@code InputStream}.
*/
public void close() throws IOException {
synchronized (in) {
if (buf != null) {
buf = null;
in.close();
}
}
}
/**
* Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"},
* this end of line marker is not included in the result.
*
* @return the next line from the input.
* @throws IOException for underlying {@code InputStream} errors.
* @throws EOFException for the end of source stream.
*/
public String readLine() throws IOException {
synchronized (in) {
if (buf == null) {
throw new IOException("LineReader is closed");
}
// Read more data if we are at the end of the buffered data.
// Though it's an error to read after an exception, we will let {@code fillBuf()}
// throw again if that happens; thus we need to handle end == -1 as well as end == pos.
if (pos >= end) {
fillBuf();
}
// Try to find LF in the buffered data and return the line if successful.
for (int i = pos; i != end; ++i) {
if (buf[i] == LF) {
int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i;
String res = new String(buf, pos, lineEnd - pos, charset.name());
pos = i + 1;
return res;
}
}
// Let's anticipate up to 80 characters on top of those already read.
ByteArrayOutputStream out = new ByteArrayOutputStream(end - pos + 80) {
@Override
public String toString() {
int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count;
try {
return new String(buf, 0, length, charset.name());
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e); // Since we control the charset this will never happen.
}
}
};
while (true) {
out.write(buf, pos, end - pos);
// Mark unterminated line in case fillBuf throws EOFException or IOException.
end = -1;
fillBuf();
// Try to find LF in the buffered data and return the line if successful.
for (int i = pos; i != end; ++i) {
if (buf[i] == LF) {
if (i != pos) {
out.write(buf, pos, i - pos);
}
pos = i + 1;
return out.toString();
}
}
}
}
}
public boolean hasUnterminatedLine() {
return end == -1;
}
/**
* Reads new input data into the buffer. Call only with pos == end or end == -1,
* depending on the desired outcome if the function throws.
*/
private void fillBuf() throws IOException {
int result = in.read(buf, 0, buf.length);
if (result == -1) {
throw new EOFException();
}
pos = 0;
end = result;
}
}
-77
View File
@@ -1,77 +0,0 @@
/*
* Copyright (C) 2010 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.ehviewer.cache;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.nio.charset.Charset;
/** Junk drawer of utility methods. */
final class Util {
static final Charset US_ASCII = Charset.forName("US-ASCII");
static final Charset UTF_8 = Charset.forName("UTF-8");
private Util() {
}
static String readFully(Reader reader) throws IOException {
try {
StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
int count;
while ((count = reader.read(buffer)) != -1) {
writer.write(buffer, 0, count);
}
return writer.toString();
} finally {
reader.close();
}
}
/**
* Deletes the contents of {@code dir}. Throws an IOException if any file
* could not be deleted, or if {@code dir} is not a readable directory.
*/
static void deleteContents(File dir) throws IOException {
File[] files = dir.listFiles();
if (files == null) {
throw new IOException("not a readable directory: " + dir);
}
for (File file : files) {
if (file.isDirectory()) {
deleteContents(file);
}
if (!file.delete()) {
throw new IOException("failed to delete file: " + file);
}
}
}
static void closeQuietly(/*Auto*/Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
}
@@ -1,54 +0,0 @@
/*
* Copyright (C) 2014 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.cardview;
import android.view.View;
/**
* @author Hippo
*
* A salon to make views look like card
*/
public final class CardViewSalon {
@SuppressWarnings("deprecation")
public static void reform(View view, int bgColor, int boundColor) {
view.setBackgroundDrawable(new RoundRectDrawable(
bgColor, boundColor));
}
@SuppressWarnings("deprecation")
public static void reform(View view, int[][] stateSets, int[] bgColors,
int[] boundColors) {
view.setBackgroundDrawable(new RoundRectDrawable(
stateSets, bgColors, boundColors));
}
@SuppressWarnings("deprecation")
public static void reformWithShadow(View view, int bgColor, int boundColor,
boolean keepPadding) {
view.setBackgroundDrawable(new RoundRectDrawableWithShadow(
bgColor, boundColor, keepPadding));
}
@SuppressWarnings("deprecation")
public static void reformWithShadow(View view, int[][] stateSets, int[] bgColors,
int[] boundColors, boolean keepPadding) {
view.setBackgroundDrawable(new RoundRectDrawableWithShadow(
stateSets, bgColors, boundColors, keepPadding));
}
}
@@ -1,164 +0,0 @@
/*
* Copyright (C) 2014 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.cardview;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.StateSet;
import com.hippo.ehviewer.util.Ui;
// Get most code from android.support.v7.widget.CardViewEclairMr1
public class RoundRectDrawable extends Drawable {
protected final float mCornerRadius;
private final int[][] mStateSets;
private final int[] mBgColors;
private final int[] mBoundColors;
private final Paint mBgPaint;
private final Paint mBoundPaint;
private int mLastIndex = -1;
protected final RectF mTempRectF = new RectF();
public RoundRectDrawable(int bgColor, int boundColor) {
mCornerRadius = Ui.dp2pix(2);
mStateSets = null;
mBgColors = null;
mBoundColors = null;
mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
mBgPaint.setColor(bgColor);
if (boundColor == 0) {
mBoundPaint = null;
} else {
mBoundPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
mBoundPaint.setColor(boundColor);
}
}
public RoundRectDrawable(int[][] stateSets, int[] bgColors, int[] boundColors) {
mCornerRadius = Ui.dp2pix(2);
mStateSets = stateSets;
mBgColors = bgColors;
mBoundColors = boundColors;
mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
if (mBoundColors == null) {
mBoundPaint = null;
} else {
mBoundPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
}
}
@Override
public boolean isStateful() {
return mStateSets != null;
}
@Override
protected boolean onStateChange(int[] stateSet) {
final int N = mStateSets.length;
for (int i = 0; i < N; i++) {
if (StateSet.stateSetMatches(mStateSets[i], stateSet)) {
if (mLastIndex == i)
return false;
mLastIndex = i;
mBgPaint.setColor(mBgColors[i]);
if (mBoundColors != null)
mBoundPaint.setColor(mBoundColors[i]);
invalidateSelf();
return true;
}
}
return false;
}
@Override
public void draw(Canvas canvas) {
drawBody(canvas, new RectF(getBounds()));
}
protected void drawBody(Canvas canvas, RectF bounds) {
if (mBoundPaint == null && Build.VERSION.SDK_INT >= 17) {
canvas.drawRoundRect(bounds, mCornerRadius, mCornerRadius, mBgPaint);
} else {
final float twoRadius = mCornerRadius * 2;
final float innerWidth = bounds.width() - twoRadius;
final float innerHeight = bounds.height() - twoRadius;
Paint drawBoundsPaint = mBoundPaint == null ? mBgPaint : mBoundPaint;
// Draw four corner
mTempRectF.set(bounds.left, bounds.top,
bounds.left + mCornerRadius * 2, bounds.top + mCornerRadius * 2);
canvas.drawArc(mTempRectF, 180, 90, true, drawBoundsPaint);
mTempRectF.offset(innerWidth, 0);
canvas.drawArc(mTempRectF, 270, 90, true, drawBoundsPaint);
mTempRectF.offset(0, innerHeight);
canvas.drawArc(mTempRectF, 0, 90, true, drawBoundsPaint);
mTempRectF.offset(-innerWidth, 0);
canvas.drawArc(mTempRectF, 90, 90, true, drawBoundsPaint);
//draw top and bottom pieces
canvas.drawRect(bounds.left + mCornerRadius, bounds.top,
bounds.right - mCornerRadius, bounds.top + mCornerRadius,
drawBoundsPaint);
canvas.drawRect(bounds.left + mCornerRadius,
bounds.bottom - mCornerRadius, bounds.right - mCornerRadius,
bounds.bottom, drawBoundsPaint);
if (mBoundPaint == null) {
// No bounds color, just draw center and left and right at same time
canvas.drawRect(bounds.left, bounds.top + mCornerRadius,
bounds.right, bounds.bottom - mCornerRadius, mBgPaint);
} else {
// Draw left and right pieces
canvas.drawRect(bounds.left, bounds.top + mCornerRadius,
bounds.left + mCornerRadius, bounds.bottom - mCornerRadius,
drawBoundsPaint);
canvas.drawRect(bounds.right - mCornerRadius, bounds.top + mCornerRadius,
bounds.right, bounds.bottom - mCornerRadius, drawBoundsPaint);
// Draw center
canvas.drawRect(bounds.left + mCornerRadius, bounds.top + mCornerRadius,
bounds.right - mCornerRadius, bounds.bottom - mCornerRadius, mBgPaint);
}
}
}
@Override
public void setAlpha(int alpha) {
// not supported
}
@Override
public void setColorFilter(ColorFilter cf) {
// not supported
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}
@@ -1,192 +0,0 @@
/*
* Copyright (C) 2014 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.cardview;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import com.hippo.ehviewer.util.Ui;
// Get most code from android.support.v7.widget.RoundRectDrawableWithShadow
public class RoundRectDrawableWithShadow extends RoundRectDrawable {
private final static float SHADOW_MULTIPLIER = 1.5f;
private int mShadowStartColor;
private int mShadowEndColor;
private float mShadowSize;
private Paint mCornerShadowPaint;
private Paint mEdgeShadowPaint;
private final RectF mPreShadowBounds = new RectF();
private final Path mCornerShadowPath = new Path();
private boolean mDirty = true;
private final boolean mKeepPadding;
public RoundRectDrawableWithShadow(int bgColor, int boundColor,
boolean keepPadding) {
super(bgColor, boundColor);
mKeepPadding = keepPadding;
init();
}
public RoundRectDrawableWithShadow(int[][] stateSets,
int[] bgColors, int[] boundColors, boolean keepPadding) {
super(stateSets, bgColors, boundColors);
mKeepPadding = keepPadding;
init();
}
private void init() {
mShadowStartColor = 0x37000000;
mShadowEndColor = 0x03000000;
mShadowSize = Ui.dp2pix(2) * SHADOW_MULTIPLIER;
mCornerShadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
mCornerShadowPaint.setStyle(Paint.Style.FILL);
mCornerShadowPaint.setDither(true);
mEdgeShadowPaint = new Paint(mCornerShadowPaint);
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mDirty = true;
}
@Override
public boolean getPadding(Rect padding) {
if (mKeepPadding) {
return false;
} else {
padding.set(getSuggestionPadding());
return true;
}
}
public Rect getSuggestionPadding() {
Rect padding = new Rect();
final int topShadow = (int) Math.ceil(mShadowSize * (1 / (SHADOW_MULTIPLIER * 2)));
final int sideShadow = (int) Math.ceil(mShadowSize - topShadow);
padding.set(sideShadow, topShadow, sideShadow, (int) Math.ceil(mShadowSize));
return padding;
}
private void buildShadowCorners() {
RectF innerBounds = new RectF(-mCornerRadius, -mCornerRadius, mCornerRadius, mCornerRadius);
RectF outerBounds = new RectF(innerBounds);
outerBounds.inset(-mShadowSize, -mShadowSize);
mCornerShadowPath.reset();
mCornerShadowPath.setFillType(Path.FillType.EVEN_ODD);
mCornerShadowPath.moveTo(-mCornerRadius, 0);
mCornerShadowPath.rLineTo(-mShadowSize, 0);
// outer arc
mCornerShadowPath.arcTo(outerBounds, 180f, 90f, false);
// inner arc
mCornerShadowPath.arcTo(innerBounds, 270f, -90f, false);
mCornerShadowPath.close();
float startRatio = mCornerRadius / (mCornerRadius + mShadowSize);
mCornerShadowPaint.setShader(new RadialGradient(0, 0, mCornerRadius + mShadowSize,
new int[]{mShadowStartColor, mShadowStartColor, mShadowEndColor},
new float[]{0f, startRatio, 1f}
, Shader.TileMode.CLAMP));
// we offset the content shadowSize/2 pixels up to make it more realistic.
// this is why edge shadow shader has some extra space
// When drawing bottom edge shadow, we use that extra space.
mEdgeShadowPaint.setShader(new LinearGradient(0, -mCornerRadius + mShadowSize, 0,
-mCornerRadius - mShadowSize,
new int[]{mShadowStartColor, mShadowStartColor, mShadowEndColor},
new float[]{0f, .5f, 1f}, Shader.TileMode.CLAMP));
}
private void buildComponents(Rect bounds) {
mPreShadowBounds.set(bounds.left + mShadowSize, bounds.top + mShadowSize,
bounds.right - mShadowSize, bounds.bottom - mShadowSize);
buildShadowCorners();
}
@Override
public void draw(Canvas canvas) {
if (mDirty) {
buildComponents(getBounds());
mDirty = false;
}
drawShadow(canvas);
final float offset = mShadowSize * (1 - 1 / (SHADOW_MULTIPLIER * 2));
final float horizontalOffset = mShadowSize - offset;
canvas.translate(0, -offset);
mPreShadowBounds.bottom += offset;
mPreShadowBounds.left -= horizontalOffset;
mPreShadowBounds.right += horizontalOffset;
drawBody(canvas, mPreShadowBounds);
mPreShadowBounds.bottom -= offset;
mPreShadowBounds.left += horizontalOffset;
mPreShadowBounds.right -= horizontalOffset;
canvas.translate(0, offset);
}
private void drawShadow(Canvas canvas) {
int saved = canvas.save();
float cornerPathSize = 2 * (mCornerRadius + mShadowSize);
float edgeShadowTop = -mCornerRadius - mShadowSize;
final Rect bounds = getBounds();
// LT
canvas.translate(mPreShadowBounds.left + mCornerRadius,
mPreShadowBounds.top + mCornerRadius);
canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
canvas.drawRect(0, edgeShadowTop,
bounds.right - cornerPathSize, -mCornerRadius,
mEdgeShadowPaint);
// RB
canvas.rotate(180f);
canvas.translate(-bounds.width() + cornerPathSize, -bounds.height() + cornerPathSize);
canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
canvas.drawRect(0, edgeShadowTop,
bounds.right - cornerPathSize, -mCornerRadius + mShadowSize,
mEdgeShadowPaint);
// LB
canvas.rotate(90f);
canvas.translate(0, -bounds.width() + cornerPathSize);
canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
canvas.drawRect(0, edgeShadowTop,
bounds.bottom - cornerPathSize, -mCornerRadius,
mEdgeShadowPaint);
// RT
canvas.rotate(180f);
canvas.translate(-bounds.height() + cornerPathSize, -bounds.width() + cornerPathSize);
canvas.drawPath(mCornerShadowPath, mCornerShadowPaint);
canvas.drawRect(0, edgeShadowTop,
bounds.bottom - cornerPathSize, -mCornerRadius,
mEdgeShadowPaint);
canvas.restoreToCount(saved);
}
}
@@ -0,0 +1,44 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 2/3/2017.
*/
import android.net.Uri;
import com.facebook.imagepipeline.cache.DefaultCacheKeyFactory;
/**
* A {@code EhCacheKeyFactory} detects ehentai thumbnail url,
* create the same source url for the thumbnail urls with the same fingerprint.
*/
public class EhCacheKeyFactory extends DefaultCacheKeyFactory {
private static final String EH_THUMBNAIL_SCHEME = "eh_thumbnail";
@Override
protected Uri getCacheKeySourceUri(Uri sourceUri) {
String url = sourceUri.toString();
String fingerprint = EhUrl.getThumbnailFingerprint(url);
if (fingerprint != null) {
return new Uri.Builder().scheme(EH_THUMBNAIL_SCHEME).path(fingerprint).build();
} else {
return sourceUri;
}
}
}
@@ -0,0 +1,302 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/18/2017.
*/
import android.content.Context;
import com.hippo.ehviewer.EhvApp;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.param.GalleryMetadataParam;
import com.hippo.ehviewer.client.result.FavouritesResult;
import com.hippo.ehviewer.client.result.ForumsResult;
import com.hippo.ehviewer.client.result.GalleryDetailResult;
import com.hippo.ehviewer.client.result.GalleryListResult;
import com.hippo.ehviewer.client.result.GalleryMetadataResult;
import com.hippo.ehviewer.client.result.ProfileResult;
import com.hippo.ehviewer.client.result.SignInResult;
import com.hippo.ehviewer.client.result.VoidResult;
import com.hippo.ehviewer.client.result.WhatsHotResult;
import com.hippo.ehviewer.util.MutableObject;
import com.hippo.yorozuya.ArrayUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.Result;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;
// TODO Let EhClient generate url
public final class EhClient {
private static final int GALLERY_METADATA_MAX_COUNT = 25;
private EhEngine engine;
/**
* Create a {@code EhClient} with a {@link EhEngine}.
*/
public EhClient(EhEngine engine) {
this.engine = engine;
}
/**
* Sign in with username and password.
*/
public Observable<Result<SignInResult>> signIn(String userName, String passWord) {
return engine.signIn(
"https://forums.e-hentai.org/index.php?",
"",
"",
userName,
passWord,
"1");
}
/**
* Sign in with username, password and recaptcha.
*/
public Observable<Result<SignInResult>> signIn(String userName, String passWord,
String recaptchaChallenge, String recaptchaResponse) {
return engine.signIn(
"https://forums.e-hentai.org/index.php?",
"",
"",
userName,
passWord,
recaptchaChallenge,
recaptchaResponse,
"1");
}
/**
* Gets user profile, name and avatar.
*/
public Observable<Result<ProfileResult>> profile() {
return engine.forums()
.flatMap(new EhFlatMapFunc<ForumsResult, ProfileResult>() {
@Override
public Observable<Result<ProfileResult>> onCall(ForumsResult result) {
return engine.profile(result.profileUrl());
}
});
}
/**
* Just get https://exhentai.org/ and https://exhentai.org/favorites.php to get cookies.
* <p>
* Only call it after signing in.
*/
public Observable<Result<VoidResult>> touchEHentai() {
return engine.touchEHentaiFavourite();
}
/**
* Just get https://exhentai.org/ and https://exhentai.org/favorites.php to get cookies.
* <p>
* Only call it after signing in.
*/
public Observable<Result<VoidResult>> touchExHentai() {
return engine.touchExHentai()
.flatMap(new EhFlatMapFunc<VoidResult, VoidResult>() {
@Override
public Observable<Result<VoidResult>> onCall(VoidResult voidResult) {
return engine.touchExHentaiFavourite();
}
});
}
private static GalleryMetadataParam genGalleryMetadataParam(long[] gids, String[] tokens, int start,
int count) {
return new GalleryMetadataParam(Arrays.copyOfRange(gids, start, start + count),
Arrays.copyOfRange(tokens, start, start + count));
}
/**
* Gets gallery metadata of the input gallery gid and token array through API.
* <p>
* If one token doesn't match the gid, raise error.
* <p>
* If contains duplicate gid, only return once.
*/
public Observable<Result<GalleryMetadataResult>> getGalleryMetadata(@EhUrl.Site int site,
long[] gids, String[] tokens) {
int remain = Math.min(ArrayUtils.getLength(gids), ArrayUtils.getLength(tokens));
if (remain <= 0) {
return Observable.just(
Result.response(Response.success(new GalleryMetadataResult(Collections.emptyList()))));
}
// Remove duplicates
List<Long> gidList = new ArrayList<>(gids.length);
List<String> tokenList = new ArrayList<>(tokens.length);
for (int i = 0, n = gids.length; i < n; ++i) {
long g = gids[i];
boolean duplicate = false;
for (int j = i + 1; j < n; ++j) {
if (g == gids[j]) {
duplicate = true;
break;
}
}
if (!duplicate) {
gidList.add(g);
tokenList.add(tokens[i]);
}
}
gids = new long[gidList.size()];
for (int i = 0, n = gidList.size(); i < n; ++i) {
gids[i] = gidList.get(i);
}
tokens = tokenList.toArray(new String[tokenList.size()]);
// Update remain
remain = Math.min(ArrayUtils.getLength(gids), ArrayUtils.getLength(tokens));
// Ehentai only support 25 items per api.
// Api might be called more than once.
// The results should be merged.
String url = EhUrl.getApiUrl(site);
List<GalleryInfo> list = new ArrayList<>(remain);
Observable<Result<GalleryMetadataResult>> observable;
int read = 0;
int single = Math.min(remain, GALLERY_METADATA_MAX_COUNT);
observable = engine.getGalleryMetadata(url,
genGalleryMetadataParam(gids, tokens, read, single));
read += single;
remain -= single;
boolean merge = false;
while (true) {
single = Math.min(remain, GALLERY_METADATA_MAX_COUNT);
if (single == 0) {
break;
}
merge = true;
// Merge previous result to a list, call api again
final GalleryMetadataParam param = genGalleryMetadataParam(gids, tokens, read, single);
observable = observable.flatMap(new EhFlatMapFunc<GalleryMetadataResult, GalleryMetadataResult>() {
@Override
public Observable<Result<GalleryMetadataResult>> onCall(GalleryMetadataResult result) {
list.addAll(result.galleryInfoList());
return engine.getGalleryMetadata(url, param);
}
});
read += single;
remain -= single;
}
if (merge) {
// Merge previous result, return the final result
observable = observable.map(new EhMapFunc<GalleryMetadataResult, GalleryMetadataResult>() {
@Override
public Result<GalleryMetadataResult> onCall(GalleryMetadataResult result) {
list.addAll(result.galleryInfoList());
return Result.response(Response.success(new GalleryMetadataResult(list)));
}
});
}
return observable;
}
/**
* Get gallery list.
*/
// TODO handles favourites
public Observable<Result<GalleryListResult>> getGalleryList(String url, Map<String, String> query) {
return engine.getGalleryList(url, query);
}
/**
* Gets what's hot.
*/
public Observable<Result<WhatsHotResult>> getWhatsHot(final int site) {
final MutableObject<WhatsHotResult> holder = new MutableObject<>();
return engine.getWhatsHot()
.flatMap(new EhFlatMapFunc<WhatsHotResult, GalleryMetadataResult>() {
@Override
public Observable<Result<GalleryMetadataResult>> onCall(WhatsHotResult whatsHotResult) {
holder.value = whatsHotResult;
List<GalleryInfo> list = whatsHotResult.galleryInfoList();
int size = list.size();
long[] gids = new long[size];
String[] tokens = new String[size];
int i = 0;
for (GalleryInfo info: list) {
gids[i] = info.gid;
tokens[i] = info.token;
++i;
}
return getGalleryMetadata(site, gids, tokens);
}
}).map(new EhMapFunc<GalleryMetadataResult, WhatsHotResult>() {
@Override
public Result<WhatsHotResult> onCall(GalleryMetadataResult result) {
WhatsHotResult whatsHotResult = holder.value;
List<GalleryInfo> metadata = result.galleryInfoList();
for (GalleryInfo info: whatsHotResult.galleryInfoList()) {
info.merge(metadata);
}
return Result.response(Response.success(whatsHotResult));
}
});
}
/**
* Gets favourites.
*/
public Observable<Result<FavouritesResult>> getFavourites(String url, Map<String, String> query) {
return engine.getFavourites(url, query);
}
/**
* Gets gallery detail.
*/
public Observable<Result<GalleryDetailResult>> getGalleryDetail(int site, long gid, String token) {
return engine.getGalleryDetail(EhUrl.getGalleryDetailUrl(site, gid, token));
}
/**
* Create a {@code EhClient} with default {@link EhEngine}.
*/
public static EhClient create(Context context) {
EhvApp app = (EhvApp) context.getApplicationContext();
Retrofit retrofit = new Retrofit.Builder()
// Base url is useless, but it makes Retrofit happy
.baseUrl("http://www.ehviewer.com/")
.client(app.getOkHttpClient())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(EhConverterFactory.create())
.build();
EhEngine engine = retrofit.create(EhEngine.class);
return new EhClient(engine);
}
}
@@ -1,11 +1,11 @@
/*
* Copyright (C) 2014 Hippo Seven
* 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
* 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,
@@ -14,8 +14,15 @@
* limitations under the License.
*/
package com.hippo.ehviewer.exception;
package com.hippo.ehviewer.client;
/*
* Created by Hippo on 1/29/2017.
*/
/**
*
*/
public class EhConfig {
public class NoSdCardException extends Exception {
private static final long serialVersionUID = 1L;
}
@@ -0,0 +1,70 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/18/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.exception.SadPandaException;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;
/**
* Base {@link Converter} of {@link com.hippo.ehviewer.client.EhClient}.
*/
public abstract class EhConverter<T extends EhResult> implements Converter<ResponseBody, T> {
private static final MediaType SAD_PANDA_MEDIA_TYPE = MediaType.parse("image/gif");
private static final long SAD_PANDA_CONTENT_LENGTH = 9615L;
private void checkSadPanda(ResponseBody value) throws SadPandaException {
if (SAD_PANDA_CONTENT_LENGTH == value.contentLength()
&& SAD_PANDA_MEDIA_TYPE.equals(value.contentType())) {
throw new SadPandaException();
}
}
@Override
public final T convert(ResponseBody value) throws IOException {
try {
checkSadPanda(value);
String body = value.string();
return convert(body);
} catch (Throwable e) {
return error(e);
} finally {
value.close();
}
}
/**
* Converts body string to result object.
*/
@NonNull
public abstract T convert(String body) throws Exception;
/**
* Wraps the {@link Throwable} to a result object.
*/
// TODO It's pain. I need a better way.
@NonNull
public abstract T error(Throwable t);
}
@@ -0,0 +1,84 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/15/2017.
*/
import com.hippo.ehviewer.client.converter.FavouritesConverter;
import com.hippo.ehviewer.client.converter.ForumsConverter;
import com.hippo.ehviewer.client.converter.GalleryDetailConverter;
import com.hippo.ehviewer.client.converter.GalleryListConverter;
import com.hippo.ehviewer.client.converter.GalleryMetadataConverter;
import com.hippo.ehviewer.client.converter.ProfileConverter;
import com.hippo.ehviewer.client.converter.SignInConverter;
import com.hippo.ehviewer.client.converter.VoidConverter;
import com.hippo.ehviewer.client.converter.WhatsHotConverter;
import com.hippo.ehviewer.client.param.GalleryMetadataParam;
import com.hippo.ehviewer.client.result.FavouritesResult;
import com.hippo.ehviewer.client.result.ForumsResult;
import com.hippo.ehviewer.client.result.GalleryDetailResult;
import com.hippo.ehviewer.client.result.GalleryListResult;
import com.hippo.ehviewer.client.result.GalleryMetadataResult;
import com.hippo.ehviewer.client.result.ProfileResult;
import com.hippo.ehviewer.client.result.SignInResult;
import com.hippo.ehviewer.client.result.VoidResult;
import com.hippo.ehviewer.client.result.WhatsHotResult;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* A {@code Converter.Factory} to create {@link EhConverter}.
*/
public final class EhConverterFactory extends Converter.Factory {
private EhConverterFactory() {}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
if (SignInResult.class.equals(type)) return SignInConverter.INSTANCE;
else if (VoidResult.class.equals(type)) return VoidConverter.INSTANCE;
else if (GalleryListResult.class.equals(type)) return GalleryListConverter.INSTANCE;
else if (ForumsResult.class.equals(type)) return ForumsConverter.INSTANCE;
else if (ProfileResult.class.equals(type)) return ProfileConverter.INSTANCE;
else if (WhatsHotResult.class.equals(type)) return WhatsHotConverter.INSTANCE;
else if (GalleryMetadataResult.class.equals(type)) return GalleryMetadataConverter.INSTANCE;
else if (FavouritesResult.class.equals(type)) return FavouritesConverter.INSTANCE;
else if (GalleryDetailResult.class.equals(type)) return GalleryDetailConverter.INSTANCE;
else throw new IllegalStateException("Unknown type: " + type);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if (GalleryMetadataParam.class.equals(type)) return new GalleryMetadataParam.Converter();
else return null;
}
/**
* Create a {@code EhConverterFactory}.
*/
public static EhConverterFactory create() {
return new EhConverterFactory();
}
}
@@ -0,0 +1,74 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/25/2017.
*/
import android.content.Context;
import com.hippo.ehviewer.network.CookieRepository;
import com.hippo.yorozuya.ArrayUtils;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.HttpUrl;
/**
* {@code EhCookieJar} makes persistent non-expired cookies which from ehentai domains long live.
*/
public class EhCookieJar extends CookieRepository {
private static final String[] LONG_LIVE_DOMAINS = {
EhUrl.DOMAIN_E,
EhUrl.DOMAIN_EX,
};
public EhCookieJar(Context context, String dbName) {
super(context, dbName);
}
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
// Make persistent non-expired cookies in LONG_LIVE_DOMAINS long live
List<Cookie> list = new ArrayList<>(cookies.size());
for (Cookie cookie: cookies) {
if (ArrayUtils.contains(LONG_LIVE_DOMAINS, cookie.domain())
&& cookie.persistent()
&& cookie.expiresAt() >= System.currentTimeMillis()) {
Cookie.Builder builder = new Cookie.Builder();
builder.name(cookie.name());
builder.value(cookie.value());
if (cookie.hostOnly()) {
builder.hostOnlyDomain(cookie.domain());
} else {
builder.domain(cookie.domain());
}
builder.path(cookie.path());
// Long Live
builder.expiresAt(Long.MAX_VALUE);
if (cookie.secure()) builder.secure();
if (cookie.httpOnly()) builder.httpOnly();
list.add(builder.build());
} else {
list.add(cookie);
}
}
super.saveFromResponse(url, list);
}
}
@@ -0,0 +1,112 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/14/2017.
*/
import com.hippo.ehviewer.client.param.GalleryMetadataParam;
import com.hippo.ehviewer.client.result.FavouritesResult;
import com.hippo.ehviewer.client.result.ForumsResult;
import com.hippo.ehviewer.client.result.GalleryDetailResult;
import com.hippo.ehviewer.client.result.GalleryListResult;
import com.hippo.ehviewer.client.result.GalleryMetadataResult;
import com.hippo.ehviewer.client.result.ProfileResult;
import com.hippo.ehviewer.client.result.SignInResult;
import com.hippo.ehviewer.client.result.VoidResult;
import com.hippo.ehviewer.client.result.WhatsHotResult;
import java.util.Map;
import retrofit2.adapter.rxjava.Result;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;
import rx.Observable;
public interface EhEngine {
@FormUrlEncoded
@POST(EhUrl.URL_SIGN_IN)
Observable<Result<SignInResult>> signIn(
@Field("referer") String referer,
@Field("b") String b,
@Field("bt") String bt,
@Field("UserName") String userName,
@Field("PassWord") String passWord,
@Field("CookieDate") String cookieDate
);
@FormUrlEncoded
@POST(EhUrl.URL_SIGN_IN)
Observable<Result<SignInResult>> signIn(
@Field("referer") String referer,
@Field("b") String b,
@Field("bt") String bt,
@Field("UserName") String userName,
@Field("PassWord") String passWord,
@Field("recaptcha_challenge_field") String recaptchaChallenge,
@Field("recaptcha_response_field") String recaptchaResponse,
@Field("CookieDate") String cookieDate
);
@GET(EhUrl.URL_FORUMS)
Observable<Result<ForumsResult>> forums();
@GET
Observable<Result<ProfileResult>> profile(
@Url String url
);
@GET(EhUrl.URL_FAVOURITES_E)
Observable<Result<VoidResult>> touchEHentaiFavourite();
@GET(EhUrl.URL_EX)
Observable<Result<VoidResult>> touchExHentai();
@GET(EhUrl.URL_FAVOURITES_EX)
Observable<Result<VoidResult>> touchExHentaiFavourite();
@POST
Observable<Result<GalleryMetadataResult>> getGalleryMetadata(
@Url String url,
@Body GalleryMetadataParam param
);
@GET
Observable<Result<GalleryListResult>> getGalleryList(
@Url String url,
@QueryMap Map<String, String> query
);
@GET(EhUrl.URL_E)
Observable<Result<WhatsHotResult>> getWhatsHot();
@GET
Observable<Result<FavouritesResult>> getFavourites(
@Url String url,
@QueryMap Map<String, String> query
);
@GET
Observable<Result<GalleryDetailResult>> getGalleryDetail(
@Url String url
);
}
@@ -0,0 +1,36 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/19/2017.
*/
import retrofit2.adapter.rxjava.Result;
import rx.Observable;
import rx.functions.Func1;
public abstract class EhFlatMapFunc<T extends EhResult, R extends EhResult>
implements Func1<Result<T>, Observable<Result<R>>> {
@Override
public Observable<Result<R>> call(Result<T> result) {
return EhReactiveX.handleResult(result, this::onCall);
}
public abstract Observable<Result<R>> onCall(T t);
}
@@ -0,0 +1,35 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/19/2017.
*/
import retrofit2.adapter.rxjava.Result;
import rx.functions.Func1;
public abstract class EhMapFunc<T extends EhResult, R extends EhResult>
implements Func1<Result<T>, Result<R>> {
@Override
public Result<R> call(Result<T> result) {
return EhReactiveX.handleResult(result, this::onCall);
}
public abstract Result<R> onCall(T t);
}
@@ -0,0 +1,154 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/19/2017.
*/
import com.hippo.ehviewer.client.exception.ErrorWrapper;
import com.hippo.ehviewer.client.exception.GeneralException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.exception.RuntimeExceptionWrapper;
import com.hippo.ehviewer.client.exception.SadPandaException;
import com.hippo.ehviewer.client.exception.StatusCodeException;
import com.hippo.ehviewer.reactivex.ThrowableWrapper;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.adapter.rxjava.Result;
import rx.exceptions.Exceptions;
import rx.functions.Action1;
import rx.functions.Func1;
/**
* Helps RxJava.
*/
final class EhReactiveX {
private EhReactiveX() {}
// TODO Is it suitable?
private static final int PLAIN_NOTICE_MAX_LENGTH = 512;
/**
* Handles {@link Throwable}.
* {@code handler} do the actual job.
*/
public static void handleError(Throwable e, Action1<Throwable> handler) {
// Unwraps RuntimeExceptionWrapper and ErrorWrapper,
// and throws them. They are thrown by onSuccess().
if (e instanceof RuntimeExceptionWrapper) {
throw ((RuntimeExceptionWrapper) e).unwrap();
}
if (e instanceof ErrorWrapper) {
throw ((ErrorWrapper) e).unwrap();
}
// Unwrap ThrowableWrapper which wrapped in onNext()
if (e instanceof ThrowableWrapper) {
e = ((ThrowableWrapper) e).unwrap();
}
handler.call(e);
}
/**
* Handles {@link Result}, get error from it.
* {@code handler} do the actual job.
* <p>
* Call {@link #handleError(Throwable, Action1)} to handle error.
*/
public static <T extends EhResult, R> R handleResult(Result<T> result, Func1<T, R> handler) {
// Wraps all kinds of throwable in ThrowableWrapper,
// let onError() handle it.
if (result.isError()) {
Throwable error = result.error();
Exceptions.throwIfFatal(error);
throw ThrowableWrapper.wrap(error);
} else {
Response<T> response = result.response();
if (response.isSuccessful()) {
T body = response.body();
if (body.isError()) {
Throwable error = body.error();
Exceptions.throwIfFatal(error);
throw ThrowableWrapper.wrap(fixError(error, response.raw()));
} else {
// Only one of onSuccess() and onFailure() can be called.
// We must catch unchecked exceptions thrown by onSuccess()
// to avoid onFailure() calling it.
try {
return handler.call(body);
} catch (RuntimeException e) {
throw RuntimeExceptionWrapper.wrap(e);
} catch (Error e) {
throw ErrorWrapper.wrap(e);
}
}
} else {
throw ThrowableWrapper.wrap(catchError(response.errorBody(), response.raw()));
}
}
}
private static Throwable fixError(Throwable t, okhttp3.Response response) {
// Always throw SadPandaException first
if (t instanceof SadPandaException) return t;
if (t instanceof ParseException) {
ParseException pe = (ParseException) t;
pe.url(response.request().url());
String body = pe.body();
// If a body don't contains '<' and not too long, it should be a plain txt,
// and it might be a notice.
// TODO What if it's a JSON?
if (!body.contains("<") && body.length() <= PLAIN_NOTICE_MAX_LENGTH && body.length() >= 0) {
t = new GeneralException(body, pe);
}
}
// Don't let bad status code covers EhException
if (t instanceof GeneralException) return t;
if (!response.isSuccessful()) {
t = new StatusCodeException(response.code(), t);
}
return t;
}
private static Throwable catchError(ResponseBody errorBody, okhttp3.Response response) {
try {
String body = errorBody.string();
// If a body don't contains '<' and not too long, it should be a plain txt,
// and it might be a notice.
// TODO What if it's a JSON?
if (!body.contains("<") && body.length() <= PLAIN_NOTICE_MAX_LENGTH && body.length() >= 0) {
return new GeneralException(body);
}
// Only bad status code cause this
return new StatusCodeException(response.code());
} catch (IOException e) {
return e;
} finally {
errorBody.close();
}
}
}
@@ -0,0 +1,51 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/18/2017.
*/
/**
* A base result for {@link com.hippo.ehviewer.client.EhClient}.
* <p>
* {@link retrofit2.adapter.rxjava.Result} in {@link retrofit2.adapter.rxjava.RxJavaCallAdapterFactory}
* doesn't support error and response at the same time.
* But I need response to fix error, so wrap error in result.
*/
public abstract class EhResult {
private final Throwable error;
public EhResult(Throwable error) {
this.error = error;
}
/**
* Only present when {@link #isError()} is true, null otherwise.
*/
public Throwable error() {
return error;
}
/**
* Returns {@code true} if the result is an error.
*/
public boolean isError() {
return error != null;
}
}
@@ -0,0 +1,117 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/18/2017.
*/
import retrofit2.adapter.rxjava.Result;
import rx.Subscriber;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;
/**
* A base {@link Subscriber} for {@link EhClient}.
*/
public abstract class EhSubscriber<T extends EhResult> extends Subscriber<Result<T>> {
// Use from() instead
private EhSubscriber() {}
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {
EhReactiveX.handleError(e, this::onFailure);
}
@Override
public void onNext(Result<T> result) {
EhReactiveX.handleResult(result, t -> {
onSuccess(t);
return null;
});
}
/**
* Called if we get the result.
*/
public abstract void onSuccess(T t);
/**
* Called if an error occurred.
*/
public abstract void onFailure(Throwable e);
/**
* Creates a {@code EhSubscriber} from a {@code Action1<T>} and a {@code Action1<Throwable>}.
*/
public static <T extends EhResult> EhSubscriber<T> from(Action1<T> onSuccess,
Action1<Throwable> onFailure) {
return new DelegateEhSubscriber<>(onSuccess, onFailure);
}
/**
* Creates a {@code EhSubscriber} from a {@code Action1<T>} and a {@code Action1<Throwable>},
* adds the subscriber to a {@link CompositeSubscription}.
*/
public static <T extends EhResult> EhSubscriber<T> from(CompositeSubscription subscription,
Action1<T> onSuccess, Action1<Throwable> onFailure) {
return new AutoEhSubscriber<>(subscription, onSuccess, onFailure);
}
// TODO The document doesn't say that the Subscriber passed is the Subscription returned, this class may not work
private static class AutoEhSubscriber<T extends EhResult> extends DelegateEhSubscriber<T> {
private CompositeSubscription subscription;
public AutoEhSubscriber(CompositeSubscription subscription, Action1<T> onSuccess,
Action1<Throwable> onFailure) {
super(onSuccess, onFailure);
this.subscription = subscription;
this.subscription.add(this);
}
@Override
public void onCompleted() {
subscription.remove(this);
}
}
private static class DelegateEhSubscriber<T extends EhResult> extends EhSubscriber<T> {
private final Action1<T> onSuccess;
private final Action1<Throwable> onFailure;
public DelegateEhSubscriber(Action1<T> onSuccess, Action1<Throwable> onFailure) {
this.onSuccess = onSuccess;
this.onFailure = onFailure;
}
@Override
public void onSuccess(T t) {
onSuccess.call(t);
}
@Override
public void onFailure(Throwable e) {
onFailure.call(e);
}
}
}
@@ -0,0 +1,186 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/25/2017.
*/
import android.support.annotation.IntDef;
import android.support.annotation.StringDef;
import com.hippo.yorozuya.StringUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class EhUrl {
private EhUrl() {}
private static final Pattern PATTERN_GID_TOKEN = Pattern.compile("/g/(\\d+)/([0-9a-f]{10})");
// A thumbnail url looks like:
// https://exhentai.org/t/e8/50/e850fc3d8fb7bfea934f66206fb8db8a86f57251-28396-1074-1538-jpg_l.jpg
private static final Pattern PATTERN_THUMBNAIL =
Pattern.compile("/([0-9a-f]{2})/([0-9a-f]{2})/([0-9a-f]{40}-\\d+-\\d+-\\d+-[0-9a-z]+)_([0-9a-zA-Z]+)\\.[0-9a-zA-Z]+");
private static final Pattern PATTERN_IMAGE_FINGERPRINT =
Pattern.compile("[0-9a-f]{40}-\\d+-\\d+-\\d+-[0-9a-z]+");
@IntDef({SITE_E, SITE_EX})
@Retention(RetentionPolicy.SOURCE)
public @interface Site {}
public static final int SITE_E = 0;
public static final int SITE_EX = 1;
public static final String DOMAIN_E = "e-hentai.org";
public static final String DOMAIN_EX = "exhentai.org";
public static final String URL_E = "https://e-hentai.org/";
public static final String URL_EX = "https://exhentai.org/";
public static final String URL_FAVOURITES_E = URL_E + "favorites.php";
public static final String URL_FAVOURITES_EX = URL_EX + "favorites.php";
public static final String URL_THUMBNAIL_E = "https://ehgt.org/";
public static final String URL_THUMBNAIL_EX = "https://exhentai.org/t/";
public static final String URL_API_E = URL_E + "api.php";
public static final String URL_API_EX = URL_EX + "api.php";
public static final String URL_FORUMS = "https://forums.e-hentai.org/";
public static final String URL_SIGN_IN = URL_FORUMS + "index.php?act=Login&CODE=01";
@StringDef({THUMBNAIL_TYPE_L, THUMBNAIL_TYPE_250, THUMBNAIL_TYPE_300})
@Retention(RetentionPolicy.SOURCE)
public @interface ThumbnailType {}
/**
* Width == 200
**/
public static final String THUMBNAIL_TYPE_L = "l";
/**
* Width == 250, only available for cover
*/
public static final String THUMBNAIL_TYPE_250 = "250";
/**
* Width == 300, only available for cover
*/
public static final String THUMBNAIL_TYPE_300 = "300";
/**
* Return site url which ends with "/"
*/
public static String getSiteUrl(int site) {
if (site == SITE_EX) {
return URL_EX;
} else {
return URL_E;
}
}
/**
* Parse image url to fingerprint.
* {@code null} if can't parse it.
* <p>
* Example:
* <ul>
* <li>Url: {@code https://exhentai.org/t/e8/50/e850fc3d8fb7bfea934f66206fb8db8a86f57251-28396-1074-1538-jpg_l.jpg}</li>
* <li>Image fingerprint: {@code e850fc3d8fb7bfea934f66206fb8db8a86f57251-28396-1074-1538-jpg}</li>
* </ul>
*/
public static String getImageFingerprint(String url) {
if (url == null) return null;
Matcher m = PATTERN_THUMBNAIL.matcher(url);
if (m.find()) {
String g1 = m.group(1);
String g2 = m.group(2);
String g3 = m.group(3);
if (g1.equals(g3.substring(0, 2)) && g2.equals(g3.substring(2, 4))) {
return g3;
}
}
return null;
}
/**
* Parse image url to fingerprint.
* {@code null} if can't parse it.
* <p>
* Example:
* <ul>
* <li>Url: {@code https://exhentai.org/t/e8/50/e850fc3d8fb7bfea934f66206fb8db8a86f57251-28396-1074-1538-jpg_l.jpg}</li>
* <li>Image fingerprint: {@code e850fc3d8fb7bfea934f66206fb8db8a86f57251-28396-1074-1538-jpg_l}</li>
* </ul>
*/
public static String getThumbnailFingerprint(String url) {
if (url == null) return null;
Matcher m = PATTERN_THUMBNAIL.matcher(url);
if (m.find()) {
String g1 = m.group(1);
String g2 = m.group(2);
String g3 = m.group(3);
String g4 = m.group(4);
if (g1.equals(g3.substring(0, 2)) && g2.equals(g3.substring(2, 4))) {
return g3 + "_" + g4;
}
}
return null;
}
/**
* Gets thumbnail url.
* The {@code fingerprint} is not checked, but
* {@code null} is returned if the {@code fingerprint}
* doesn't support the method.
*/
public static String getThumbnailUrl(String fingerprint,
@Site int site, @ThumbnailType String type) {
if (fingerprint == null || fingerprint.length() < 4) return null;
String url;
if (site == SITE_EX) {
url = URL_THUMBNAIL_EX;
} else {
url = URL_THUMBNAIL_E;
}
return url + fingerprint.substring(0, 2) + "/" + fingerprint.substring(2, 4)
+ "/" + fingerprint + "_" + type + ".jpg";
}
public static String getFavouritesUrl(int site) {
if (site == SITE_EX) {
return URL_FAVOURITES_EX;
} else {
return URL_FAVOURITES_E;
}
}
public static String getApiUrl(@Site int site) {
if (site == SITE_EX) {
return URL_API_EX;
} else {
return URL_API_E;
}
}
/**
* Returns the gallery detail url.
* Like: {@code https://exhentai.org/g/1064283/49faede5c5/}
*/
public static String getGalleryDetailUrl(@Site int site, long gid, String token) {
return StringUtils.join(getSiteUrl(site), "/g/" + gid + "/" + token + "/", '/');
}
}
@@ -0,0 +1,499 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/29/2017.
*/
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.R;
import com.hippo.yorozuya.StringUtils;
import java.util.Locale;
import java.util.regex.Pattern;
public final class EhUtils {
private EhUtils() {}
///////////////////////////////////////////////////////////////////////////
// Gallery Category
///////////////////////////////////////////////////////////////////////////
public static final int CATEGORY_MISC = 0x1;
public static final int CATEGORY_DOUJINSHI = 0x2;
public static final int CATEGORY_MANGA = 0x4;
public static final int CATEGORY_ARTIST_CG = 0x8;
public static final int CATEGORY_GAME_CG = 0x10;
public static final int CATEGORY_IMAGE_SET = 0x20;
public static final int CATEGORY_COSPLAY = 0x40;
public static final int CATEGORY_ASIAN_PORN = 0x80;
public static final int CATEGORY_NON_H = 0x100;
public static final int CATEGORY_WESTERN = 0x200;
/**
* No category specify. Represents homepage.
*/
public static final int CATEGORY_NONE = 0;
/**
* Unknown category.
* <p>
* Used when can't parse the category string.
*/
public static final int CATEGORY_UNKNOWN = -1;
private static final int[] CATEGORY_VALUES = {
CATEGORY_MISC,
CATEGORY_DOUJINSHI,
CATEGORY_MANGA,
CATEGORY_ARTIST_CG,
CATEGORY_GAME_CG,
CATEGORY_IMAGE_SET,
CATEGORY_COSPLAY,
CATEGORY_ASIAN_PORN,
CATEGORY_NON_H,
CATEGORY_WESTERN,
};
private static final String[][] CATEGORY_STRINGS = {
new String[] { "misc" },
new String[] { "doujinshi" },
new String[] { "manga" },
new String[] { "artist cg", "artistcg", "artist cg sets" },
new String[] { "game cg", "gamecg", "game cg sets" },
new String[] { "image set", "imageset", "image sets" },
new String[] { "cosplay" },
new String[] { "asian porn", "asianporn", "asian porn" },
new String[] { "non-h" },
new String[] { "western" },
};
public static final int COLOR_DOUJINSHI = 0xfff44336; // red_500
public static final int COLOR_MANGA = 0xffff9800; // orange_500
public static final int COLOR_ARTIST_CG = 0xffffc107; // amber_500
public static final int COLOR_GAME_CG = 0xff4caf50; // green_500
public static final int COLOR_WESTERN = 0xff8bc34a; // light_green_500
public static final int COLOR_NON_H = 0xff2196f3; // blue_500
public static final int COLOR_IMAGE_SET = 0xff3f51b5; // indigo_500
public static final int COLOR_COSPLAY = 0xff9c27b0; // purple_500
public static final int COLOR_ASIAN_PORN = 0xff9575cd; // deep_purple_300
public static final int COLOR_MISC = 0xfff06292; // pink_300
public static final int COLOR_UNKNOWN = Color.BLACK;
/**
* Converts category string to category value.
* Returns {@link #CATEGORY_UNKNOWN} if can't recognize the category.
*/
public static int getCategory(String type) {
if (StringUtils.isEmpty(type)) {
return CATEGORY_UNKNOWN;
}
type = type.toLowerCase(Locale.ENGLISH);
for (int i = 0, n = CATEGORY_STRINGS.length; i < n; ++i) {
for (String str : CATEGORY_STRINGS[i]) {
if (type.equals(str)) {
return CATEGORY_VALUES[i];
}
}
}
return CATEGORY_UNKNOWN;
}
/**
* Converts category value to category string.
* Returns {@code null} if can't recognize the category.
*/
@Nullable
public static String getCategory(int type) {
for (int i = 0, n = CATEGORY_VALUES.length; i < n; ++i) {
if (CATEGORY_VALUES[i] == type) {
return CATEGORY_STRINGS[i][0];
}
}
return null;
}
/**
* Converts category value to category string.
* Returns {@code "unknown"} if can't recognize the category.
*/
@NonNull
public static String getCategoryNotNull(int type) {
String category = getCategory(type);
if (category != null) {
return category;
} else {
return "unknown";
}
}
/**
* Get the color to represent the category.
* Returns black if can't recognize the category.
*/
public static int getCategoryColor(int category) {
switch (category) {
case CATEGORY_DOUJINSHI:
return COLOR_DOUJINSHI;
case CATEGORY_MANGA:
return COLOR_MANGA;
case CATEGORY_ARTIST_CG:
return COLOR_ARTIST_CG;
case CATEGORY_GAME_CG:
return COLOR_GAME_CG;
case CATEGORY_WESTERN:
return COLOR_WESTERN;
case CATEGORY_NON_H:
return COLOR_NON_H;
case CATEGORY_IMAGE_SET:
return COLOR_IMAGE_SET;
case CATEGORY_COSPLAY:
return COLOR_COSPLAY;
case CATEGORY_ASIAN_PORN:
return COLOR_ASIAN_PORN;
case CATEGORY_MISC:
return COLOR_MISC;
default:
return COLOR_UNKNOWN;
}
}
/**
* Gets the theme to represent the category.
* Returns {@code 0} if can't recognize the category.
*/
public static int getCategoryTheme(int category, boolean dark) {
switch (category) {
case CATEGORY_DOUJINSHI:
return dark ? R.style.AppTheme_Dark_Ehv_Doujinshi : R.style.AppTheme_Ehv_Doujinshi;
case CATEGORY_MANGA:
return dark ? R.style.AppTheme_Dark_Ehv_Manga : R.style.AppTheme_Ehv_Manga;
case CATEGORY_ARTIST_CG:
return dark ? R.style.AppTheme_Dark_Ehv_ArtistCG : R.style.AppTheme_Ehv_ArtistCG;
case CATEGORY_GAME_CG:
return dark ? R.style.AppTheme_Dark_Ehv_GameCG : R.style.AppTheme_Ehv_GameCG;
case CATEGORY_WESTERN:
return dark ? R.style.AppTheme_Dark_Ehv_Western : R.style.AppTheme_Ehv_Western;
case CATEGORY_NON_H:
return dark ? R.style.AppTheme_Dark_Ehv_NonH : R.style.AppTheme_Ehv_NonH;
case CATEGORY_IMAGE_SET:
return dark ? R.style.AppTheme_Dark_Ehv_ImageSet : R.style.AppTheme_Ehv_ImageSet;
case CATEGORY_COSPLAY:
return dark ? R.style.AppTheme_Dark_Ehv_Cosplay : R.style.AppTheme_Ehv_Cosplay;
case CATEGORY_ASIAN_PORN:
return dark ? R.style.AppTheme_Dark_Ehv_AsianPorn : R.style.AppTheme_Ehv_AsianPorn;
case CATEGORY_MISC:
return dark ? R.style.AppTheme_Dark_Ehv_Misc : R.style.AppTheme_Ehv_Misc;
default:
return 0;
}
}
///////////////////////////////////////////////////////////////////////////
// Language
///////////////////////////////////////////////////////////////////////////
/**
* Unknown
*/
public static final int LANG_UNKNOWN = -1;
/**
* Japanese
*/
public static final int LANG_JA = 0;
/**
* English
*/
public static final int LANG_EN = 1;
/**
* Chinese
*/
public static final int LANG_ZH = 2;
/**
* Dutch
*/
public static final int LANG_NL = 3;
/**
* French
*/
public static final int LANG_FR = 4;
/**
* German
*/
public static final int LANG_DE = 5;
/**
* Hungarian
*/
public static final int LANG_HU = 6;
/**
* Italian
*/
public static final int LANG_IT = 7;
/**
* Korean
*/
public static final int LANG_KO = 8;
/**
* Polish
*/
public static final int LANG_PL = 9;
/**
* Portuguese
*/
public static final int LANG_PT = 10;
/**
* Russian
*/
public static final int LANG_RU = 11;
/**
* Spanish
*/
public static final int LANG_ES = 12;
/**
* Thai
*/
public static final int LANG_TH = 13;
/**
* Vietnamese
*/
public static final int LANG_VI = 14;
/**
* N/A
*/
public static final int LANG_N_A = 15;
/**
* Other
*/
public static final int LANG_OTHER = 16;
private static final Pattern LANG_PATTERN_EN =
Pattern.compile("[(\\[]eng(?:lish)?[)\\]]|英訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_ZH =
Pattern.compile("[((\\[]ch(?:inese)?[))\\]]|[汉漢]化|中[国國][语語]|中文|中国翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_NL =
Pattern.compile("[(\\[]dutch[)\\]]|オランダ語訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_FR =
Pattern.compile("[(\\[]fr(?:ench)?[)\\]]|フランス翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_DE =
Pattern.compile("[(\\[]german[)\\]]|ドイツ翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_HU =
Pattern.compile("[(\\[]hun(?:garian)?[)\\]]|ハンガリー翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_IT =
Pattern.compile("[(\\[]italiano?[)\\]]|イタリア翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_KO =
Pattern.compile("[(\\[]korean?[)\\]]|韓国翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_PL =
Pattern.compile("[(\\[]polish[)\\]]|ポーランド翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_PT =
Pattern.compile("[(\\[]portuguese|ポルトガル翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_RU =
Pattern.compile("[(\\[]rus(?:sian)?[)\\]]|ロシア翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_ES =
Pattern.compile("[(\\[]spanish[)\\]]|[(\\[]Español[)\\]]|スペイン翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_TH =
Pattern.compile("[(\\[]thai(?: ภาษาไทย)?[)\\]]|แปลไทย|タイ翻訳", Pattern.CASE_INSENSITIVE);
private static final Pattern LANG_PATTERN_VI =
Pattern.compile("[(\\[]vietnamese(?: Tiếng Việt)?[)\\]]|ベトナム翻訳", Pattern.CASE_INSENSITIVE);
private static final int[] GUESS_LANGS = {
LANG_EN,
LANG_ZH,
LANG_ES,
LANG_KO,
LANG_RU,
LANG_FR,
LANG_PT,
LANG_TH,
LANG_DE,
LANG_IT,
LANG_VI,
LANG_PL,
LANG_HU,
LANG_NL,
};
private static final Pattern[] GUESS_LANG_PATTERNS = {
LANG_PATTERN_EN,
LANG_PATTERN_ZH,
LANG_PATTERN_ES,
LANG_PATTERN_KO,
LANG_PATTERN_RU,
LANG_PATTERN_FR,
LANG_PATTERN_PT,
LANG_PATTERN_TH,
LANG_PATTERN_DE,
LANG_PATTERN_IT,
LANG_PATTERN_VI,
LANG_PATTERN_PL,
LANG_PATTERN_HU,
LANG_PATTERN_NL,
};
private static final int[] LANG_ABBR_IDS = {
R.string.language_abbr_japanese,
R.string.language_abbr_english,
R.string.language_abbr_chinese,
R.string.language_abbr_dutch,
R.string.language_abbr_french,
R.string.language_abbr_german,
R.string.language_abbr_hungarian,
R.string.language_abbr_italian,
R.string.language_abbr_korean,
R.string.language_abbr_polish,
R.string.language_abbr_portuguese,
R.string.language_abbr_russian,
R.string.language_abbr_spanish,
R.string.language_abbr_thai,
R.string.language_abbr_vietnamese,
};
private static final int[] LANG_IDS = {
R.string.language_japanese,
R.string.language_english,
R.string.language_chinese,
R.string.language_dutch,
R.string.language_french,
R.string.language_german,
R.string.language_hungarian,
R.string.language_italian,
R.string.language_korean,
R.string.language_polish,
R.string.language_portuguese,
R.string.language_russian,
R.string.language_spanish,
R.string.language_thai,
R.string.language_vietnamese,
R.string.language_n_a,
R.string.language_other,
};
private static final String[] LANG_TEXTS = {
"japanese",
"english",
"chinese",
"dutch",
"french",
"german",
"hungarian",
"italian",
"korean",
"polish",
"portuguese",
"russian",
"spanish",
"thai",
"vietnamese",
};
/**
* Guesses the language of the gallery according to the title.
* Returns {@link #LANG_UNKNOWN} if can't guess.
*/
public static int guessLang(String title) {
if (StringUtils.isEmpty(title)) {
return LANG_UNKNOWN;
}
for (int i = 0, n = GUESS_LANGS.length; i < n; ++i) {
if (GUESS_LANG_PATTERNS[i].matcher(title).find()) {
return GUESS_LANGS[i];
}
}
return LANG_UNKNOWN;
}
/**
* Returns abbreviation for the language.
* Returns {@code null} if no abbreviation for the language.
*/
@Nullable
public static String getLangAbbr(Context context, int lang) {
if (lang >= 0 && lang < LANG_ABBR_IDS.length) {
return context.getString(LANG_ABBR_IDS[lang]);
} else {
return null;
}
}
/**
* Returns the language.
* Returns {@link #LANG_UNKNOWN} if can't recognize the language.
*/
public static int getLang(String language) {
if (language != null) {
language = language.toLowerCase();
for (int i = 0, n = LANG_TEXTS.length; i < n; ++i) {
if (language.equals(LANG_TEXTS[i])) {
return i;
}
}
}
return LANG_UNKNOWN;
}
/**
* Returns string for the language.
* Returns {@code null} if no string for the language.
*/
@Nullable
public static String getLang(Context context, int lang) {
if (lang >= 0 && lang < LANG_IDS.length) {
return context.getString(LANG_IDS[lang]);
} else {
return null;
}
}
/**
* Returns string for the language.
* Returns a string to represent unknown if can't recognize the category.
*/
@Nullable
public static String getLangNotNull(Context context, int lang) {
String language = getLang(context, lang);
if (language != null) {
return language;
} else {
return context.getString(R.string.language_unknown);
}
}
/**
* Returns text for the language. The text can be used for tag.
* Returns {@code null} if no string for the language.
*/
@Nullable
public static String getLangText(int lang) {
if (lang >= 0 && lang < LANG_TEXTS.length) {
return LANG_TEXTS[lang];
} else {
return null;
}
}
///////////////////////////////////////////////////////////////////////////
// Favourite
///////////////////////////////////////////////////////////////////////////
public static final int FAV_CAT_ALL = -1;
public static final int FAV_CAT_LOCAL = -2;
public static final int FAV_CAT_UNKNOWN = -3;
public static final int FAV_CAT_MAX = 9;
}
@@ -0,0 +1,92 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/29/2017.
*/
import com.hippo.yorozuya.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Favourite list url builder.
*/
public class FLUrlBuilder {
private int page;
private int favCat = EhUtils.FAV_CAT_ALL;
private String keyword;
/**
* Set page of the favourite list.
* <p>
* 0-base.
*/
public void setPage(int page) {
this.page = page;
}
/**
* Set category of the favourite list.
*/
public void setFavCat(int favCat) {
if (favCat > EhUtils.FAV_CAT_MAX) {
favCat = EhUtils.FAV_CAT_MAX;
} else if (favCat < EhUtils.FAV_CAT_ALL) {
favCat = EhUtils.FAV_CAT_ALL;
}
this.favCat = favCat;
}
/**
* Set keyword of the favourite list.
* <p>
* {@code null} for no keyword.
*/
public void setKeyword(String keyword) {
this.keyword = keyword;
}
/**
* Build query map
*/
public Map<String, String> build() {
Map<String, String> map = new HashMap<>();
// Page
if (page != 0) {
map.put("page", Integer.toString(page));
}
// FavCat
if (favCat == EhUtils.FAV_CAT_ALL) {
map.put("favcat", "all");
} else {
map.put("favcat", Integer.toString(favCat));
}
// keyword
if (!StringUtils.isEmpty(keyword)) {
map.put("f_search", keyword);
map.put("f_apply", "Search Favorites");
}
return map;
}
}
@@ -0,0 +1,227 @@
/*
* 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.ehviewer.client;
/*
* Created by Hippo on 1/29/2017.
*/
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.hippo.ehviewer.client.data.TagSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Gallery list url builder.
*/
public class GLUrlBuilder {
private int page;
private int category = EhUtils.CATEGORY_NONE;
private int language = EhUtils.LANG_UNKNOWN;
private String keyword;
private final TagSet tagSet = new TagSet();
/**
* Set this GLUrlBuilder the same as that GLUrlBuilder.
*/
public void set(GLUrlBuilder builder) {
if (this != builder) {
this.page = builder.page;
this.category = builder.category;
this.language = builder.language;
this.keyword = builder.keyword;
this.tagSet.set(builder.tagSet);
}
}
/**
* Set page of the gallery list.
* <p>
* 0-base.
*/
public void setPage(int page) {
this.page = page;
}
/**
* Set category of the gallery list.
*
* @see #getCategory()
*/
public void setCategory(int category) {
this.category = category;
}
/**
* Returns the category.
*
* @see #setCategory(int)
*/
public int getCategory() {
return category;
}
/**
* Set keyword of the gallery list.
* <p>
* {@code null} for no keyword.
*
* @see #getKeyword()
*/
public void setKeyword(String keyword) {
this.keyword = keyword;
}
/**
* Returns the keyword.
*
* @see #setKeyword(String)
*/
public String getKeyword() {
return this.keyword;
}
/**
* Sets language for the gallery list.
*
* @see #getLanguage()
*/
public void setLanguage(int language) {
this.language = language;
}
/**
* Returns the language.
*
* @see #setLanguage(int)
*/
public int getLanguage() {
return language;
}
/**
* Add a tag.
*
* @param tag no quotation marks, no dollar sign
*/
public void addTag(@NonNull String namespace, @NonNull String tag) {
tagSet.add(namespace, tag);
}
/**
* Returns {@code true} if it contains a least one tag.
*/
public int getTagCount() {
return tagSet.size();
}
/**
* Returns the first tag.
* Returns {@code null} if no tags.
*/
@Nullable
public String getFirstTag() {
Iterator<Map.Entry<String, Set<String>>> iterator = tagSet.iterator();
if (iterator.hasNext()) {
Map.Entry<String, Set<String>> entry = iterator.next();
return entry.getValue() + ":" + entry.getValue().iterator().next();
} else {
return null;
}
}
private void appendTag(StringBuilder sb, String namespace, String tag) {
if (sb.length() != 0) {
sb.append(' ');
}
sb.append(namespace).append(":\"").append(tag).append("$\"");
}
// Combine keyword, language and tags
@Nullable
private String resolveKeyword() {
StringBuilder sb = new StringBuilder();
if (!TextUtils.isEmpty(keyword)) {
sb.append(keyword);
}
String language = EhUtils.getLangText(this.language);
if (language != null) {
appendTag(sb, "language", language);
}
for (Map.Entry<String, Set<String>> entry : tagSet) {
String namespace = entry.getKey();
for (String tag : entry.getValue()) {
appendTag(sb, namespace, tag);
}
}
return sb.length() != 0 ? sb.toString() : null;
}
/**
* Build query map
*/
public Map<String, String> build() {
Map<String, String> map = new HashMap<>();
// True if need ("f_apply", "Apply+Filter")
boolean filter = false;
// Category
if (category != EhUtils.CATEGORY_NONE) {
if ((category & EhUtils.CATEGORY_DOUJINSHI) != 0) map.put("f_doujinshi", "on");
if ((category & EhUtils.CATEGORY_MANGA) != 0) map.put("f_manga", "on");
if ((category & EhUtils.CATEGORY_ARTIST_CG) != 0) map.put("f_artistcg", "on");
if ((category & EhUtils.CATEGORY_GAME_CG) != 0) map.put("f_gamecg", "on");
if ((category & EhUtils.CATEGORY_WESTERN) != 0) map.put("f_western", "on");
if ((category & EhUtils.CATEGORY_NON_H) != 0) map.put("f_non-h", "on");
if ((category & EhUtils.CATEGORY_IMAGE_SET) != 0) map.put("f_imageset", "on");
if ((category & EhUtils.CATEGORY_COSPLAY) != 0) map.put("f_cosplay", "on");
if ((category & EhUtils.CATEGORY_ASIAN_PORN) != 0) map.put("f_asianporn", "on");
if ((category & EhUtils.CATEGORY_MISC) != 0) map.put("f_misc", "on");
filter = true;
}
// Keyword
String keyword = resolveKeyword();
if (keyword != null) {
map.put("f_search", keyword);
filter = true;
}
// Page
if (page != 0) {
map.put("page", Integer.toString(page));
}
// TODO Advance
// Add filter foot
if (filter) {
map.put("f_apply", "Apply Filter");
}
return map;
}
}
@@ -0,0 +1,73 @@
/*
* 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.ehviewer.client.converter;
/*
* Created by Hippo on 3/4/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhConverter;
import com.hippo.ehviewer.client.data.FavouritesItem;
import com.hippo.ehviewer.client.data.FavouritesState;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.FavouritesParser;
import com.hippo.ehviewer.client.result.FavouritesResult;
import java.util.Collections;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
/**
* A {@link retrofit2.Converter} to parse the html of favourites.
*/
public class FavouritesConverter extends EhConverter<FavouritesResult> {
public static final FavouritesConverter INSTANCE = new FavouritesConverter();
private FavouritesConverter() {}
@NonNull
@Override
public FavouritesResult convert(String body) throws ParseException {
Document document = Jsoup.parse(body);
FavouritesState state = FavouritesParser.parseFavouritesState(body, document);
int pages = FavouritesParser.parsePages(body, document);
List<FavouritesItem> favouritesItemList;
if (pages > 0) {
favouritesItemList = FavouritesParser.parseFavourites(body, document);
} else {
favouritesItemList = Collections.emptyList();
}
return new FavouritesResult(pages, favouritesItemList, state);
}
////////////////
// Pain part
////////////////
@NonNull
@Override
public FavouritesResult error(Throwable t) {
return FavouritesResult.error(t);
}
}
@@ -0,0 +1,55 @@
/*
* 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.ehviewer.client.converter;
/*
* Created by Hippo on 2/12/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhConverter;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.ForumsParser;
import com.hippo.ehviewer.client.result.ForumsResult;
/**
* A {@link retrofit2.Converter} to parse the html of forums
* to get user profile url.
*/
public class ForumsConverter extends EhConverter<ForumsResult> {
public static final ForumsConverter INSTANCE = new ForumsConverter();
private ForumsConverter() {}
@NonNull
@Override
public ForumsResult convert(String body) throws ParseException {
return new ForumsResult(ForumsParser.parseForums(body));
}
////////////////
// Pain part
////////////////
@NonNull
@Override
public ForumsResult error(Throwable t) {
return ForumsResult.error(t);
}
}
@@ -0,0 +1,87 @@
/*
* 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.ehviewer.client.converter;
/*
* Created by Hippo on 5/15/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhConverter;
import com.hippo.ehviewer.client.data.ApiUidKey;
import com.hippo.ehviewer.client.data.CommentEntry;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.PreviewPage;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.ApiUidKeyParser;
import com.hippo.ehviewer.client.parser.GalleryDetailParser;
import com.hippo.ehviewer.client.result.GalleryDetailResult;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
/**
* A {@link retrofit2.Converter} to parse gallery detail page.
*/
public class GalleryDetailConverter extends EhConverter<GalleryDetailResult> {
public static final GalleryDetailConverter INSTANCE = new GalleryDetailConverter();
private GalleryDetailConverter() {}
@NonNull
@Override
public GalleryDetailResult convert(String body) throws ParseException {
Document document = Jsoup.parse(body);
GalleryInfo info = GalleryDetailParser.parseGalleryDetail(body, document);
List<CommentEntry> comments;
try {
comments = GalleryDetailParser.parseComments(body, document);
} catch (ParseException e) {
comments = null;
}
List<PreviewPage> previews;
try {
previews = GalleryDetailParser.parsePreviews(body, document);
} catch (ParseException e) {
previews = null;
}
ApiUidKey apiUidKey;
try {
apiUidKey = ApiUidKeyParser.parseApiUidKey(body);
} catch (ParseException e) {
apiUidKey = null;
}
return new GalleryDetailResult(info, comments, previews, apiUidKey);
}
////////////////
// Pain part
////////////////
@NonNull
@Override
public GalleryDetailResult error(Throwable t) {
return GalleryDetailResult.error(t);
}
}
@@ -0,0 +1,70 @@
/*
* 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.ehviewer.client.converter;
/*
* Created by Hippo on 1/29/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhConverter;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.GalleryListParser;
import com.hippo.ehviewer.client.result.GalleryListResult;
import java.util.Collections;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
/**
* A {@link retrofit2.Converter} to parse the html of gallery list.
*/
public class GalleryListConverter extends EhConverter<GalleryListResult> {
public static final GalleryListConverter INSTANCE = new GalleryListConverter();
private GalleryListConverter() {}
@NonNull
@Override
public GalleryListResult convert(String body) throws ParseException {
Document document = Jsoup.parse(body);
int pages = GalleryListParser.parsePages(body, document);
List<GalleryInfo> galleryInfoList;
if (pages > 0) {
galleryInfoList = GalleryListParser.parseGalleryList(body, document);
} else {
galleryInfoList = Collections.emptyList();
}
return new GalleryListResult(pages, galleryInfoList);
}
////////////////
// Pain part
////////////////
@NonNull
@Override
public GalleryListResult error(Throwable t) {
return GalleryListResult.error(t);
}
}
@@ -0,0 +1,50 @@
/*
* 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.ehviewer.client.converter;
/*
* Created by Hippo on 2/24/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhConverter;
import com.hippo.ehviewer.client.parser.GalleryMetadataParser;
import com.hippo.ehviewer.client.result.GalleryMetadataResult;
public class GalleryMetadataConverter extends EhConverter<GalleryMetadataResult> {
public static final GalleryMetadataConverter INSTANCE = new GalleryMetadataConverter();
private GalleryMetadataConverter() {}
@NonNull
@Override
public GalleryMetadataResult convert(String body) throws Exception {
return new GalleryMetadataResult(GalleryMetadataParser.parseGalleryMetadata(body));
}
////////////////
// Pain part
////////////////
@NonNull
@Override
public GalleryMetadataResult error(Throwable t) {
return GalleryMetadataResult.error(t);
}
}
@@ -0,0 +1,57 @@
/*
* 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.ehviewer.client.converter;
/*
* Created by Hippo on 2/12/2017.
*/
import android.support.annotation.NonNull;
import android.util.Pair;
import com.hippo.ehviewer.client.EhConverter;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.ProfileParser;
import com.hippo.ehviewer.client.result.ProfileResult;
/**
* A {@link retrofit2.Converter} to parse the html of profile
* to get name and avatar.
*/
public class ProfileConverter extends EhConverter<ProfileResult> {
public static final ProfileConverter INSTANCE = new ProfileConverter();
private ProfileConverter() {}
@NonNull
@Override
public ProfileResult convert(String body) throws ParseException {
Pair<String, String> pair = ProfileParser.parseProfile(body);
return new ProfileResult(pair.first, pair.second);
}
////////////////
// Pain part
////////////////
@NonNull
@Override
public ProfileResult error(Throwable t) {
return ProfileResult.error(t);
}
}
@@ -0,0 +1,55 @@
/*
* 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.ehviewer.client.converter;
/*
* Created by Hippo on 1/18/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhConverter;
import com.hippo.ehviewer.client.exception.GeneralException;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.SignInParser;
import com.hippo.ehviewer.client.result.SignInResult;
/**
* A {@link retrofit2.Converter} to parse the html of signing in.
*/
public class SignInConverter extends EhConverter<SignInResult> {
public static final SignInConverter INSTANCE = new SignInConverter();
private SignInConverter() {}
@NonNull
@Override
public SignInResult convert(String body) throws ParseException, GeneralException {
return new SignInResult(SignInParser.parseSignIn(body));
}
////////////////
// Pain part
////////////////
@NonNull
@Override
public SignInResult error(Throwable t) {
return SignInResult.error(t);
}
}
@@ -0,0 +1,52 @@
/*
* 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.ehviewer.client.converter;
/*
* Created by Hippo on 1/24/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhConverter;
import com.hippo.ehviewer.client.result.VoidResult;
/**
* A {@link retrofit2.Converter} to return {@link VoidResult}.
*/
public class VoidConverter extends EhConverter<VoidResult> {
public static final VoidConverter INSTANCE = new VoidConverter();
private VoidConverter() {}
@NonNull
@Override
public VoidResult convert(String body) throws Exception {
return VoidResult.getInstance();
}
////////////////
// Pain part
////////////////
@NonNull
@Override
public VoidResult error(Throwable t) {
return VoidResult.error(t);
}
}
@@ -0,0 +1,54 @@
/*
* 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.ehviewer.client.converter;
/*
* Created by Hippo on 2/24/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhConverter;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.WhatsHotParser;
import com.hippo.ehviewer.client.result.WhatsHotResult;
/**
* A {@link retrofit2.Converter} to parse whats hot.
*/
public class WhatsHotConverter extends EhConverter<WhatsHotResult> {
public static final WhatsHotConverter INSTANCE = new WhatsHotConverter();
private WhatsHotConverter() {}
@NonNull
@Override
public WhatsHotResult convert(String body) throws ParseException {
return new WhatsHotResult(WhatsHotParser.parseWhatsHot(body));
}
////////////////
// Pain part
////////////////
@NonNull
@Override
public WhatsHotResult error(Throwable t) {
return WhatsHotResult.error(t);
}
}
@@ -0,0 +1,36 @@
/*
* 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.ehviewer.client.data;
/*
* Created by Hippo on 5/16/2017.
*/
/**
* Api uid and api key can be get from gallery detail page.
* They are used to vote comment.
*/
public final class ApiUidKey {
public final long uid;
public final String key;
public ApiUidKey(long uid, String key) {
this.uid = uid;
this.key = key;
}
}
@@ -0,0 +1,127 @@
/*
* 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.ehviewer.client.data;
/*
* Created by Hippo on 5/15/2017.
*/
import android.os.Parcel;
import android.os.Parcelable;
import com.hippo.yorozuya.HashCodeUtils;
import com.hippo.yorozuya.ObjectUtils;
public final class CommentEntry implements Parcelable {
// 0 for uploader comment. can't vote
public long id;
public long date;
public String user;
public String comment;
public int score;
public boolean votedUp;
public boolean votedDown;
public String voteState;
@Override
public int describeContents() {
return 0;
}
@Override
public String toString() {
return "CommentEntry: {\n"
+ "id: " + id + ",\n"
+ "date: " + date + ",\n"
+ "user: " + user + ",\n"
+ "comment: " + comment + ",\n"
+ "score: " + score + ",\n"
+ "votedUp: " + votedUp + ",\n"
+ "votedDown: " + votedDown + ",\n"
+ "voteState: " + voteState + "\n"
+ "}";
}
@Override
public boolean equals(Object obj) {
if (obj instanceof CommentEntry) {
CommentEntry entry = (CommentEntry) obj;
return entry.id == id &&
entry.date == date &&
ObjectUtils.equals(entry.user, user) &&
ObjectUtils.equals(entry.comment, comment) &&
entry.score == score &&
entry.votedUp == votedUp &&
entry.votedDown == votedDown &&
ObjectUtils.equals(entry.voteState, voteState);
} else {
return false;
}
}
@Override
public int hashCode() {
return HashCodeUtils.hashCode(
id,
date,
user,
comment,
score,
votedUp,
votedDown,
voteState
);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeLong(this.date);
dest.writeString(this.user);
dest.writeString(this.comment);
dest.writeInt(this.score);
dest.writeByte(this.votedUp ? (byte) 1 : (byte) 0);
dest.writeByte(this.votedDown ? (byte) 1 : (byte) 0);
dest.writeString(this.voteState);
}
public CommentEntry() {}
protected CommentEntry(Parcel in) {
this.id = in.readLong();
this.date = in.readLong();
this.user = in.readString();
this.comment = in.readString();
this.score = in.readInt();
this.votedUp = in.readByte() != 0;
this.votedDown = in.readByte() != 0;
this.voteState = in.readString();
}
public static final Parcelable.Creator<CommentEntry> CREATOR =
new Parcelable.Creator<CommentEntry>() {
@Override
public CommentEntry createFromParcel(Parcel source) {
return new CommentEntry(source);
}
@Override
public CommentEntry[] newArray(int size) {
return new CommentEntry[size];
}
};
}
@@ -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.ehviewer.client.data;
/*
* Created by Hippo on 3/4/2017.
*/
/**
* The item of favourites.
*/
public class FavouritesItem implements GalleryInfoContainer {
/**
* The {@link GalleryInfo} of this {@code FavouritesItem}.
* <p>
* If it's {@code null}, this {@code FavouritesItem} is invalid.
*/
public GalleryInfo info;
/**
* The note that user input.
*/
public String note;
/**
* Favourited date.
* <p>
* 0 if can't get it.
*/
public long date;
@Override
public GalleryInfo getGalleryInfo() {
return info;
}
@Override
public void setGalleryInfo(GalleryInfo info) {
this.info = info;
}
}
@@ -0,0 +1,49 @@
/*
* 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.ehviewer.client.data;
/*
* Created by Hippo on 5/17/2017.
*/
import android.support.annotation.NonNull;
import android.util.Pair;
import java.util.List;
/**
* {@code FavouritesState} stores favourites name and count.
*/
public final class FavouritesState {
private final List<Pair<String, Integer>> state;
public FavouritesState(@NonNull List<Pair<String, Integer>> state) {
this.state = state;
}
public int getFavouritesSlotCount() {
return state.size();
}
public String getFavouritesName(int index) {
return state.get(index).first;
}
public int getFavouritesCount(int index) {
return state.get(index).second;
}
}
@@ -0,0 +1,506 @@
/*
* 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.ehviewer.client.data;
/*
* Created by Hippo on 1/29/2017.
*/
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.util.JsonStore;
import com.hippo.yorozuya.HashCodeUtils;
import com.hippo.yorozuya.ObjectUtils;
import java.util.List;
/**
* Gallery Information.
* <p>
* There three ways to obtain a {@code GalleryInfo}.
* <ul>
* <li>Parsing gallery list html</li>
* <li>Parsing gallery detail html</li>
* <li>Gallery Metadata API</li>
* </ul>
* None of these methods can fill all fields.
*/
@JsonStore.Info(
version = 1,
name = "com.hippo.ehviewer:GalleryInfo"
)
public class GalleryInfo implements JsonStore.Item, Parcelable {
private static final String LOG_TAG = GalleryInfo.class.getSimpleName();
/**
* An invalid {@code GalleryInfo}.
*/
public static final GalleryInfo INVALID = new GalleryInfo();
/**
* Gallery ID.
* <p>
* {@code 0} for invalid.
* <p>
* {@code int} should be enough for a long long time.
* But I like {@code long}.
*/
public long gid;
/**
* Gallery token. Most gallery operations need it.
* <p>
* {@code null} for invalid
* <p>
* Regex:<pre>{@code
* [0-9a-f]{10}
* }</pre>
* Example:<pre>{@code
* c219d2cf41
* }</pre>
*/
public String token;
/**
* Gallery title.
* <p>
* May be {@code null} if user enable show jp title.
* <p>
* One of {@code title} and {@code titleJpn} must be non-null.
*/
public String title;
/**
* Gallery title.
* <p>
* {@code null} if can't get it.
* <p>
* One of {@code title} and {@code titleJpn} must be non-null.
*/
public String titleJpn;
/**
* The fingerprint of the first image.
* <p>
* Format:
* {@code [sha1]-[size]-[width]-[height]-[format]}
* <p>
* Regex:
* {@code [0-9a-f]{40}-\d+-\d+-\d+-[0-9a-z]+}
* <p>
* Example:
* {@code 7dd3e4a62807a6938910a14407d9867b18a58a9f-2333088-2831-4015-jpg}
* <p>
* {@code null} if can't get it.
*/
public String cover;
/**
* The url of the cover.
* <p>
* {@code null} if can't get it.
*/
public String coverUrl;
/**
* Cover width / Cover height.
* <p>
* {@code 0.0f} if can't it.
*/
public float coverRatio = 0.0f;
/**
* Gallery category.
* <p>
* {@link com.hippo.ehviewer.client.EhUtils#CATEGORY_UNKNOWN} if can't get it.
*/
public int category = EhUtils.CATEGORY_UNKNOWN;
/**
* Posted time stamp.
* <p>
* {@code 0} if can't get it.
*/
public long date;
/**
* Who uploads the gallery.
* <p>
* {@code null} if can't get it.
*/
public String uploader;
/**
* Gallery Rating.
* <p>
* Range: {@code [0.5, 5]}
* <p>
* {@code 0.0f} if can't it, or if no rating temporarily.
*/
public float rating = 0.0f;
/**
* How many users rated the gallery.
* <p>
* {@code 0} if can't get it.
*/
public int rated;
/**
* Gallery Language.
* <p>
* {@link EhUtils#LANG_UNKNOWN} if can't get it.
*/
public int language = EhUtils.LANG_UNKNOWN;
/**
* How many users favourited the gallery.
* <p>
* {@code 0} if can't get it.
*/
public int favourited;
/**
* Favourite slot.
* <p>
* Range: {@code [-3, 9]}
* <p>
* {@code -3} for un-favourited.
*/
public int favouriteSlot = EhUtils.FAV_CAT_UNKNOWN;
/**
* Expunged, deleted or replaced.
*/
public boolean invalid = false;
/**
* The key to download archive.
*/
public String archiverKey;
/**
* Gallery Pages.
* <p>
* {@code 0} for unknown.
*/
public int pages = 0;
/**
* Gallery size in bytes.
* <p>
* {@code 0} for unknown.
*/
public long size = 0;
/**
* Torrent count.
* <p>
* {@code 0} for default.
*/
public int torrentCount = 0;
/**
* Gallery tags.
*/
public final TagSet tagSet;
/**
* The gid of the parent gallery.
* <p>
* {@code 0} if no parent.
* <p>
* The parent is a gallery which is replaced by this gallery.
*/
public long parentGid;
/**
* The token of the parent gallery.
* <p>
* {@code null} if no parent.
* <p>
* The parent is a gallery which is replaced by this gallery.
*/
public String parentToken;
/**
* The gid of the child gallery.
* <p>
* {@code 0} if no child.
* <p>
* The child is a gallery which replaces this gallery.
*/
public long childGid;
/**
* The token of the child gallery.
* <p>
* {@code null} if no child.
* <p>
* The child is a gallery which replaces this gallery.
*/
public String childToken;
/**
* Merges data in {@code info} to this {@code GalleryInfo}.
* The principle is if the field in the new {@code GalleryInfo} is valid, use it, otherwise
* keep the old one.
*/
public boolean merge(GalleryInfo info) {
if (info == null) {
return false;
}
if (info.gid != gid || !ObjectUtils.equals(info.token, token)) {
Log.w(LOG_TAG, "Can't merge different GalleryInfo");
return false;
}
if (info.title != null) {
title = info.title;
}
if (info.titleJpn != null) {
titleJpn = info.titleJpn;
}
if (info.cover != null) {
cover = info.cover;
}
if (info.coverUrl != null) {
coverUrl = info.coverUrl;
}
if (info.coverRatio != 0.0f) {
coverRatio = info.coverRatio;
}
if (info.category != EhUtils.CATEGORY_UNKNOWN) {
category = info.category;
}
if (info.date != 0) {
date = info.date;
}
if (info.uploader != null) {
uploader = info.uploader;
}
if (info.rating != 0.0f) {
rating = info.rating;
}
if (info.rated != 0) {
rating = info.rated;
}
if (info.language != EhUtils.LANG_UNKNOWN) {
language = info.language;
}
if (info.favourited != 0) {
favourited = info.favourited;
}
if (info.favouriteSlot != EhUtils.FAV_CAT_UNKNOWN) {
favouriteSlot = info.favouriteSlot;
}
if (info.invalid) {
invalid = true;
}
if (info.archiverKey != null) {
archiverKey = info.archiverKey;
}
if (info.pages != 0) {
pages = info.pages;
}
if (info.size != 0) {
size = info.size;
}
if (info.torrentCount != 0) {
torrentCount = info.torrentCount;
}
if (info.tagSet.size() != 0) {
tagSet.set(info.tagSet);
}
if (info.parentGid != 0 && info.parentToken != null) {
parentGid = info.parentGid;
parentToken = info.parentToken;
}
if (info.childGid != 0 && info.childToken != null) {
childGid = info.childGid;
childToken = info.childToken;
}
return true;
}
/**
* Merges the first same {@code GalleryInfo} in {@code list}.
*/
public void merge(List<GalleryInfo> list) {
if (list == null) {
return;
}
for (GalleryInfo info: list) {
if (info != null && info.gid == gid && ObjectUtils.equals(info.token, token)) {
merge(info);
return;
}
}
}
@Override
public boolean onFetch(int version) {
return true;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof GalleryInfo) {
GalleryInfo info = (GalleryInfo) obj;
return info.gid == gid &&
ObjectUtils.equals(info.token, token) &&
ObjectUtils.equals(info.title, title) &&
ObjectUtils.equals(info.titleJpn, titleJpn) &&
ObjectUtils.equals(info.cover, cover) &&
ObjectUtils.equals(info.coverUrl, coverUrl) &&
info.coverRatio == coverRatio &&
info.category == category &&
info.date == date &&
ObjectUtils.equals(info.uploader, uploader) &&
info.rating == rating &&
info.rated == rated &&
info.language == language &&
info.favourited == favourited &&
info.favouriteSlot == favouriteSlot &&
info.invalid == invalid &&
ObjectUtils.equals(info.archiverKey, archiverKey) &&
info.pages == pages &&
info.size == size &&
info.torrentCount == torrentCount &&
info.tagSet.equals(tagSet) &&
info.parentGid == parentGid &&
ObjectUtils.equals(info.parentToken, parentToken) &&
info.childGid == childGid &&
ObjectUtils.equals(info.childToken, childToken);
} else {
return false;
}
}
@Override
public int hashCode() {
return HashCodeUtils.hashCode(
gid,
token,
title,
titleJpn,
cover,
coverUrl,
coverRatio,
category,
date,
uploader,
rating,
rated,
language,
favourited,
favouriteSlot,
invalid,
archiverKey,
pages,
size,
torrentCount,
tagSet,
parentGid,
parentToken,
childGid,
childToken
);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.gid);
dest.writeString(this.token);
dest.writeString(this.title);
dest.writeString(this.titleJpn);
dest.writeString(this.cover);
dest.writeString(this.coverUrl);
dest.writeFloat(this.coverRatio);
dest.writeInt(this.category);
dest.writeLong(this.date);
dest.writeString(this.uploader);
dest.writeFloat(this.rating);
dest.writeInt(this.rated);
dest.writeInt(this.language);
dest.writeInt(this.favourited);
dest.writeInt(this.favouriteSlot);
dest.writeByte(this.invalid ? (byte) 1 : (byte) 0);
dest.writeString(this.archiverKey);
dest.writeInt(this.pages);
dest.writeLong(this.size);
dest.writeInt(this.torrentCount);
dest.writeParcelable(this.tagSet, flags);
dest.writeLong(this.parentGid);
dest.writeString(this.parentToken);
dest.writeLong(this.childGid);
dest.writeString(this.childToken);
}
public GalleryInfo() {
tagSet = new TagSet();
}
protected GalleryInfo(Parcel in) {
this.gid = in.readLong();
this.token = in.readString();
this.title = in.readString();
this.titleJpn = in.readString();
this.cover = in.readString();
this.coverUrl = in.readString();
this.coverRatio = in.readFloat();
this.category = in.readInt();
this.date = in.readLong();
this.uploader = in.readString();
this.rating = in.readFloat();
this.rated = in.readInt();
this.language = in.readInt();
this.favourited = in.readInt();
this.favouriteSlot = in.readInt();
this.invalid = in.readByte() != 0;
this.archiverKey = in.readString();
this.pages = in.readInt();
this.size = in.readLong();
this.torrentCount = in.readInt();
this.tagSet = in.readParcelable(getClass().getClassLoader());
this.parentGid = in.readLong();
this.parentToken = in.readString();
this.childGid = in.readLong();
this.childToken = in.readString();
}
public static final Parcelable.Creator<GalleryInfo> CREATOR =
new Parcelable.Creator<GalleryInfo>() {
@Override
public GalleryInfo createFromParcel(Parcel source) {
return new GalleryInfo(source);
}
@Override
public GalleryInfo[] newArray(int size) {
return new GalleryInfo[size];
}
};
}
@@ -0,0 +1,40 @@
/*
* 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.ehviewer.client.data;
/*
* Created by Hippo on 3/5/2017.
*/
import android.support.annotation.Nullable;
/**
* {@code GalleryInfoContainer} contains a {@link GalleryInfo}.
*/
public interface GalleryInfoContainer {
/**
* Returns the {@link GalleryInfo}.
*/
@Nullable
GalleryInfo getGalleryInfo();
/**
* Sets {@link GalleryInfo}.
*/
void setGalleryInfo(GalleryInfo info);
}
@@ -0,0 +1,147 @@
/*
* 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.ehviewer.client.data;
/*
* Created by Hippo on 5/15/2017.
*/
import android.os.Parcel;
import android.os.Parcelable;
import com.hippo.yorozuya.HashCodeUtils;
import com.hippo.yorozuya.ObjectUtils;
public final class PreviewPage implements Parcelable {
public final int index;
public final String url;
public final String image;
public final boolean clip;
public final int clipLeft;
public final int clipTop;
public final int clipWidth;
public final int clipHeight;
public PreviewPage(int index, String url, String image) {
this.index = index;
this.url = url;
this.image = image;
this.clip = false;
this.clipLeft = 0;
this.clipTop = 0;
this.clipWidth = 0;
this.clipHeight = 0;
}
public PreviewPage(int index, String url, String image,
int clipLeft, int clipTop, int clipWidth, int clipHeight) {
this.index = index;
this.url = url;
this.image = image;
this.clip = true;
this.clipLeft = clipLeft;
this.clipTop = clipTop;
this.clipWidth = clipWidth;
this.clipHeight = clipHeight;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof PreviewPage) {
PreviewPage page = (PreviewPage) obj;
return page.index == index &&
ObjectUtils.equals(page.url, url) &&
ObjectUtils.equals(page.image, image) &&
page.clip == clip &&
page.clipLeft == clipLeft &&
page.clipTop == clipTop &&
page.clipWidth == clipWidth &&
page.clipHeight == clipHeight;
} else {
return false;
}
}
@Override
public int hashCode() {
return HashCodeUtils.hashCode(
index,
url,
image,
clip,
clipLeft,
clipTop,
clipWidth,
clipHeight
);
}
@Override
public String toString() {
return "PreviewPage: {\n"
+ "index: " + index + ",\n"
+ "url: " + url + ",\n"
+ "image: " + image + ",\n"
+ "clip: " + clip + ",\n"
+ "clipLeft: " + clipLeft + ",\n"
+ "clipTop: " + clipTop + ",\n"
+ "clipWidth: " + clipWidth + ",\n"
+ "clipHeight: " + clipHeight + "\n"
+ "}";
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.index);
dest.writeString(this.url);
dest.writeString(this.image);
dest.writeByte(this.clip ? (byte) 1 : (byte) 0);
dest.writeInt(this.clipLeft);
dest.writeInt(this.clipTop);
dest.writeInt(this.clipWidth);
dest.writeInt(this.clipHeight);
}
protected PreviewPage(Parcel in) {
this.index = in.readInt();
this.url = in.readString();
this.image = in.readString();
this.clip = in.readByte() != 0;
this.clipLeft = in.readInt();
this.clipTop = in.readInt();
this.clipWidth = in.readInt();
this.clipHeight = in.readInt();
}
public static final Parcelable.Creator<PreviewPage> CREATOR =
new Parcelable.Creator<PreviewPage>() {
@Override
public PreviewPage createFromParcel(Parcel source) {
return new PreviewPage(source);
}
@Override
public PreviewPage[] newArray(int size) {
return new PreviewPage[size];
}
};
}
@@ -0,0 +1,167 @@
/*
* 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.ehviewer.client.data;
/*
* Created by Hippo on 5/15/2017.
*/
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* A set which stores multiple tags.
*/
public final class TagSet implements Iterable<Map.Entry<String, Set<String>>>, Parcelable {
private Map<String, Set<String>> groups = new HashMap<>();
/**
* Put a tag to this set.
*/
public void add(@NonNull String namespace, @NonNull String tag) {
Set<String> set = groups.get(namespace);
if (set == null) {
set = new HashSet<>();
groups.put(namespace, set);
}
// Don't add duplicate tag
if (!set.contains(tag)) {
set.add(tag);
}
}
/**
* Remove a tag from this set.
*/
public void remove(@NonNull String namespace, @NonNull String tag) {
Set<String> set = groups.get(namespace);
if (set != null) {
set.remove(tag);
// Remove the namespace if it's empty
if (set.isEmpty()) {
groups.remove(namespace);
}
}
}
public void clear() {
groups.clear();
}
/**
* Make this set the same as another set.
*/
public void set(@NonNull TagSet tagSet) {
groups.clear();
for (Map.Entry<String, Set<String>> entry : tagSet) {
groups.put(entry.getKey(), new HashSet<>(entry.getValue()));
}
}
/**
* Returns the size of tags.
*/
public int size() {
int sum = 0;
for (Set<String> set : groups.values()) {
sum += set.size();
}
return sum;
}
/**
* Returns {@code true} if no tags.
*/
public boolean isEmpty() {
return groups.isEmpty();
}
@Override
public Iterator<Map.Entry<String, Set<String>>> iterator() {
return groups.entrySet().iterator();
}
@Override
public boolean equals(Object obj) {
return obj instanceof TagSet && groups.equals(((TagSet) obj).groups);
}
@Override
public int hashCode() {
return groups.hashCode();
}
@Override
public String toString() {
return "TagSet: " + groups.toString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(groups.size());
for (Map.Entry<String, Set<String>> entry : groups.entrySet()) {
dest.writeString(entry.getKey());
Set<String> set = entry.getValue();
dest.writeInt(set.size());
for (String tag: set) {
dest.writeString(tag);
}
}
}
public TagSet() {}
protected TagSet(Parcel in) {
int groupSize = in.readInt();
groups = new HashMap<>(groupSize);
for (int i = 0; i < groupSize; ++i) {
String key = in.readString();
int tagSize = in.readInt();
Set<String> set = new HashSet<>(tagSize);
for (int j = 0; j < tagSize; ++j) {
set.add(in.readString());
}
groups.put(key, set);
}
}
public static final Parcelable.Creator<TagSet> CREATOR = new Parcelable.Creator<TagSet>() {
@Override
public TagSet createFromParcel(Parcel source) {
return new TagSet(source);
}
@Override
public TagSet[] newArray(int size) {
return new TagSet[size];
}
};
}
@@ -0,0 +1,44 @@
/*
* 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.ehviewer.client.exception;
/*
* Created by Hippo on 1/19/2017.
*/
/**
* A {@link RuntimeException} wrapper of {@link Error}.
*/
public class ErrorWrapper extends RuntimeException {
private final Error origin;
public ErrorWrapper(Error origin) {
this.origin = origin;
}
public Error unwrap() {
return origin;
}
/**
* Wraps a {@link Error}.
*/
public static ErrorWrapper wrap(Error origin) {
return new ErrorWrapper(origin);
}
}
@@ -0,0 +1,35 @@
/*
* 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.ehviewer.client.exception;
/*
* Created by Hippo on 1/18/2017.
*/
/**
* A general exception of {@link com.hippo.ehviewer.client.EhClient}.
*/
public class GeneralException extends Exception {
public GeneralException(String message) {
super(message);
}
public GeneralException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -1,11 +1,11 @@
/*
* Copyright (C) 2014 Hippo Seven
* 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
* 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,
@@ -14,17 +14,22 @@
* limitations under the License.
*/
package com.hippo.ehviewer.util;
package com.hippo.ehviewer.client.exception;
import android.animation.Animator;
import android.animation.ValueAnimator;
/*
* Created by Hippo on 1/30/2017.
*/
public final class AnimatorUtils {
/**
* {@code ParseException} for inner.
*/
public class InnerParseException extends Exception {
public static Animator createDelayAnimator(long delay) {
Animator anim = ValueAnimator.ofFloat(0f, 1f);
anim.setDuration(delay);;
return anim;
}
public InnerParseException(String message) {
super(message);
}
public InnerParseException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,60 @@
/*
* 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.ehviewer.client.exception;
/*
* Created by Hippo on 1/18/2017.
*/
import com.hippo.ehviewer.client.EhConverter;
import okhttp3.HttpUrl;
/**
* Signals that html/json/others parsing failed
* in {@link com.hippo.ehviewer.client.EhClient}.
*/
public class ParseException extends Exception {
private HttpUrl url;
private String body;
public ParseException(String message, String body) {
super(message);
this.body = body;
}
public ParseException(String message, String body, Throwable cause) {
super(message, cause);
this.body = body;
}
/**
* We can't get url in {@link EhConverter}.
* So set it in {@link com.hippo.ehviewer.client.EhSubscriber}.
*/
public void url(HttpUrl url) {
this.url = url;
}
public HttpUrl url() {
return url;
}
public String body() {
return body;
}
}
@@ -0,0 +1,44 @@
/*
* 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.ehviewer.client.exception;
/*
* Created by Hippo on 1/19/2017.
*/
/**
* A {@link RuntimeException} wrapper of {@link RuntimeException}.
*/
public class RuntimeExceptionWrapper extends RuntimeException {
private final RuntimeException origin;
public RuntimeExceptionWrapper(RuntimeException origin) {
this.origin = origin;
}
public RuntimeException unwrap() {
return origin;
}
/**
* Wraps a {@link RuntimeException}.
*/
public static RuntimeExceptionWrapper wrap(RuntimeException origin) {
return new RuntimeExceptionWrapper(origin);
}
}
@@ -1,11 +1,11 @@
/*
* Copyright (C) 2014 Hippo Seven
* 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
* 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,
@@ -14,8 +14,18 @@
* limitations under the License.
*/
package com.hippo.ehviewer.exception;
package com.hippo.ehviewer.client.exception;
public class StopRequestException extends Exception {
private static final long serialVersionUID = 1L;
/*
* Created by Hippo on 1/18/2017.
*/
/**
* Don't Be a Sad Panda.
*/
public class SadPandaException extends Exception {
public SadPandaException() {
super("SAD PANDA");
}
}
@@ -0,0 +1,43 @@
/*
* 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.ehviewer.client.exception;
/*
* Created by Hippo on 1/18/2017.
*/
/**
* A {@code Exception} for bad status code.
*/
public class StatusCodeException extends Exception {
private final int code;
public StatusCodeException(int code) {
super("Status code: " + code);
this.code = code;
}
public StatusCodeException(int code, Throwable cause) {
super("Status code: " + code, cause);
this.code = code;
}
public int code() {
return code;
}
}
@@ -0,0 +1,62 @@
/*
* 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.ehviewer.client.param;
/*
* Created by Hippo on 2/24/2017.
*/
import android.support.annotation.NonNull;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
public class GalleryMetadataParam {
public static final MediaType MEDIA_TYPE_JSON =
MediaType.parse("application/json; charset=utf-8");
private long[] gids;
private String[] tokens;
public GalleryMetadataParam(@NonNull long[] gids, @NonNull String[] tokens) {
this.gids = gids;
this.tokens = tokens;
}
public String toJson() {
StringBuilder sb = new StringBuilder();
sb.append("{\"method\":\"gdata\",\"gidlist\":[");
for (int i = 0, n = Math.min(gids.length, tokens.length); i < n; ++i) {
if (i != 0) {
sb.append(",");
}
sb.append("[").append(gids[i]).append(",\"").append(tokens[i]).append("\"]");
}
sb.append("],\"namespace\":1}");
return sb.toString();
}
public static class Converter implements retrofit2.Converter<GalleryMetadataParam, RequestBody> {
@Override
public RequestBody convert(GalleryMetadataParam value) throws IOException {
String json = value.toJson();
return RequestBody.create(MEDIA_TYPE_JSON, json);
}
}
}
@@ -0,0 +1,51 @@
/*
* 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.ehviewer.client.parser;
/*
* Created by Hippo on 5/18/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.data.ApiUidKey;
import com.hippo.ehviewer.client.exception.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class ApiUidKeyParser {
private ApiUidKeyParser() {}
private static final Pattern PATTERN_UID = Pattern.compile("var apiuid = (\\d+);");
private static final Pattern PATTERN_KEY = Pattern.compile("var apikey = \"(\\w+)\";");
/**
* Parses page to get api uid and api key.
*
* @throws ParseException if can't parse it
*/
@NonNull
public static ApiUidKey parseApiUidKey(@NonNull String body) throws ParseException {
Matcher matcher1 = PATTERN_UID.matcher(body);
Matcher matcher2 = PATTERN_KEY.matcher(body);
if (matcher1.find() && matcher2.find()) {
int uid = ParserUtils.parseInt(matcher1.group(1), 0);
String key = matcher2.group(2);
return new ApiUidKey(uid, key);
}
throw new ParseException("Can't get uid and key", body);
}
}
@@ -0,0 +1,118 @@
/*
* 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.ehviewer.client.parser;
/*
* Created by Hippo on 5/17/2017.
*/
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.util.Pair;
import com.hippo.ehviewer.client.data.FavouritesItem;
import com.hippo.ehviewer.client.data.FavouritesState;
import com.hippo.ehviewer.client.exception.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public final class FavouritesParser {
private FavouritesParser() {}
private static final Pattern PATTERN_DATE = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}");
private static final GalleryListParser.ItemCreator<FavouritesItem> FAVOURITES_ITEM_CREATOR =
(info, e) -> {
FavouritesItem item = new FavouritesItem();
item.info = info;
// Get favorite note
Element favNote = e.getElementById("favnote_" + info.gid);
if (favNote != null) {
String note = favNote.text();
if (note.startsWith("Note: ")) {
note = note.substring("Note: ".length());
}
item.note = note;
}
// Get favorite date
Matcher matcher = PATTERN_DATE.matcher(e.html());
if (matcher.find()) {
item.date = ParserUtils.parseDate(matcher.group(), 0);
}
return item;
};
/**
* Parses favourites page to a favourites item list.
*
* @throws ParseException if can't parse it
*/
@NonNull
public static List<FavouritesItem> parseFavourites(@NonNull String body,
@NonNull Document document) throws ParseException {
return GalleryListParser.parseGalleryList(body, document, FAVOURITES_ITEM_CREATOR);
}
/**
* Parses favourites page to a favourites state.
*
* @throws ParseException if can't parse it
*/
@NonNull
public static FavouritesState parseFavouritesState(@NonNull String body,
@NonNull Document document) throws ParseException {
Element ido = document.getElementsByClass("ido").first();
if (ido != null) {
List<Pair<String, Integer>> list = new ArrayList<>();
for (Element fp : ido.getElementsByClass("fp")) {
Elements children = fp.children();
if (children.size() < 3) continue;
String name = ParserUtils.unescape(children.get(2).text());
int count = ParserUtils.parseInt(children.get(0).text(), -1);
if (count == -1) continue;
list.add(new Pair<>(name, count));
}
if (!list.isEmpty()) {
return new FavouritesState(list);
}
}
throw new ParseException("Can't get favourites state", body);
}
/**
* Parses favourites page to pages.
*
* @throws ParseException if can't parse it
*/
@IntRange(from = 0)
public static int parsePages(@NonNull String body,
@NonNull Document document) throws ParseException {
return GalleryListParser.parsePages(body, document);
}
}
@@ -0,0 +1,67 @@
/*
* 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.ehviewer.client.parser;
/*
* Created by Hippo on 5/17/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.exception.ParseException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public final class ForumsParser {
private ForumsParser() {}
/**
* Same as {@code parseForums(body, Jsoup.parse(body))}.
*/
@NonNull
public static String parseForums(@NonNull String body) throws ParseException {
return parseForums(body, Jsoup.parse(body));
}
/**
* Parses gallery forums page to a profile url.
*
* @throws ParseException if can't parse it
*/
@NonNull
public static String parseForums(@NonNull String body, @NonNull Document document)
throws ParseException {
Element userLinks = document.getElementById("userlinks");
Element child = userLinks.children().first();
if (child != null) {
child = child.children().first();
if (child != null) {
child = child.children().first();
if (child != null) {
String url = child.attr("href");
url = ParserUtils.completeUrl(EhUrl.URL_FORUMS, url);
url = ParserUtils.unescape(url);
return url;
}
}
}
throw new ParseException("Can't get profile url", body);
}
}
@@ -0,0 +1,571 @@
/*
* 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.ehviewer.client.parser;
/*
* Created by Hippo on 5/17/2017.
*/
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.CommentEntry;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.PreviewPage;
import com.hippo.ehviewer.client.data.TagSet;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.url.ArchiveUrlParser;
import com.hippo.ehviewer.client.parser.url.CategoryUrlParser;
import com.hippo.ehviewer.client.parser.url.GalleryDetailUrlParser;
import com.hippo.yorozuya.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public final class GalleryDetailParser {
private GalleryDetailParser() {}
private static final String LOG_TAG = GalleryDetailParser.class.getSimpleName();
private static final Pattern PATTERN_GID = Pattern.compile("var gid = (\\d+);");
private static final Pattern PATTERN_TOKEN = Pattern.compile("var token = \"(\\w+)\";");
private static final Pattern PATTERN_COVER = Pattern.compile("width:(\\d+)px; height:(\\d+)px.+?url\\((.+?)\\)");
private static final Pattern PATTERN_ARCHIVE = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Archive Download</a>");
private static final Pattern PATTERN_TORRENT = Pattern.compile("<a[^<>]*onclick=\"return popUp\\('([^']+)'[^)]+\\)\">Torrent Download \\( (\\d+) \\)</a>");
private static final Pattern PATTERN_NORMAL_PREVIEW = Pattern.compile("width:(\\d+).+?height:(\\d+).+?url\\((.+?)\\).+?-(\\d+)px");
private static final String COMMENT_DATE_PREFIX = "Posted on ";
private static final String COMMENT_DATE_SUFFIX = " by:";
/**
* Parses gallery detail page to a {@link GalleryInfo} object.
* The {@code document} must be from the {@code body}.
* <p>
* Gid and token must be filled.
*
* @throws ParseException if can't parse it
*/
@NonNull
public static GalleryInfo parseGalleryDetail(@NonNull String body, @NonNull Document document)
throws ParseException {
GalleryInfo info = new GalleryInfo();
// Gid and token
Matcher matcher = PATTERN_GID.matcher(body);
if (matcher.find()) {
info.gid = ParserUtils.parseLong(matcher.group(1), 0);
}
matcher = PATTERN_TOKEN.matcher(body);
if (matcher.find()) {
info.token = matcher.group(1);
}
if (info.gid == 0 || info.token == null) {
throw new ParseException("Can't get gid or token", body);
}
// Title
parseTitle(document, info);
if (StringUtils.isEmpty(info.title) && StringUtils.isEmpty(info.titleJpn)) {
throw new ParseException("Can't get title", body);
}
// Cover
parseCover(document, info);
// Archive and Torrent
parseArchiveAndTorrent(document, info);
// Info
parseInfo(document, info);
// Rating
parseRating(document, info);
// Favourite slot
parseFavouriteSlot(document, info);
// TagSet
parseTagSet(document, info);
// Child
parseChild(document, info);
return info;
}
private static void parseCover(Document document, GalleryInfo info) {
Element gd1 = document.getElementById("gd1");
if (gd1 == null) return;
Element element = gd1.children().first();
if (element == null) return;
parseCoverStyle(element.attr("style"), info);
}
// 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 void parseCoverStyle(String str, GalleryInfo info) {
Matcher matcher = PATTERN_COVER.matcher(str);
if (!matcher.find()) return;
int width = ParserUtils.parseInt(matcher.group(1), 0);
int height = ParserUtils.parseInt(matcher.group(2), 0);
if (width >= 0 && height >= 0) {
info.coverRatio = (float) width / (float) height;
}
info.coverUrl = ParserUtils.unescape(matcher.group(3));
info.cover = EhUrl.getImageFingerprint(info.coverUrl);
}
private static void parseTitle(Document document, GalleryInfo info) {
Element gd2 = document.getElementById("gd2");
if (gd2 == null) return;
// Title
Element gn = gd2.getElementById("gn");
if (gn != null) {
info.title = ParserUtils.unescape(gn.text());
}
// Japanese title
Element gj = gd2.getElementById("gj");
if (gj != null) {
info.titleJpn = ParserUtils.unescape(gj.text());
}
}
private static void parseArchiveAndTorrent(Document document, GalleryInfo info) {
Element gd5 = document.getElementById("gd5");
if (gd5 == null) return;
String html = gd5.html();
parseArchive(html, info);
parseTorrent(html, info);
}
private static void parseArchive(String str, GalleryInfo info) {
if (str == null) return;
Matcher matcher = PATTERN_ARCHIVE.matcher(str);
if (!matcher.find()) return;
String url = ParserUtils.unescape(matcher.group(1));
ArchiveUrlParser.Result result = ArchiveUrlParser.parser(url);
if (result == null) return;
if ((info.gid == 0 || info.gid == result.gid) &&
(info.token == null || result.token.equals(info.token))) {
info.gid = result.gid;
info.token = result.token;
info.archiverKey = result.archiverKey;
} else {
Log.w(LOG_TAG, "The gid and token in archive url do not match. "
+ "They are " + result.gid + ", " + result.token + ". "
+ "They should be " + result.gid + ", " + result.token + ".");
}
}
private static void parseTorrent(String str, GalleryInfo info) {
Matcher matcher = PATTERN_TORRENT.matcher(str);
if (matcher.find()) {
info.torrentCount = ParserUtils.parseInt(matcher.group(2), 0);
}
}
private static void parseInfo(Document document, GalleryInfo info) {
Element gd3 = document.getElementById("gd3");
if (gd3 == null) return;
// Category
Element gdc = document.getElementById("gdc");
if (gdc != null) {
Element a = gdc.children().first();
if (a != null) {
String url = ParserUtils.unescape(a.attr("href"));
info.category = CategoryUrlParser.parser(url);
}
}
// Uploader
Element gdn = document.getElementById("gdn");
if (gdn != null) {
info.uploader = ParserUtils.unescape(gdn.text());
}
// Info table
Element gdd = document.getElementById("gdd");
if (gdd != null) {
Element tbody = gdd.getElementsByTag("tbody").first();
if (tbody != null) {
parseInfoTable(tbody, info);
}
}
}
private static void parseInfoTable(Element tbody, GalleryInfo info) {
for (Element e : tbody.children()) {
Elements es = e.children();
if (es.size() < 2) {
continue;
}
String key = ParserUtils.unescape(es.get(0).text());
String value = ParserUtils.unescape(es.get(1).ownText());
if (key.startsWith("Posted")) {
// Date
info.date = ParserUtils.parseDate(value, 0);
} else if (key.startsWith("Parent")) {
// Parent
Element a = es.get(1).children().first();
if (a != null) {
String url = ParserUtils.unescape(a.attr("href"));
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parser(url);
if (result != null) {
info.parentGid = result.gid;
info.parentToken = result.token;
}
}
} else if (key.startsWith("Visible")) {
// Invalid
info.invalid = !value.equalsIgnoreCase("yes");
} else if (key.startsWith("Language")) {
// Language
info.language = EhUtils.getLang(value);
} else if (key.startsWith("File Size")) {
// Size
info.size = parseSize(value);
} else if (key.startsWith("Length")) {
// Pages
int index = value.indexOf(' ');
if (index >= 0) {
info.pages = ParserUtils.parseInt(value.substring(0, index), 0);
}
} else if (key.startsWith("Favorited")) {
// Favourited
switch (value) {
case "Never":
info.favourited = 0;
break;
case "Once":
info.favourited = 1;
break;
default:
int index = value.indexOf(' ');
if (index != -1) {
info.favourited = ParserUtils.parseInt(value.substring(0, index), 0);
}
break;
}
}
}
}
private static long parseSize(String str) {
int index = str.indexOf(' ');
if (index < 0) return 0;
float num = ParserUtils.parseFloat(str.substring(0, index), 0.0f);
if (num == 0.0f) return 0;
str = str.substring(index + 1).toLowerCase();
index = str.indexOf('b');
if (index < 0) return 0;
// XX.XX B
if (index == 0) {
return (long) num;
}
char ch = str.charAt(index - 1);
switch (ch) {
case 'k':
// XX.XX KB
return (long) (num * 1024);
case 'm':
// XX.XX MB
return (long) (num * 1024 * 1024);
case 'g':
// XX.XX GB
return (long) (num * 1024 * 1024 * 1024);
default:
return 0;
}
}
private static void parseRating(Document document, GalleryInfo info) {
Element gdr = document.getElementById("gdr");
if (gdr == null) return;
Element rating_label = gdr.getElementById("rating_label");
if (rating_label != null) {
String ratingStr = ParserUtils.unescape(rating_label.text());
if (!"Not Yet Rated".equals(ratingStr)) {
int index = ratingStr.indexOf(' ');
if (index != -1) {
info.rating = ParserUtils.parseFloat(ratingStr.substring(index + 1), 0.0f);
}
}
}
Element rating_count = gdr.getElementById("rating_count");
if (rating_count != null) {
info.rated = ParserUtils.parseInt(rating_count.text(), 0);
}
}
private static void parseFavouriteSlot(Document document, GalleryInfo info) {
Element fav = document.getElementById("fav");
if (fav == null) return;
Element div = fav.children().first();
if (div == null) return;
info.favouriteSlot = GalleryListParser.parseFavouriteSlot(div.attr("style"));
}
private static void parseTagSet(Document document, GalleryInfo info) {
Element taglist = document.getElementById("taglist");
if (taglist == null) return;
Element tbody = taglist.getElementsByTag("tbody").first();
if (tbody == null) return;
TagSet tagSet = info.tagSet;
for (Element tr : tbody.children()) {
Elements children = tr.children();
if (children.size() < 2) continue;
String namespace = ParserUtils.unescape(children.get(0).text());
if (StringUtils.isEmpty(namespace)) continue;
if (namespace.endsWith(":")) {
namespace = namespace.substring(0, namespace.length() - 1);
}
parseTags(children.get(1), namespace, tagSet);
}
}
private static void parseTags(Element td, String namespace, TagSet tagSet) {
for (Element div : td.children()) {
String tag = ParserUtils.unescape(div.text());
if (!StringUtils.isEmpty(tag)) {
tagSet.add(namespace, tag);
}
}
}
private static void parseChild(Document document, GalleryInfo info) {
Element gnd = document.getElementById("gnd");
if (gnd == null) return;
Element a = gnd.getElementsByTag("a").first();
if (a == null) return;
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parser(a.attr("href"));
if (result != null) {
info.gid = result.gid;
info.token = result.token;
}
}
/**
* Parses gallery detail page to preview pages.
*
* @throws ParseException if can't parse it
*/
@NonNull
public static List<PreviewPage> parsePreviews(@NonNull String body,
@NonNull Document document) throws ParseException {
Element gdt = document.getElementById("gdt");
if (gdt != null) {
Elements gdts = gdt.children();
Element first = gdts.first();
if (first != null) {
String className = first.className();
if ("gdtl".equals(className)) {
return parseLargePreviews(gdts, body);
} else if ("gdtm".equals(className)) {
return parseNormalPreviews(gdts, body);
}
}
}
throw new ParseException("Can't parse previews", body);
}
@NonNull
private static List<PreviewPage> parseLargePreviews(Elements gdts, String body)
throws ParseException {
List<PreviewPage> list = new ArrayList<>();
for (Element gdtl : gdts) {
Element a = gdtl.children().first();
if (a == null) continue;
String url = ParserUtils.unescape(a.attr("href"));
if (!ParserUtils.isUrl(url)) continue;
Element img = a.children().first();
if (img == null) continue;
int index = ParserUtils.parseInt(img.attr("alt"), 0) - 1;
if (index == -1) continue;
String image = ParserUtils.unescape(img.attr("src"));
if (!ParserUtils.isUrl(image)) continue;
list.add(new PreviewPage(index, url, image));
}
if (!list.isEmpty()) {
return list;
} else {
throw new ParseException("Can't parse large previews", body);
}
}
@NonNull
private static List<PreviewPage> parseNormalPreviews(Elements gdts, String body)
throws ParseException {
List<PreviewPage> list = new ArrayList<>();
for (Element gdtm : gdts) {
Element div = gdtm.children().first();
if (div == null) continue;
Matcher matcher = PATTERN_NORMAL_PREVIEW.matcher(div.attr("style"));
if (!matcher.find()) continue;
int width = ParserUtils.parseInt(matcher.group(1), -1);
int height = ParserUtils.parseInt(matcher.group(2), -1);
String image = ParserUtils.unescape(matcher.group(3));
int clipLeft = ParserUtils.parseInt(matcher.group(4), -1);
if (width == -1 || height == -1 || !ParserUtils.isUrl(image) || clipLeft == -1) continue;
Element a = div.children().first();
if (a == null) continue;
String url = a.attr("href");
if (!ParserUtils.isUrl(url)) continue;
Element img = a.children().first();
if (img == null) continue;
int index = ParserUtils.parseInt(img.attr("alt"), 0) - 1;
if (index == -1) continue;
list.add(new PreviewPage(index, url, image, clipLeft, 0, width, height));
}
if (!list.isEmpty()) {
return list;
} else {
throw new ParseException("Can't parse normal previews", body);
}
}
/**
* Parses gallery detail page to a list of comment.
*
* @throws ParseException if can't parse it
*/
@NonNull
public static List<CommentEntry> parseComments(@NonNull String body,
@NonNull Document document) throws ParseException {
Element cdiv = document.getElementById("cdiv");
if (cdiv != null) {
List<CommentEntry> list = new ArrayList<>();
for (Element c1 : cdiv.children()) {
if (!"c1".equals(c1.className())) continue;
CommentEntry entry = parseCommentEntry(c1);
if (entry != null) {
list.add(entry);
}
}
if (!list.isEmpty()) {
return list;
}
}
throw new ParseException("Can't get comments", body);
}
@Nullable
private static CommentEntry parseCommentEntry(Element c1) {
// Id, required
Element a = c1.previousElementSibling();
if (a == null) return null;
String text = ParserUtils.unescape(a.attr("name"));
if (StringUtils.isEmpty(text)) return null;
int id = ParserUtils.parseInt(text.substring(1), -1);
if (id == -1) return null;
// Comment, required
Element c6 = c1.getElementsByClass("c6").first();
if (c6 == null) return null;
String comment = c6.html();
if (StringUtils.isEmpty(comment)) return null;
CommentEntry entry = new CommentEntry();
entry.id = id;
entry.comment = comment;
// Date
Element c3 = c1.getElementsByClass("c3").first();
if (c3 != null) {
text = ParserUtils.unescape(c3.ownText());
if (text.length() > COMMENT_DATE_PREFIX.length() + COMMENT_DATE_SUFFIX.length()) {
text = text.substring(COMMENT_DATE_PREFIX.length(),
text.length() - COMMENT_DATE_SUFFIX.length());
entry.date = ParserUtils.parseCommentDate(text, 0);
}
// User
a = c3.children().first();
if (a != null) {
entry.user = ParserUtils.unescape(a.text());
}
}
// Score
Element c5 = c1.getElementsByClass("c5").first();
if (c5 != null) {
Element span = c5.children().first();
if (span != null) {
entry.score = ParserUtils.parseInt(span.text(), 0);
}
}
// Vote up and vote down
Element c4 = c1.getElementsByClass("c4").first();
if (c4 != null) {
Elements es = c4.children();
if (es.size() == 2) {
entry.votedUp = !TextUtils.isEmpty(StringUtils.trim(es.get(0).attr("style")));
entry.votedDown = !TextUtils.isEmpty(StringUtils.trim(es.get(1).attr("style")));
}
}
// Vote state
Element c7 = c1.getElementsByClass("c7").first();
if (c7 != null) {
entry.voteState = ParserUtils.unescape(c7.text());
}
return entry;
}
}
@@ -0,0 +1,315 @@
/*
* 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.ehviewer.client.parser;
/*
* Created by Hippo on 5/17/2017.
*/
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.url.GalleryDetailUrlParser;
import com.hippo.yorozuya.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public final class GalleryListParser {
private GalleryListParser() {}
private static final String EMPTY_KEYWORD = "No hits found</p>";
private static final Pattern PATTERN_COVER_SIZE = Pattern.compile("height:(\\d+)px; width:(\\d+)px");
private static final Pattern PATTERN_PX = Pattern.compile("(\\d+)px");
private static final ItemCreator<GalleryInfo> GALLERY_INFO_CREATOR = (info, e) -> info;
/**
* Parses gallery list page to a gallery info list.
*
* @throws ParseException if can't parse it
*/
@NonNull
public static List<GalleryInfo> parseGalleryList(@NonNull String body,
@NonNull Document document) throws ParseException {
return parseGalleryList(body, document, GALLERY_INFO_CREATOR);
}
/**
* Creates the actual item.
*/
interface ItemCreator<T> {
/**
* Creates a item from the {@link GalleryInfo} and the {@link Element}.
*/
@Nullable
T create(@NonNull GalleryInfo info, @NonNull Element e);
}
/**
* Parses gallery list page to a list.
*
* @throws ParseException if can't parse it
*/
@NonNull
static <T> List<T> parseGalleryList(@NonNull String body, @NonNull Document document,
@NonNull ItemCreator<T> creator) throws ParseException {
Element itg = document.getElementsByClass("itg").first();
if (itg != null) {
Element tbody = itg.children().first();
if (tbody != null) {
List<T> list = new ArrayList<>();
boolean isHeader = true;
for (Element e : tbody.children()) {
// First one is table header, skip it
if (isHeader) {
isHeader = false;
continue;
}
T t = parseItem(e, creator);
if (t != null) {
list.add(t);
}
}
if (!list.isEmpty()) {
return list;
}
}
}
throw new ParseException("Can't parse gallery list", body);
}
@Nullable
private static <T> T parseItem(Element e, ItemCreator<T> creator) {
// gid, token, title (required)
Element it5 = e.getElementsByClass("it5").first();
if (it5 == null) return null;
Element a = it5.children().first();
if (a == null) return null;
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parser(a.attr("href"));
if (result == null) return null;
String title = ParserUtils.unescape(a.text());
if (StringUtils.isEmpty(title)) return null;
GalleryInfo info = new GalleryInfo();
info.gid = result.gid;
info.token = result.token;
// TODO It might be jpn title
info.title = title;
info.language = EhUtils.guessLang(title);
// Category
Element ic = e.getElementsByClass("ic").first();
if (ic != null) {
info.category = EhUtils.getCategory(ParserUtils.unescape(ic.attr("alt")));
}
// Date
Element itd = e.getElementsByClass("itd").first();
if (itd != null) {
info.date = ParserUtils.parseDate(itd.text(), 0);
}
// Cover
Element it2 = e.getElementsByClass("it2").first();
if (it2 != null) {
// Cover ratio
Matcher m = PATTERN_COVER_SIZE.matcher(it2.attr("style"));
if (m.find()) {
int width = ParserUtils.parseInt(m.group(2), 0);
int height = ParserUtils.parseInt(m.group(1), 0);
if (width >= 0 && height >= 0) {
info.coverRatio = (float) width / (float) height;
}
}
// Cover url
Elements es = it2.children();
if (!es.isEmpty()) {
info.coverUrl = ParserUtils.unescape(es.get(0).attr("src"));
} else {
info.coverUrl = ParserUtils.unescape(parseCoverUrl(it2.text()));
}
// Cover
if (info.coverUrl != null) {
info.cover = EhUrl.getImageFingerprint(info.coverUrl);
}
}
Element it3 = e.getElementsByClass("it3").first();
if (it3 != null) {
String favId = "favicon_" + info.gid;
for (Element child: it3.children()) {
// Favourite slot
if (favId.equals(child.id())) {
info.favouriteSlot = parseFavouriteSlot(child.attr("style"));
}
Elements children = child.children();
// invalid
if (children.size() >= 1 && "E".equals(children.get(0).attr("alt"))) {
info.invalid = true;
}
}
}
// Rating
Element it4r = e.getElementsByClass("it4r").first();
if (it4r != null) {
info.rating = parseRating(it4r.attr("style"));
}
// Uploader
Element itu = e.getElementsByClass("itu").first();
if (itu != null) {
info.uploader = ParserUtils.unescape(itu.text());
}
return creator.create(info, e);
}
// Parses url from a string like:
// inits~exhentai.org~t/53/a8/53a82a8deec79d3824ab413b4cf784d6df8589b2-1264635-1050-1540-png_l.jpg~(C91) [ガンバリマシン (Shino)] Pさん、今日も頑張ってくれませんか? (アイドルマスター シンデレラガールズ)
private static String parseCoverUrl(String str) {
int index1 = str.indexOf('~');
if (index1 == -1) return null;
int index2 = str.indexOf('~', index1 + 1);
if (index2 == -1) return null;
int index3 = str.indexOf('~', index2 + 1);
if (index3 == -1) return null;
return "https://" + str.substring(index1 + 1, index2) + "/" + str.substring(index2 + 1, index3);
}
/**
* Parse the style string to get favourite slot.
* <p>
* Ehentai website uses a picture to show favourite slot.
* Looks like: <pre>{@code
* ------------------
* ◇
* ◇
* ◇
* ◇
* ◇
* ◇
* ◇
* ◇
* ◇
* ◇
*
* ------------------
* }</pre>
* The style looks like:
* {@code background-position:0px -2px}.
* The first one is x offset, always 0.
* The second one is y offset, starts from -2, step -19.
*/
public static int parseFavouriteSlot(String style) {
Matcher m = PATTERN_PX.matcher(style);
// Move to the second one
if (!m.find() || !m.find()) return EhUtils.FAV_CAT_UNKNOWN;
int num = ParserUtils.parseInt(m.group(1), 0);
if (num == 0) return EhUtils.FAV_CAT_UNKNOWN;
int slot = (num - 2) / 19;
if (slot >= 0 && slot <= 9) {
return slot;
} else {
return EhUtils.FAV_CAT_UNKNOWN;
}
}
// ehentai website uses a picture to show rating.
// Looks like:
// ------------------
// ⛤ ⛤ ⛤ ⛤ ⛤
// ⛤ ⛤ ⛤ ⛤ half⛤
// ------------------
// The style looks like:
// background-position:-16px -1px
// The first one is x offset, 16px for a star.
// The second one is y offset, row1 is -1px, row2 is -21px
public static float parseRating(String style) {
Matcher m = PATTERN_PX.matcher(style);
int num1;
int num2;
float rate = 5.0f;
if (m.find()) {
num1 = ParserUtils.parseInt(m.group(1), -1);
} else {
return 0.0f;
}
if (m.find()) {
num2 = ParserUtils.parseInt(m.group(1), -1);
} else {
return 0.0f;
}
if (num1 == -1 || num2 == -1) {
return 0.0f;
}
rate = rate - (num1 / 16);
if (num2 == 21) {
rate -= 0.5f;
}
return rate;
}
/**
* Parses gallery list page to pages.
*
* @throws ParseException if can't parse it
*/
@IntRange(from = 0)
public static int parsePages(@NonNull String body,
@NonNull Document document) throws ParseException {
int pages = 0;
Element ptt = document.getElementsByClass("ptt").first();
if (ptt != null) {
Element tbody = ptt.children().first();
if (tbody != null) {
Element tr = tbody.children().first();
if (tr != null) {
Elements tds = tr.children();
if (tds.size() >= 2) {
pages = ParserUtils.parseInt(tds.get(tds.size() - 2).text(), 0);
}
}
}
}
if (pages == 0 && !body.contains(EMPTY_KEYWORD)) {
throw new ParseException("Can't get pages", body);
}
return pages;
}
}
@@ -0,0 +1,126 @@
/*
* 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.ehviewer.client.parser;
/*
* Created by Hippo on 5/17/2017.
*/
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.util.JSONUtils;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public final class GalleryMetadataParser {
private GalleryMetadataParser() {}
private static final String DEFAULT_GROUP = "misc";
/**
* Parses gallery metadata json to a list of {@link GalleryInfo}.
* <p>
* Gid and token must be filled.
*
* @throws ParseException if can't parse it
*/
@NonNull
public static List<GalleryInfo> parseGalleryMetadata(@NonNull String body) throws ParseException {
List<GalleryInfo> galleryInfoList = new ArrayList<>();
try {
JSONObject jo = new JSONObject(body);
JSONArray ja = jo.getJSONArray("gmetadata");
for (int i = 0, n = ja.length(); i < n; ++i) {
GalleryInfo info = parseGalleryInfo(ja.getJSONObject(i));
if (info != null) {
galleryInfoList.add(info);
}
}
} catch (JSONException e) {
throw new ParseException("Can't parse gallery metadata json", body, e);
}
return galleryInfoList;
}
@Nullable
private static GalleryInfo parseGalleryInfo(JSONObject jo) {
GalleryInfo info = new GalleryInfo();
info.gid = jo.optLong("gid");
if (info.gid == 0) return null;
info.token = JSONUtils.optString(jo, "token");
if (info.token == null) return null;
info.title = ParserUtils.unescape(JSONUtils.optString(jo, "title"));
if (info.title != null) {
info.language = EhUtils.guessLang(info.title);
}
info.titleJpn = JSONUtils.optString(jo, "title_jpn");
if (info.language == EhUtils.LANG_UNKNOWN && info.titleJpn != null) {
info.language = EhUtils.guessLang(info.titleJpn);
}
if (StringUtils.isEmpty(info.title) || StringUtils.isEmpty(info.titleJpn)) return null;
info.archiverKey = JSONUtils.optString(jo, "archiver_key");
info.category = EhUtils.getCategory(JSONUtils.optString(jo, "category"));
info.coverUrl = ParserUtils.unescape(JSONUtils.optString(jo, "thumb"));
info.cover = EhUrl.getImageFingerprint(info.coverUrl);
info.uploader = JSONUtils.optString(jo, "uploader");
info.date = NumberUtils.parseLong(JSONUtils.optString(jo, "posted"), 0) * 1000;
info.pages = NumberUtils.parseInt(JSONUtils.optString(jo, "filecount"), 0);
info.size = NumberUtils.parseLong(JSONUtils.optString(jo, "filesize"), 0);
info.invalid = jo.optBoolean("expunged", false);
info.rating = NumberUtils.parseFloat(JSONUtils.optString(jo, "rating"), 0.0f);
info.torrentCount = NumberUtils.parseInt(JSONUtils.optString(jo, "torrentcount"), 0);
JSONArray tags = jo.optJSONArray("tags");
if (tags != null) {
for (int i = 0, n = tags.length(); i < n; ++i) {
String tag = JSONUtils.optString(tags, i);
if (tag == null) continue;
String group;
String name;
int index = tag.indexOf(":");
if (index == -1) {
// Default group
group = DEFAULT_GROUP;
name = tag;
} else {
group = tag.substring(0, index);
name = tag.substring(index + 1);
}
info.tagSet.add(group, name);
}
}
return info;
}
}
@@ -0,0 +1,211 @@
/*
* 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.ehviewer.client.parser;
/*
* Created by Hippo on 1/30/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
public final class ParserUtils {
private ParserUtils() {}
private static final String IMPURITIES_INT = ",";
private final static DateFormat DATE_FORMAT;
private final static DateFormat DATE_FORMAT_COMMENT;
static {
DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
DATE_FORMAT_COMMENT = new SimpleDateFormat("dd MMMMM yyyy, HH:mm z", Locale.ENGLISH);
}
/**
* Remove specified chars in the string.
*/
private static String cleanString(String str, String impurities, boolean removeWhiteSpace) {
if (str == null) {
return null;
}
if (impurities == null) {
impurities = StringUtils.EMPTY;
}
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0, n = str.length(); i < n; ++i) {
char ch = str.charAt(i);
if (impurities.indexOf(ch) != -1) {
continue;
}
if (removeWhiteSpace && (Character.isSpaceChar(ch) || Character.isWhitespace(ch))) {
continue;
}
sb.append(ch);
}
return sb.toString();
}
/**
* Parses string to int.
* Example: {@code " 23,532 "}.
* Return {@code defaultValue} if can't parse the string.
*/
public static int parseInt(@NonNull String str, int defaultValue) {
str = unescape(str);
str = cleanString(str, IMPURITIES_INT, true);
return NumberUtils.parseInt(str, defaultValue);
}
/**
* Parses string to long.
* Example: {@code " 23,532 "}.
* Return {@code defaultValue} if can't parse the string.
*/
public static long parseLong(@NonNull String str, long defaultValue) {
str = unescape(str);
str = cleanString(str, IMPURITIES_INT, true);
return NumberUtils.parseLong(str, defaultValue);
}
/**
* Parses string to long.
* Example: {@code " 23,532.67 "}.
* Return {@code defaultValue} if can't parse the string.
*/
public static float parseFloat(@NonNull String str, float defaultValue) {
str = unescape(str);
str = cleanString(str, IMPURITIES_INT, true);
return NumberUtils.parseFloat(str, defaultValue);
}
/**
* Parses string to time stamp.
* Example: {@code "2017-01-30 05:19"}.
* Return {@code defaultValue} if can't parse the string.
*/
public static long parseDate(@NonNull String str, long defaultValue) {
str = unescape(str);
try {
return DATE_FORMAT.parse(str).getTime();
} catch (ParseException e) {
return defaultValue;
}
}
/**
* Parses string to time stamp.
* Example: {@code "16 May 2017, 02:28 UTC"}.
* Return {@code defaultValue} if can't parse the string.
*/
public static long parseCommentDate(@NonNull String str, long defaultValue) {
str = unescape(str);
try {
return DATE_FORMAT_COMMENT.parse(str).getTime();
} catch (ParseException e) {
return defaultValue;
}
}
/**
* Converts relative url to absolute url.
*/
public static String completeUrl(@NonNull String base, @NonNull String url) {
if (url.startsWith("http://") || url.startsWith("https://")) {
return url;
} else {
return StringUtils.join(base, url, '/');
}
}
/**
* Remove white characters from both ends of the string.
* <p>
* Don't use {@link StringUtils#strip(String)}, it can't remove some characters.
*/
public static String strip(String str) {
if (StringUtils.isEmpty(str)) return str;
int strLen = str.length();
int start = 0;
while (start != strLen) {
char ch = str.charAt(start);
if (Character.isSpaceChar(ch) || Character.isWhitespace(ch)) {
start++;
} else {
break;
}
}
int end = strLen;
while (end != start) {
char ch = str.charAt(end - 1);
if (Character.isSpaceChar(ch) || Character.isWhitespace(ch)) {
end--;
} else {
break;
}
}
return str.substring(start, end);
}
private static final String[] ESCAPE_CHARACTER_LIST = {
"&amp;",
"&lt;",
"&gt;",
"&quot;",
"&#039;",
"&times;",
"&nbsp;"
};
private static final String[] UNESCAPE_CHARACTER_LIST = {
"&",
"<",
">",
"\"",
"'",
"×",
"\u00a0"
};
/**
* Unescape xml and strip.
*/
public static String unescape(String str) {
str = StringUtils.replaceEach(str, ESCAPE_CHARACTER_LIST, UNESCAPE_CHARACTER_LIST);
return strip(str);
}
/**
* Returns {@code true} if the string is a url.
*/
public static boolean isUrl(String str) {
return str != null && (str.startsWith("http://") || str.startsWith("https://"));
}
}
@@ -0,0 +1,81 @@
/*
* 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.ehviewer.client.parser;
/*
* Created by Hippo on 5/17/2017.
*/
import android.support.annotation.NonNull;
import android.util.Pair;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.yorozuya.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public final class ProfileParser {
private ProfileParser() {}
/**
* Same as {@code parseProfile(body, Jsoup.parse(body))}.
*/
@NonNull
public static Pair<String, String> parseProfile(@NonNull String body) throws ParseException {
return parseProfile(body, Jsoup.parse(body));
}
/**
* Parses profile page to a pair of name and avatar.
* The {@code document} must be from the {@code body}.
* <p>
* The name can't be {@code null}, the avatar could be {@code null}.
*
* @throws ParseException if can't parse it
*/
@NonNull
public static Pair<String, String> parseProfile(@NonNull String body,
@NonNull Document document) throws ParseException {
String name = null;
String avatar = null;
Element profileName = document.getElementById("profilename");
if (profileName != null) {
name = ParserUtils.unescape(profileName.text());
Element element = profileName.nextElementSibling();
if (element != null) {
element = element.nextElementSibling();
if (element != null) {
element = element.children().first();
if (element != null) {
avatar = element.attr("src");
avatar = ParserUtils.unescape(avatar);
avatar = ParserUtils.completeUrl(EhUrl.URL_FORUMS, avatar);
}
}
}
}
if (StringUtils.isEmpty(name)) {
throw new ParseException("Can't parse profile page", body);
}
return new Pair<>(name, avatar);
}
}
@@ -0,0 +1,58 @@
/*
* 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.ehviewer.client.parser;
/*
* Created by Hippo on 5/17/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.exception.GeneralException;
import com.hippo.ehviewer.client.exception.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class SignInParser {
private SignInParser() {}
private static final Pattern PATTERN_NAME = Pattern.compile("<p>You are now logged in as: (.+?)<");
private static final Pattern PATTERN_ERROR = Pattern.compile(
"(?:<h4>The error returned was:</h4>\\s*<p>(.+?)</p>)"
+ "|(?:<span class=\"postcolor\">(.+?)</span>)");
/**
* Parses sign in page to a profile name.
*
* @throws GeneralException if get a error in the body
* @throws ParseException if can't parse it
*/
@NonNull
public static String parseSignIn(@NonNull String body)
throws GeneralException, ParseException {
Matcher m = PATTERN_NAME.matcher(body);
if (m.find()) {
return ParserUtils.unescape(m.group(1));
} else {
m = PATTERN_ERROR.matcher(body);
if (m.find()) {
throw new GeneralException(m.group(1) == null ? m.group(2) : m.group(1));
} else {
throw new ParseException("Can't parse the html of signing in", body);
}
}
}
}
@@ -0,0 +1,114 @@
/*
* 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.ehviewer.client.parser;
/*
* Created by Hippo on 5/17/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhUrl;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.exception.ParseException;
import com.hippo.ehviewer.client.parser.url.GalleryDetailUrlParser;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public final class WhatsHotParser {
private WhatsHotParser() {}
/**
* Same as {@code parseWhatsHot(body, Jsoup.parse(body))}.
*/
public static List<GalleryInfo> parseWhatsHot(@NonNull String body) throws ParseException {
return parseWhatsHot(body, Jsoup.parse(body));
}
/**
* Parses whats hot page to a gallery info list.
*
* @throws ParseException if can't parse it
*/
public static List<GalleryInfo> parseWhatsHot(@NonNull String body, @NonNull Document document)
throws ParseException {
Element pp = document.getElementById("pp");
if (pp != null) {
List<GalleryInfo> list = new ArrayList<>();
for (Element id1 : pp.getElementsByClass("id1")) {
GalleryInfo info = parseGalleryInfo(id1);
if (info != null) {
list.add(info);
}
}
if (!list.isEmpty()) {
return list;
}
}
throw new ParseException("Can't parse whats hot", body);
}
private static GalleryInfo parseGalleryInfo(Element element) {
Element id3 = element.getElementsByClass("id3").first();
if (id3 == null) return null;
Element a = id3.getElementsByTag("a").first();
if (a == null) return null;
String url = a.attr("href");
GalleryDetailUrlParser.Result result = GalleryDetailUrlParser.parser(url);
if (result == null) return null;
GalleryInfo info = new GalleryInfo();
info.gid = result.gid;
info.token = result.token;
Element img = a.getElementsByTag("img").first();
if (img != null) {
info.coverUrl = ParserUtils.unescape(img.attr("src"));
info.cover = EhUrl.getImageFingerprint(info.coverUrl);
// TODO Might be title jpn
info.title = ParserUtils.unescape(img.attr("title"));
info.language = EhUtils.guessLang(info.title);
}
Element id41 = element.getElementsByClass("id41").first();
if (id41 != null) {
info.category = EhUtils.getCategory(ParserUtils.unescape(id41.attr("title")));
}
Element id42 = element.getElementsByClass("id42").first();
if (id42 != null) {
String text = id42.text();
int index = text.indexOf(' ');
if (index >= 0) {
info.pages = ParserUtils.parseInt(text.substring(0, index), 0);
}
}
Element id43 = element.getElementsByClass("id43").first();
if (id43 != null) {
info.rating = GalleryListParser.parseRating(id43.attr("style"));
}
return info;
}
}
@@ -0,0 +1,67 @@
/*
* 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.ehviewer.client.parser.url;
/*
* Created by Hippo on 5/16/2017.
*/
import android.net.UrlQuerySanitizer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.yorozuya.NumberUtils;
import com.hippo.yorozuya.StringUtils;
public class ArchiveUrlParser {
public static class Result {
public final long gid;
public final String token;
public final String archiverKey;
public Result(long gid, String token, String archiverKey) {
this.gid = gid;
this.token = token;
this.archiverKey = archiverKey;
}
}
// https://exhentai.org/archiver.php?gid=1063451&token=6cc24065cb&or=415253--00cbf86c557d53304ba6d23b7faf64f9928156ca
/**
* Parses a archiver url. The url looks like:
* {@code https://exhentai.org/archiver.php?gid=1063451&token=6cc24065cb&or=415253--00cbf86c557d53304ba6d23b7faf64f9928156ca}
* Returns {@code null} if can't parse it.
*/
@Nullable
public static Result parser(@NonNull String url) {
UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
sanitizer.setAllowUnregisteredParamaters(true);
sanitizer.setUnregisteredParameterValueSanitizer(UrlQuerySanitizer.getAllButNulLegal());
sanitizer.parseUrl(url);
long gid = NumberUtils.parseLong(sanitizer.getValue("gid"), 0);
if (gid == 0) return null;
String token = sanitizer.getValue("token");
if (StringUtils.isEmpty(token)) return null;
String archiverKey = sanitizer.getValue("or");
if (StringUtils.isEmpty(archiverKey)) return null;
return new Result(gid, token, archiverKey);
}
}
@@ -0,0 +1,45 @@
/*
* 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.ehviewer.client.parser.url;
/*
* Created by Hippo on 5/16/2017.
*/
import android.support.annotation.NonNull;
import com.hippo.ehviewer.client.EhUtils;
public class CategoryUrlParser {
// https://exhentai.org/doujinshi
/**
* Parses a category url. The url looks like:
* {@code https://exhentai.org/doujinshi}
* Returns {@link EhUtils#CATEGORY_UNKNOWN} if can't parse it.
*/
public static int parser(@NonNull String str) {
if (str.charAt(str.length() - 1) == '/') {
str = str.substring(0, str.length() - 1);
}
int index = str.lastIndexOf("/");
if (index >= 0) {
return EhUtils.getCategory(str.substring(index + 1));
} else {
return EhUtils.CATEGORY_UNKNOWN;
}
}
}
@@ -0,0 +1,58 @@
/*
* 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.ehviewer.client.parser.url;
/*
* Created by Hippo on 5/16/2017.
*/
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GalleryDetailUrlParser {
public static final Pattern URL_PATTERN = Pattern.compile("/g/(\\d+)/(\\w+)");
public static class Result {
public final long gid;
public final String token;
public Result(long gid, String token) {
this.gid = gid;
this.token = token;
}
}
// https://exhentai.org/g/1060346/03702a68a5/
/**
* Parses a gallery detail url. The url looks like:
* {@code https://exhentai.org/g/1060346/03702a68a5/}
* Returns {@code null} if can't parse it.
*/
@Nullable
public static Result parser(@NonNull String url) {
Matcher matcher = URL_PATTERN.matcher(url);
if (matcher.find()) {
long gid = Long.parseLong(matcher.group(1));
String token = matcher.group(2);
return new Result(gid, token);
}
return null;
}
}
@@ -0,0 +1,61 @@
/*
* 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.ehviewer.client.parser.url;
/*
* Created by Hippo on 5/16/2017.
*/
import android.net.UrlQuerySanitizer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.yorozuya.NumberUtils;
public class TorrentUrlParser {
public static class Result {
public final long gid;
public final String token;
public Result(long gid, String token) {
this.gid = gid;
this.token = token;
}
}
// https://exhentai.org/gallerytorrents.php?gid=1063451&t=6cc24065cb
/**
* Parses a torrent url. The url looks like:
* {@code https://exhentai.org/gallerytorrents.php?gid=1063451&t=6cc24065cb}
* Returns {@code null} if can't parse it.
*/
@Nullable
public static Result parser(@NonNull String url) {
UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
sanitizer.setAllowUnregisteredParamaters(true);
sanitizer.setUnregisteredParameterValueSanitizer(UrlQuerySanitizer.getAllButNulLegal());
sanitizer.parseUrl(url);
long gid = NumberUtils.parseLong(sanitizer.getValue("gid"), 0);
if (gid == 0) return null;
String token = sanitizer.getValue("t");
if (token == null) return null;
return new Result(gid, token);
}
}
@@ -0,0 +1,79 @@
/*
* 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.ehviewer.client.result;
/*
* Created by Hippo on 3/4/2017.
*/
import com.hippo.ehviewer.client.EhResult;
import com.hippo.ehviewer.client.data.FavouritesItem;
import com.hippo.ehviewer.client.data.FavouritesState;
import java.util.List;
/**
* Result for {@link com.hippo.ehviewer.client.converter.FavouritesConverter}.
*/
public class FavouritesResult extends EhResult {
private int pages;
private List<FavouritesItem> fis;
private FavouritesState state;
public FavouritesResult(int pages, List<FavouritesItem> fis, FavouritesState state) {
super(null);
this.pages = pages;
this.fis = fis;
this.state = state;
}
/**
* Returns favourites pages.
*/
public int pages() {
return pages;
}
/**
* Returns FavouritesItem list.
*/
public List<FavouritesItem> list() {
return fis;
}
/**
* Returns favourites state.
* <p>
* Favourites slot name, favourites count
*/
public FavouritesState state() {
return state;
}
////////////////
// Pain part
////////////////
private FavouritesResult(Throwable t) {
super(t);
}
public static FavouritesResult error(Throwable t) {
return new FavouritesResult(t);
}
}
@@ -0,0 +1,50 @@
/*
* 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.ehviewer.client.result;
/*
* Created by Hippo on 2/12/2017.
*/
import com.hippo.ehviewer.client.EhResult;
public class ForumsResult extends EhResult {
private String profileUrl;
public ForumsResult(String profileUrl) {
super(null);
this.profileUrl = profileUrl;
}
public String profileUrl() {
return profileUrl;
}
////////////////
// Pain part
////////////////
private ForumsResult(Throwable t) {
super(t);
}
public static ForumsResult error(Throwable t) {
return new ForumsResult(t);
}
}
@@ -0,0 +1,79 @@
/*
* 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.ehviewer.client.result;
/*
* Created by Hippo on 5/15/2017.
*/
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.EhResult;
import com.hippo.ehviewer.client.data.ApiUidKey;
import com.hippo.ehviewer.client.data.CommentEntry;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.PreviewPage;
import java.util.List;
public class GalleryDetailResult extends EhResult {
private GalleryInfo info;
private List<CommentEntry> comments;
private List<PreviewPage> previews;
private ApiUidKey apiUidKey;
public GalleryDetailResult(@NonNull GalleryInfo info, List<CommentEntry> comments,
List<PreviewPage> previews, ApiUidKey apiUidKey) {
super(null);
this.info = info;
this.comments = comments;
this.previews = previews;
this.apiUidKey = apiUidKey;
}
public GalleryInfo getGalleryInfo() {
return info;
}
@Nullable
public List<CommentEntry> getComments() {
return comments;
}
@Nullable
public List<PreviewPage> getPreviews() {
return previews;
}
@Nullable
public ApiUidKey getApiUidKey() {
return apiUidKey;
}
////////////////
// Pain part
////////////////
private GalleryDetailResult(Throwable t) {
super(t);
}
public static GalleryDetailResult error(Throwable t) {
return new GalleryDetailResult(t);
}
}
@@ -0,0 +1,52 @@
/*
* 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.ehviewer.client.result;
/*
* Created by Hippo on 1/29/2017.
*/
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.result.base.GalleryInfoListResult;
import java.util.List;
public class GalleryListResult extends GalleryInfoListResult {
private int pages;
public GalleryListResult(int pages, List<GalleryInfo> gis) {
super(gis);
this.pages = pages;
}
public int pages() {
return pages;
}
////////////////
// Pain part
////////////////
protected GalleryListResult(Throwable t) {
super(t);
}
public static GalleryListResult error(Throwable t) {
return new GalleryListResult(t);
}
}
@@ -0,0 +1,45 @@
/*
* 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.ehviewer.client.result;
/*
* Created by Hippo on 2/24/2017.
*/
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.result.base.GalleryInfoListResult;
import java.util.List;
public class GalleryMetadataResult extends GalleryInfoListResult {
public GalleryMetadataResult(List<GalleryInfo> gis) {
super(gis);
}
////////////////
// Pain part
////////////////
private GalleryMetadataResult(Throwable t) {
super(t);
}
public static GalleryMetadataResult error(Throwable t) {
return new GalleryMetadataResult(t);
}
}
Loaded 100 of 1190 files, more files were not shown because too many files have changed in this diff. Show more