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
351 changed files with 29264 additions and 2 deletions

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
*.iml
.gradle
/local.properties
/.idea
.DS_Store
/build
/captures
.externalNativeBuild
/src
+1
View File
@@ -0,0 +1 @@
/build
+124
View File
@@ -0,0 +1,124 @@
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'android-chinese-string'
apply plugin: 'com.hippo.android-preferences'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.hippo.ehviewer"
minSdkVersion 14
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 {
buildConfigField "String", "APPLICATION_NAME", "\"${APPLICATION_NAME}\""
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
androidPreferences {
preference from: 'com.hippo.ehviewer.EhvPreferencesImpl', to: 'com.hippo.ehviewer.EhvPreferences'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
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'
}
+98
View File
@@ -0,0 +1,98 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in E:\Android\android-sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Don't obfuscate
-dontobfuscate
###########################################################################
## Fresco
###########################################################################
# 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 *;
}
-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 rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
rx.internal.util.atomic.LinkedQueueNode producerNode;
}
-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueConsumerNodeRef {
rx.internal.util.atomic.LinkedQueueNode consumerNode;
}
-dontwarn sun.misc.Unsafe
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<resources>
<string name="app_name">EhViewer Debug</string>
</resources>
+45
View File
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2016 Hippo Seven
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<manifest
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"/>
<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=".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>
@@ -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();
}
}
@@ -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;
/*
* 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();
}
}
@@ -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();
}
@@ -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);
}
}
@@ -0,0 +1,28 @@
/*
* 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.
*/
/**
*
*/
public class EhConfig {
}
@@ -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);
}
}
@@ -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/30/2017.
*/
/**
* {@code ParseException} for inner.
*/
public class InnerParseException extends Exception {
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);
}
}
@@ -0,0 +1,31 @@
/*
* 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.
*/
/**
* 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);
}
}
@@ -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.result;
/*
* Created by Hippo on 2/12/2017.
*/
import android.support.annotation.Nullable;
import com.hippo.ehviewer.client.EhResult;
public class ProfileResult extends EhResult {
private String name;
private String avatar;
public ProfileResult(String name, String avatar) {
super(null);
this.name = name;
this.avatar = avatar;
}
public String name() {
return name;
}
@Nullable
public String avatar() {
return avatar;
}
////////////////
// Pain part
////////////////
private ProfileResult(Throwable t) {
super(t);
}
public static ProfileResult error(Throwable t) {
return new ProfileResult(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 1/19/2017.
*/
import com.hippo.ehviewer.client.EhResult;
public class RecaptchaChallengeResult extends EhResult {
private String challenge;
public RecaptchaChallengeResult(String challenge) {
super(null);
this.challenge = challenge;
}
public String challenge() {
return challenge;
}
////////////////
// Pain part
////////////////
private RecaptchaChallengeResult(Throwable t) {
super(t);
}
public static RecaptchaChallengeResult error(Throwable t) {
return new RecaptchaChallengeResult(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 1/19/2017.
*/
import com.hippo.ehviewer.client.EhResult;
public class RecaptchaImageResult extends EhResult {
private String image;
public RecaptchaImageResult(String image) {
super(null);
this.image = image;
}
public String image() {
return image;
}
////////////////
// Pain part
////////////////
private RecaptchaImageResult(Throwable t) {
super(t);
}
public static RecaptchaImageResult error(Throwable t) {
return new RecaptchaImageResult(t);
}
}
@@ -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.result;
/*
* Created by Hippo on 1/19/2017.
*/
import com.hippo.ehviewer.client.EhResult;
public class RecaptchaResult extends EhResult {
private String challenge;
private String image;
public RecaptchaResult() {
super(null);
}
public String challenge() {
return challenge;
}
public void challenge(String challenge) {
this.challenge = challenge;
}
public String image() {
return image;
}
public void image(String image) {
this.image = image;
}
}
@@ -0,0 +1,53 @@
/*
* 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/18/2017.
*/
import com.hippo.ehviewer.client.EhResult;
/**
* A result of signing in, contains profile name.
*/
public class SignInResult extends EhResult {
private String profileName;
public SignInResult(String profileName) {
super(null);
this.profileName = profileName;
}
public String profileName() {
return profileName;
}
////////////////
// Pain part
////////////////
private SignInResult(Throwable t) {
super(t);
}
public static SignInResult error(Throwable t) {
return new SignInResult(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.result;
/*
* Created by Hippo on 1/24/2017.
*/
import com.hippo.ehviewer.client.EhResult;
/**
* Void, nothing.
*/
public class VoidResult extends EhResult {
private static class InstanceHolder {
private static final VoidResult INSTANCE = new VoidResult();
}
private VoidResult() {
super(null);
}
public static VoidResult getInstance() {
return InstanceHolder.INSTANCE;
}
////////////////
// Pain part
////////////////
private VoidResult(Throwable t) {
super(t);
}
public static VoidResult error(Throwable t) {
return new VoidResult(t);
}
}
@@ -0,0 +1,48 @@
/*
* 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;
/**
* A result of whats hot, contains GalleryInfo list.
*/
public class WhatsHotResult extends GalleryInfoListResult {
public WhatsHotResult(List<GalleryInfo> gis) {
super(gis);
}
////////////////
// Pain part
////////////////
private WhatsHotResult(Throwable t) {
super(t);
}
public static WhatsHotResult error(Throwable t) {
return new WhatsHotResult(t);
}
}
@@ -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.result.base;
/*
* Created by Hippo on 2/24/2017.
*/
import com.hippo.ehviewer.client.EhResult;
import com.hippo.ehviewer.client.data.GalleryInfo;
import java.util.List;
/**
* {@code EhResult} with only a {@code List<GalleryInfo>}.
*/
public abstract class GalleryInfoListResult extends EhResult {
private List<GalleryInfo> gis;
public GalleryInfoListResult(List<GalleryInfo> gis) {
super(null);
this.gis = gis;
}
public List<GalleryInfo> galleryInfoList() {
return gis;
}
////////////////
// Pain part
////////////////
protected GalleryInfoListResult(Throwable t) {
super(t);
}
}
@@ -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.component;
/*
* Created by Hippo on 2/3/2017.
*/
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Let ViewHolders bind themselves.
*/
public abstract class BindingViewHolder<T> extends RecyclerView.ViewHolder {
public BindingViewHolder(View itemView) {
super(itemView);
}
/**
* Binds the ViewHolder with the {@code t}.
*/
public abstract void bind(T t);
}
@@ -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.component;
/*
* Created by Hippo on 2/24/2017.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.hippo.easyrecyclerview.EasyAdapter;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.widget.ContentContract;
/**
* Abstract {@code Adapter} for gallery info list.
* <p>
* Implements {@link #createDetailHolder(LayoutInflater, ViewGroup)}
* and {@link #createBriefHolder(LayoutInflater, ViewGroup)}
* to create actual {@code ViewHolder}.
*/
public abstract class GalleryInfoAdapter extends EasyAdapter<BindingViewHolder<GalleryInfo>> {
private static final int TYPE_DETAIL = 0;
private static final int TYPE_BRIEF = 1;
public LayoutInflater inflater;
public ContentContract.DataPresenter<GalleryInfo> data;
public int type = TYPE_DETAIL;
public GalleryInfoAdapter(Context context, ContentContract.DataPresenter<GalleryInfo> data) {
this.inflater = LayoutInflater.from(context);
this.data = data;
}
@Override
public final BindingViewHolder<GalleryInfo> onCreateViewHolder2(ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_DETAIL:
return createDetailHolder(inflater, parent);
case TYPE_BRIEF:
return createBriefHolder(inflater, parent);
default:
throw new IllegalStateException("Unknown view type: " + viewType);
}
}
/**
* Creates detail gallery info {@code ViewHolder}.
*/
protected abstract BindingViewHolder<GalleryInfo> createDetailHolder(
LayoutInflater inflater, ViewGroup parent);
/**
* Creates brief gallery info {@code ViewHolder}.
*/
protected abstract BindingViewHolder<GalleryInfo> createBriefHolder(
LayoutInflater inflater, ViewGroup parent);
@Override
public final void onBindViewHolder(BindingViewHolder<GalleryInfo> holder, int position) {
holder.bind(data.get(position));
}
@Override
public final int getItemCount() {
return data.size();
}
@Override
public final long getItemId(int position) {
return data.get(position).gid;
}
@Override
public final int getItemViewType(int position) {
return type;
}
/**
* Switches to detail mode.
*/
public final void showDetail() {
if (type != TYPE_DETAIL) {
type = TYPE_DETAIL;
notifyDataSetChanged();
}
}
/**
* Switches to brief mode.
*/
public final void showBrief() {
if (type != TYPE_BRIEF) {
type = TYPE_BRIEF;
notifyDataSetChanged();
}
}
/**
* Solidify the data to release the actual data.
*/
public final void solidify() {
data = data.solidify();
}
}
@@ -0,0 +1,75 @@
/*
* 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.component;
/*
* Created by Hippo on 3/4/2017.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.widget.CoverView;
import com.hippo.ehviewer.widget.NumberRatingView;
/**
* {@code GalleryInfoBriefHolder} shows brief of a {@link GalleryInfo}.
*/
public abstract class GalleryInfoBriefHolder<T> extends BindingViewHolder<T> {
private static final int CATEGORY_ALPHA = 0x8a000000;
private CoverView cover;
private View category;
private NumberRatingView rating;
private TextView language;
protected GalleryInfoBriefHolder(View view) {
super(view);
cover = (CoverView) view.findViewById(R.id.cover);
category = view.findViewById(R.id.category);
rating = (NumberRatingView) view.findViewById(R.id.rating);
language = (TextView) view.findViewById(R.id.language);
}
/**
* Binds {@link GalleryInfo} to itself.
*/
protected void bindGalleryInfo(GalleryInfo info) {
Context context = cover.getContext();
cover.load(info);
category.setBackgroundColor(setAlpha(EhUtils.getCategoryColor(info.category), CATEGORY_ALPHA));
rating.setRating(info.rating);
language.setText(EhUtils.getLangAbbr(context, info.language));
}
private static int setAlpha(int color, int alpha) {
return (color & 0x00ffffff) | alpha;
}
/**
* Creates actual view.
*/
protected static View createView(LayoutInflater inflater, ViewGroup container) {
return inflater.inflate(R.layout.item_gallery_info_brief, container, false);
}
}
@@ -0,0 +1,90 @@
/*
* 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.component;
/*
* Created by Hippo on 3/2/2017.
*/
import android.support.annotation.Nullable;
import com.google.gson.Gson;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.reactivex.Catcher;
import com.hippo.ehviewer.reactivex.Thrower1;
import com.hippo.ehviewer.util.JsonStore;
import com.hippo.ehviewer.widget.ContentData;
import java.io.File;
import java.util.List;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Actions;
import rx.schedulers.Schedulers;
/**
* {@code GalleryInfoData} is a {@code ContentData} of {@link GalleryInfo}.
*/
public abstract class GalleryInfoData extends ContentData<GalleryInfo> {
public GalleryInfoData() {
setRemoveDuplicates(true);
}
/**
* Returns the file to store backup data.
*/
protected abstract File getBackupFile();
/**
* Returns the {@link Gson} to serialize and deserialize {@link GalleryInfo}.
*/
protected abstract Gson getGson();
@Override
protected void onRestoreData(long id) {
Observable.just(getBackupFile())
.map(Thrower1.from(file -> JsonStore.fetchList(getGson(), file, GalleryInfo.class)))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
list -> setData(id, list, 1),
Catcher.from(e -> setError(id, e))
);
}
@Override
protected void onBackupData(List<GalleryInfo> data) {
Observable.just(data)
.map(Thrower1.from(d -> {
JsonStore.push(getGson(), getBackupFile(), d, GalleryInfo.class);
return true;
}))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(Actions.empty(), Actions.empty());
}
@Override
protected boolean isDuplicate(@Nullable GalleryInfo t1, @Nullable GalleryInfo t2) {
if (t1 == null && t2 == null) {
return true;
}
if (t1 != null && t2 != null) {
return t1.gid == t2.gid;
}
return false;
}
}
@@ -0,0 +1,99 @@
/*
* 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.component;
/*
* Created by Hippo on 3/4/2017.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.hippo.ehviewer.R;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.util.ReadableTime;
import com.hippo.ehviewer.widget.CoverView;
import com.hippo.ehviewer.widget.SmallRatingView;
/**
* {@code GalleryInfoDetailHolder} shows detail of a {@link GalleryInfo}.
*/
public abstract class GalleryInfoDetailHolder<T> extends BindingViewHolder<T> {
private CoverView cover;
private TextView title;
private TextView uploader;
private SmallRatingView rating;
private TextView category;
private TextView date;
private TextView language;
private View favourite;
private View download;
private View invalid;
private TextView note;
protected GalleryInfoDetailHolder(View view) {
super(view);
cover = (CoverView) view.findViewById(R.id.cover);
title = (TextView) view.findViewById(R.id.title);
uploader = (TextView) view.findViewById(R.id.uploader);
rating = (SmallRatingView) view.findViewById(R.id.rating);
category = (TextView) view.findViewById(R.id.category);
date = (TextView) view.findViewById(R.id.date);
language = (TextView) view.findViewById(R.id.language);
favourite = view.findViewById(R.id.favourite);
download = view.findViewById(R.id.download);
invalid = view.findViewById(R.id.invalid);
note = (TextView) view.findViewById(R.id.note);
}
/**
* Binds {@link GalleryInfo} to itself.
*/
protected void bindGalleryInfo(GalleryInfo info) {
Context context = cover.getContext();
cover.load(info);
// TODO titleJpn
title.setText(info.title);
uploader.setText(info.uploader);
rating.setRating(info.rating);
category.setText(EhUtils.getCategoryNotNull(info.category));
category.setBackgroundColor(EhUtils.getCategoryColor(info.category));
date.setText(ReadableTime.getTimeAgo(context, info.date));
language.setText(EhUtils.getLangAbbr(context, info.language));
favourite.setVisibility(info.favouriteSlot != EhUtils.FAV_CAT_UNKNOWN ? View.VISIBLE : View.GONE);
download.setVisibility(View.GONE);
invalid.setVisibility(info.invalid ? View.VISIBLE : View.GONE);
}
/**
* Binds note to itself.
*/
protected void bindNote(String note) {
this.note.setText(note);
}
/**
* Creates actual view.
*/
protected static View createView(LayoutInflater inflater, ViewGroup container) {
return inflater.inflate(R.layout.item_gallery_info_detail, container, false);
}
}
@@ -0,0 +1,34 @@
/*
* 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.component;
/*
* Created by Hippo on 2/3/2017.
*/
import android.view.View;
import com.hippo.ehviewer.client.data.GalleryInfo;
/**
* Makes BindingViewHolder<GalleryInfo> short.
*/
public abstract class GalleryInfoHolder extends BindingViewHolder<GalleryInfo> {
public GalleryInfoHolder(View itemView) {
super(itemView);
}
}
@@ -0,0 +1,115 @@
/*
* 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.content;
/*
* Created by Hippo on 1/26/2017.
*/
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import rx.functions.Action1;
/**
* Records all activities.
*/
public class RecordingApplication extends Application {
private List<WeakReference<Activity>> list = new LinkedList<>();
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
list.add(new java.lang.ref.WeakReference<>(activity));
}
@Override
public void onActivityDestroyed(Activity activity) {
Iterator<WeakReference<Activity>> iterator = list.iterator();
while (iterator.hasNext()) {
WeakReference<Activity> reference = iterator.next();
Activity a = reference.get();
// Remove current activity and null
if (a == null || a == activity) {
iterator.remove();
}
}
}
@Override
public void onActivityStarted(Activity activity) {}
@Override
public void onActivityResumed(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
});
}
/**
* Finish all activities.
*/
public void finish() {
// Copy list
ArrayList<Activity> listCopy = new ArrayList<>(list.size());
for (WeakReference<Activity> reference: list) {
Activity activity = reference.get();
if (activity == null) continue;
listCopy.add(activity);
}
// Finish all activities
for (int i = listCopy.size() - 1; i >= 0; --i) {
listCopy.get(i).finish();
}
}
/**
* Calls {@code action} on each {@link Activity}.
*/
public void foreach(Action1<Activity> action) {
// Copy list
ArrayList<Activity> listCopy = new ArrayList<>(list.size());
for (WeakReference<Activity> reference: list) {
Activity activity = reference.get();
if (activity == null) continue;
listCopy.add(activity);
}
// Recreate all activities
for (int i = listCopy.size() - 1; i >= 0; --i) {
action.call(listCopy.get(i));
}
}
}
@@ -0,0 +1,48 @@
/*
* 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.contract;
/*
* Created by Hippo on 2/24/2017.
*/
import android.content.Context;
import android.support.annotation.NonNull;
import com.hippo.ehviewer.component.GalleryInfoAdapter;
import com.hippo.ehviewer.presenter.PresenterInterface;
import com.hippo.ehviewer.view.ViewInterface;
import com.hippo.ehviewer.widget.ContentLayout;
public interface GalleryInfoContract {
interface Presenter<V extends View> extends PresenterInterface<V> {
/**
* Attaches Presenter to the {@code ContentLayout}.
* Returns the {@code RecyclerView.Adapter}.
*/
@NonNull
GalleryInfoAdapter attachContentLayout(Context context, ContentLayout layout);
/**
* Detaches Presenter from the {@code ContentLayout}.
*/
void detachContentLayout(ContentLayout layout);
}
interface View extends ViewInterface {}
}
@@ -0,0 +1,96 @@
/*
* 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.dao;
/*
* Created by Hippo on 3/5/2017.
*/
import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;
import com.google.gson.Gson;
import com.hippo.ehviewer.client.data.FavouritesItem;
import com.hippo.ehviewer.database.MSQLite;
import com.hippo.ehviewer.util.DBUtils;
import com.pushtorefresh.storio.sqlite.SQLiteTypeMapping;
public class FavouritesItemMapping extends SQLiteTypeMapping<FavouritesItem> {
public static final String TABLE_NAME = "favourites";
public static final String COLUMN_NOTE = "note";
public static final String COLUMN_DATE = "date";
public FavouritesItemMapping(Gson gson) {
super(
new FavouritesItemPutResolver(gson, TABLE_NAME),
new FavouritesItemGetResolver(gson),
new FavouritesItemDeleteResolver(gson, TABLE_NAME)
);
}
/**
* Table for FavouritesItem version 1.
*/
public static void version1(MSQLite ms) {
ms.createTable(TABLE_NAME, GalleryInfoContainerMapping.COLUMN_GID, long.class)
.insertColumn(TABLE_NAME, COLUMN_NOTE, String.class)
.insertColumn(TABLE_NAME, COLUMN_DATE, long.class);
}
private static class FavouritesItemPutResolver
extends GalleryInfoContainerMapping.UniquePutResolver<FavouritesItem> {
protected FavouritesItemPutResolver(@NonNull Gson gson, @NonNull String tableName) {
super(gson, tableName);
}
@NonNull
@Override
protected ContentValues mapToContentValues(@NonNull FavouritesItem item) {
ContentValues contentValues = new ContentValues(3);
contentValues.put(COLUMN_NOTE, item.note);
contentValues.put(COLUMN_DATE, item.date);
return contentValues;
}
}
private static class FavouritesItemGetResolver
extends GalleryInfoContainerMapping.GetResolver<FavouritesItem> {
protected FavouritesItemGetResolver(@NonNull Gson gson) {
super(gson);
}
@NonNull
@Override
protected FavouritesItem mapFromCursor2(@NonNull Cursor cursor) {
FavouritesItem item = new FavouritesItem();
item.note = DBUtils.getString(cursor, COLUMN_NOTE, null);
item.date = DBUtils.getLong(cursor, COLUMN_DATE, 0);
return item;
}
}
private static class FavouritesItemDeleteResolver
extends GalleryInfoContainerMapping.UniqueDeleteResolver<FavouritesItem> {
protected FavouritesItemDeleteResolver(@NonNull Gson gson, @NonNull String tableName) {
super(gson, tableName);
}
}
}
@@ -0,0 +1,568 @@
/*
* 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.dao;
/*
* Created by Hippo on 3/5/2017.
*/
import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.util.Log;
import com.google.gson.Gson;
import com.hippo.ehviewer.client.EhUtils;
import com.hippo.ehviewer.client.data.GalleryInfo;
import com.hippo.ehviewer.client.data.GalleryInfoContainer;
import com.hippo.ehviewer.client.data.TagSet;
import com.hippo.ehviewer.database.MSQLite;
import com.hippo.ehviewer.util.DBUtils;
import com.pushtorefresh.storio.internal.InternalQueries;
import com.pushtorefresh.storio.sqlite.StorIOSQLite;
import com.pushtorefresh.storio.sqlite.operations.delete.DeleteResult;
import com.pushtorefresh.storio.sqlite.operations.put.PutResult;
import com.pushtorefresh.storio.sqlite.queries.DeleteQuery;
import com.pushtorefresh.storio.sqlite.queries.InsertQuery;
import com.pushtorefresh.storio.sqlite.queries.Query;
import com.pushtorefresh.storio.sqlite.queries.RawQuery;
import com.pushtorefresh.storio.sqlite.queries.UpdateQuery;
/**
* {@code GalleryInfoContainerMapping} can map {@link GalleryInfoContainer}.
* Please extend {@link PutResolver}, {@link GetResolver} and {@link DeleteResolver}.
* <p>
* Must contain a {@link #COLUMN_GID} column in item table to store {@link GalleryInfo#gid}.
* <p>
* If use {@link GalleryInfo} as primary key, please extend {@link UniquePutResolver}
* and {@link UniqueDeleteResolver}.
*/
@SuppressWarnings("TryFinallyCanBeTryWithResources")
public final class GalleryInfoContainerMapping {
private GalleryInfoContainerMapping() {}
private static final String LOG_TAG = GalleryInfoContainerMapping.class.getSimpleName();
@VisibleForTesting
static final String TABLE_NAME = "gallery_info";
public static final String COLUMN_GID = "gid";
private static final String COLUMN_TOKEN = "token";
private static final String COLUMN_TITLE = "title";
private static final String COLUMN_TITLE_JPN = "title_jpn";
private static final String COLUMN_COVER = "cover";
private static final String COLUMN_COVER_URL = "cover_url";
private static final String COLUMN_COVER_RATIO = "cover_ratio";
private static final String COLUMN_CATEGORY = "category";
private static final String COLUMN_DATE = "date";
private static final String COLUMN_UPLOADER = "uploader";
private static final String COLUMN_RATING = "rating";
private static final String COLUMN_RATED = "rated";
private static final String COLUMN_LANGUAGE = "language";
private static final String COLUMN_FAVOURITED = "favourited";
private static final String COLUMN_FAVOURITE_SLOT = "favourite_slot";
private static final String COLUMN_INVALID = "invalid";
private static final String COLUMN_PAGES = "pages";
private static final String COLUMN_SIZE = "size";
private static final String COLUMN_TORRENT_COUNT = "torrent_count";
private static final String COLUMN_TAGS = "tags";
private static final String COLUMN_PARENT_GID = "parent_gid";
private static final String COLUMN_PARENT_TOKEN = "parent_token";
private static final String COLUMN_CHILD_GID = "child_gid";
private static final String COLUMN_CHILD_TOKEN = "child_token";
@VisibleForTesting
static final String COLUMN_REFERENCE = "reference";
/**
* GalleryInfo table version 1.
*/
public static void galleryInfoTableVersion1(MSQLite ms) {
ms.createTable(TABLE_NAME, COLUMN_GID, long.class)
.insertColumn(TABLE_NAME, COLUMN_TOKEN, String.class)
.insertColumn(TABLE_NAME, COLUMN_TITLE, String.class)
.insertColumn(TABLE_NAME, COLUMN_TITLE_JPN, String.class)
.insertColumn(TABLE_NAME, COLUMN_COVER, String.class)
.insertColumn(TABLE_NAME, COLUMN_COVER_URL, String.class)
.insertColumn(TABLE_NAME, COLUMN_COVER_RATIO, float.class)
.insertColumn(TABLE_NAME, COLUMN_CATEGORY, int.class)
.insertColumn(TABLE_NAME, COLUMN_DATE, long.class)
.insertColumn(TABLE_NAME, COLUMN_UPLOADER, String.class)
.insertColumn(TABLE_NAME, COLUMN_RATING, float.class)
.insertColumn(TABLE_NAME, COLUMN_RATED, int.class)
.insertColumn(TABLE_NAME, COLUMN_LANGUAGE, int.class)
.insertColumn(TABLE_NAME, COLUMN_FAVOURITED, int.class)
.insertColumn(TABLE_NAME, COLUMN_FAVOURITE_SLOT, int.class)
.insertColumn(TABLE_NAME, COLUMN_INVALID, boolean.class)
.insertColumn(TABLE_NAME, COLUMN_PAGES, int.class)
.insertColumn(TABLE_NAME, COLUMN_SIZE, long.class)
.insertColumn(TABLE_NAME, COLUMN_TORRENT_COUNT, int.class)
.insertColumn(TABLE_NAME, COLUMN_TAGS, String.class)
.insertColumn(TABLE_NAME, COLUMN_REFERENCE, int.class)
.insertColumn(TABLE_NAME, COLUMN_PARENT_GID, int.class)
.insertColumn(TABLE_NAME, COLUMN_PARENT_TOKEN, String.class)
.insertColumn(TABLE_NAME, COLUMN_CHILD_GID, int.class)
.insertColumn(TABLE_NAME, COLUMN_CHILD_TOKEN, String.class);
}
private static ContentValues mapGalleryInfoToContentValues(@NonNull Gson gson,
@NonNull GalleryInfo info, int reference) {
ContentValues contentValues = new ContentValues(19);
contentValues.put(COLUMN_GID, info.gid);
contentValues.put(COLUMN_TOKEN, info.token);
contentValues.put(COLUMN_TITLE, info.title);
contentValues.put(COLUMN_TITLE_JPN, info.titleJpn);
contentValues.put(COLUMN_COVER, info.cover);
contentValues.put(COLUMN_COVER_URL, info.coverUrl);
contentValues.put(COLUMN_COVER_RATIO, info.coverRatio);
contentValues.put(COLUMN_CATEGORY, info.category);
contentValues.put(COLUMN_DATE, info.date);
contentValues.put(COLUMN_UPLOADER, info.uploader);
contentValues.put(COLUMN_RATING, info.rating);
contentValues.put(COLUMN_RATED, info.rated);
contentValues.put(COLUMN_LANGUAGE, info.language);
contentValues.put(COLUMN_FAVOURITED, info.favourited);
contentValues.put(COLUMN_FAVOURITE_SLOT, info.favouriteSlot);
contentValues.put(COLUMN_INVALID, info.invalid);
contentValues.put(COLUMN_PAGES, info.pages);
contentValues.put(COLUMN_SIZE, info.size);
contentValues.put(COLUMN_TORRENT_COUNT, info.torrentCount);
contentValues.put(COLUMN_TAGS, gson.toJson(info.tagSet));
contentValues.put(COLUMN_PARENT_GID, info.parentGid);
contentValues.put(COLUMN_PARENT_TOKEN, info.parentToken);
contentValues.put(COLUMN_CHILD_GID, info.childGid);
contentValues.put(COLUMN_CHILD_TOKEN, info.childToken);
contentValues.put(COLUMN_REFERENCE, reference);
return contentValues;
}
@NonNull
private static GalleryInfo mapGalleryInfoFromCursor(@NonNull Cursor cursor, @NonNull Gson gson) {
GalleryInfo info = new GalleryInfo();
info.gid = DBUtils.getLong(cursor, COLUMN_GID, 0);
info.token = DBUtils.getString(cursor, COLUMN_TOKEN, null);
info.title = DBUtils.getString(cursor, COLUMN_TITLE, null);
info.titleJpn = DBUtils.getString(cursor, COLUMN_TITLE_JPN, null);
info.cover = DBUtils.getString(cursor, COLUMN_COVER, null);
info.coverUrl = DBUtils.getString(cursor, COLUMN_COVER_URL, null);
info.coverRatio = DBUtils.getFloat(cursor, COLUMN_COVER_RATIO, 0.0f);
info.category = DBUtils.getInt(cursor, COLUMN_CATEGORY, EhUtils.CATEGORY_UNKNOWN);
info.date = DBUtils.getLong(cursor, COLUMN_DATE, 0);
info.uploader = DBUtils.getString(cursor, COLUMN_UPLOADER, null);
info.rating = DBUtils.getFloat(cursor, COLUMN_RATING, 0.0f);
info.rated = DBUtils.getInt(cursor, COLUMN_RATED, 0);
info.language = DBUtils.getInt(cursor, COLUMN_LANGUAGE, EhUtils.LANG_UNKNOWN);
info.favourited = DBUtils.getInt(cursor, COLUMN_FAVOURITED, 0);
info.favouriteSlot = DBUtils.getInt(cursor, COLUMN_FAVOURITE_SLOT, EhUtils.FAV_CAT_UNKNOWN);
info.invalid = DBUtils.getBoolean(cursor, COLUMN_INVALID, false);
info.pages = DBUtils.getInt(cursor, COLUMN_PAGES, 0);
info.size = DBUtils.getLong(cursor, COLUMN_SIZE, 0);
info.torrentCount = DBUtils.getInt(cursor, COLUMN_TORRENT_COUNT, 0);
// Tags
String tags = DBUtils.getString(cursor, COLUMN_TAGS, null);
if (tags != null) {
info.tagSet.set(gson.fromJson(tags, TagSet.class));
}
info.parentGid = DBUtils.getInt(cursor, COLUMN_PARENT_GID, 0);
info.parentToken = DBUtils.getString(cursor, COLUMN_PARENT_TOKEN, null);
info.childGid = DBUtils.getInt(cursor, COLUMN_CHILD_GID, 0);
info.childToken = DBUtils.getString(cursor, COLUMN_CHILD_TOKEN, null);
return info;
}
// Insert GalleryInfo, or update GalleryInfo and increment reference
private static void putGalleryInfo(@NonNull StorIOSQLite.LowLevel lowLevel,
@NonNull Gson gson, @NonNull GalleryInfo info) {
final Cursor cursor = lowLevel.query(Query.builder()
.table(TABLE_NAME)
.where(COLUMN_GID + " = ?")
.whereArgs(info.gid)
.build());
try {
if (cursor.moveToNext()) {
// Found old GalleryInfo, merge, increment reference, put back
final GalleryInfo oldInfo = mapGalleryInfoFromCursor(cursor, gson);
final int reference = DBUtils.getInt(cursor, COLUMN_REFERENCE, 1);
oldInfo.merge(info);
final UpdateQuery updateQuery = UpdateQuery.builder()
.table(TABLE_NAME)
.where(COLUMN_GID + " = ?")
.whereArgs(info.gid)
.build();
lowLevel.update(updateQuery, mapGalleryInfoToContentValues(gson, info, reference + 1));
} else {
// Can't find old GalleryInfo, insert new one
final InsertQuery insertQuery = InsertQuery.builder()
.table(TABLE_NAME)
.build();
lowLevel.insert(insertQuery, mapGalleryInfoToContentValues(gson, info, 1));
}
} finally {
cursor.close();
}
}
// Update GalleryInfo keeping reference
private static void updateGalleryInfo(@NonNull StorIOSQLite.LowLevel lowLevel,
@NonNull Gson gson, @NonNull GalleryInfo info) {
final Cursor cursor = lowLevel.query(Query.builder()
.table(TABLE_NAME)
.where(COLUMN_GID + " = ?")
.whereArgs(info.gid)
.build());
try {
if (cursor.moveToNext()) {
final GalleryInfo oldInfo = mapGalleryInfoFromCursor(cursor, gson);
final int reference = DBUtils.getInt(cursor, COLUMN_REFERENCE, 1);
oldInfo.merge(info);
final UpdateQuery updateQuery = UpdateQuery.builder()
.table(TABLE_NAME)
.where(COLUMN_GID + " = ?")
.whereArgs(info.gid)
.build();
lowLevel.update(updateQuery, mapGalleryInfoToContentValues(gson, info, reference));
} else {
Log.e(LOG_TAG, "Can't get GalleryInfo in db: " + info.gid);
}
} finally {
cursor.close();
}
}
private static GalleryInfo getGalleryInfo(@NonNull StorIOSQLite.LowLevel lowLevel,
@NonNull Gson gson, long gid) {
final Cursor cursor = lowLevel.query(Query.builder()
.table(TABLE_NAME)
.where(COLUMN_GID + " = ?")
.whereArgs(gid)
.build());
try {
if (cursor.moveToNext()) {
return mapGalleryInfoFromCursor(cursor, gson);
} else {
Log.e(LOG_TAG, "Can't get GalleryInfo in db: " + gid);
}
} finally {
cursor.close();
}
return null;
}
// Decrement GalleryInfo reference, or delete it from database
private static void deleteGalleryInfo(@NonNull StorIOSQLite.LowLevel lowLevel,
@NonNull Gson gson, @NonNull GalleryInfo info) {
final Cursor cursor = lowLevel.query(Query.builder()
.table(TABLE_NAME)
.where(COLUMN_GID + " = ?")
.whereArgs(info.gid)
.build());
try {
if (cursor.moveToNext()) {
int reference = DBUtils.getInt(cursor, COLUMN_REFERENCE, 1);
if (reference <= 1) {
// Delete the GalleryInfo
final DeleteQuery deleteQuery = DeleteQuery.builder()
.table(TABLE_NAME)
.where(COLUMN_GID + " = ?")
.whereArgs(info.gid)
.build();
lowLevel.delete(deleteQuery);
} else {
// Merge, decrement reference, put back
final GalleryInfo oldInfo = mapGalleryInfoFromCursor(cursor, gson);
oldInfo.merge(info);
final UpdateQuery updateQuery = UpdateQuery.builder()
.table(TABLE_NAME)
.where(COLUMN_GID + " = ?")
.whereArgs(info.gid)
.build();
lowLevel.update(updateQuery, mapGalleryInfoToContentValues(gson, info, reference - 1));
}
} else {
Log.e(LOG_TAG, "Can't get GalleryInfo in db: " + info.gid);
}
} finally {
cursor.close();
}
}
/**
* Puts {@link GalleryInfoContainer} to database.
* The table must contains a column named {@link #COLUMN_GID}
* to store {@link GalleryInfo#gid}.
*/
public static abstract class PutResolver<T extends GalleryInfoContainer> extends
com.pushtorefresh.storio.sqlite.operations.put.PutResolver<T> {
private Gson gson;
protected PutResolver(@NonNull Gson gson) {
this.gson = gson;
}
/**
* Converts object of required type to {@link InsertQuery}.
*
* @param object non-null object that should be converted to {@link InsertQuery}.
* @return non-null {@link InsertQuery}.
*/
@NonNull
protected abstract InsertQuery mapToInsertQuery(@NonNull T object);
/**
* Converts object of required type to {@link UpdateQuery}.
*
* @param object non-null object that should be converted to {@link UpdateQuery}.
* @return non-null {@link UpdateQuery}.
*/
@NonNull
protected abstract UpdateQuery mapToUpdateQuery(@NonNull T object);
/**
* Converts object of required type to {@link ContentValues}.
* <p>
* {@link GalleryInfo#gid} will be put to the {@link ContentValues}.
*
* @param object non-null object that should be converted to {@link ContentValues}.
* @return non-null {@link ContentValues}.
*/
@NonNull
protected abstract ContentValues mapToContentValues(@NonNull T object);
@NonNull
@Override
public PutResult performPut(@NonNull StorIOSQLite sql, @NonNull T item) {
final UpdateQuery updateQuery = mapToUpdateQuery(item);
final StorIOSQLite.LowLevel lowLevel = sql.lowLevel();
// for data consistency in concurrent environment, encapsulate Put Operation into transaction
lowLevel.beginTransaction();
try {
final Cursor cursor = lowLevel.query(Query.builder()
.table(updateQuery.table())
.where(InternalQueries.nullableString(updateQuery.where()))
.whereArgs((Object[]) InternalQueries.nullableArrayOfStringsFromListOfStrings(updateQuery.whereArgs()))
.build());
final PutResult putResult;
try {
final GalleryInfo info = item.getGalleryInfo();
final ContentValues contentValues = mapToContentValues(item);
contentValues.put(COLUMN_GID, info != null ? info.gid : 0);
if (cursor.getCount() == 0) {
if (info != null) {
putGalleryInfo(lowLevel, gson, info);
}
final InsertQuery insertQuery = mapToInsertQuery(item);
final long insertedId = lowLevel.insert(insertQuery, contentValues);
putResult = PutResult.newInsertResult(insertedId, insertQuery.table());
} else {
if (info != null) {
updateGalleryInfo(lowLevel, gson, info);
}
final int numberOfRowsUpdated = lowLevel.update(updateQuery, contentValues);
putResult = PutResult.newUpdateResult(numberOfRowsUpdated, updateQuery.table());
}
} finally {
cursor.close();
}
// everything okay
lowLevel.setTransactionSuccessful();
return putResult;
} finally {
// in case of bad situations, db won't be affected
lowLevel.endTransaction();
}
}
}
/**
* The item table use {@link GalleryInfo} as primary key.
*/
public static abstract class UniquePutResolver<T extends GalleryInfoContainer>
extends PutResolver<T> {
private String tableName;
protected UniquePutResolver(@NonNull Gson gson, @NonNull String tableName) {
super(gson);
this.tableName = tableName;
}
@NonNull
@Override
protected InsertQuery mapToInsertQuery(@NonNull T object) {
return InsertQuery.builder()
.table(tableName)
.build();
}
@NonNull
@Override
protected UpdateQuery mapToUpdateQuery(@NonNull T object) {
GalleryInfo info = object.getGalleryInfo();
return UpdateQuery.builder()
.table(tableName)
.where(COLUMN_GID + " = ?")
.whereArgs(info != null ? info.gid : 0)
.build();
}
}
/**
* Gets {@link GalleryInfoContainer} from database.
* The table must contains a column named {@link #COLUMN_GID}
* to store {@link GalleryInfo#gid}.
*/
public static abstract class GetResolver<T extends GalleryInfoContainer> extends
com.pushtorefresh.storio.sqlite.operations.get.GetResolver<T> {
private StorIOSQLite.LowLevel lowLevel;
private Gson gson;
protected GetResolver(@NonNull Gson gson) {
this.gson = gson;
}
/**
* Converts {@link Cursor} with already set position to object of required type.
* <p>
* {@link GalleryInfoContainer#setGalleryInfo(GalleryInfo)} will be called after it.
*
* @param cursor not closed {@link Cursor} with already set position
* that should be parsed and converted to object of required type.
* @return non-null object of required type with data parsed from passed {@link Cursor}.
*/
@NonNull
protected abstract T mapFromCursor2(@NonNull Cursor cursor);
@NonNull
@Override
public T mapFromCursor(@NonNull Cursor cursor) {
T item = mapFromCursor2(cursor);
long gid = DBUtils.getLong(cursor, COLUMN_GID, 0);
if (gid != 0) {
GalleryInfo info = getGalleryInfo(lowLevel, gson, gid);
if (info != null) {
item.setGalleryInfo(info);
}
}
return item;
}
@NonNull
@Override
public Cursor performGet(@NonNull StorIOSQLite storIOSQLite, @NonNull RawQuery rawQuery) {
lowLevel = storIOSQLite.lowLevel();
return storIOSQLite.lowLevel().rawQuery(rawQuery);
}
@NonNull
@Override
public Cursor performGet(@NonNull StorIOSQLite storIOSQLite, @NonNull Query query) {
lowLevel = storIOSQLite.lowLevel();
return storIOSQLite.lowLevel().query(query);
}
}
/**
* Deletes {@link GalleryInfoContainer} from database.
* The table must contains a column named {@link #COLUMN_GID}
* to store {@link GalleryInfo#gid}.
*/
public static abstract class DeleteResolver<T extends GalleryInfoContainer> extends
com.pushtorefresh.storio.sqlite.operations.delete.DeleteResolver<T> {
private Gson gson;
protected DeleteResolver(@NonNull Gson gson) {
this.gson = gson;
}
/**
* Converts object to {@link DeleteQuery}.
*
* @param object object that should be deleted.
* @return {@link DeleteQuery} that will be performed.
*/
@NonNull
protected abstract DeleteQuery mapToDeleteQuery(@NonNull T object);
@NonNull
@Override
public DeleteResult performDelete(@NonNull StorIOSQLite sql, @NonNull T item) {
final StorIOSQLite.LowLevel lowLevel = sql.lowLevel();
// for data consistency in concurrent environment, encapsulate Put Operation into transaction
lowLevel.beginTransaction();
try {
// Delete GalleryInfo
GalleryInfo info = item.getGalleryInfo();
if (info != null) {
deleteGalleryInfo(lowLevel, gson, info);
}
final DeleteQuery deleteQuery = mapToDeleteQuery(item);
final int numberOfRowsDeleted = lowLevel.delete(deleteQuery);
final DeleteResult deleteResult =
DeleteResult.newInstance(numberOfRowsDeleted, deleteQuery.table());
// everything okay
lowLevel.setTransactionSuccessful();
return deleteResult;
} finally {
// in case of bad situations, db won't be affected
lowLevel.endTransaction();
}
}
}
/**
* The item table use {@link GalleryInfo} as primary key.
*/
public static abstract class UniqueDeleteResolver<T extends GalleryInfoContainer>
extends DeleteResolver<T> {
private String tableName;
protected UniqueDeleteResolver(@NonNull Gson gson, @NonNull String tableName) {
super(gson);
this.tableName = tableName;
}
@NonNull
@Override
protected DeleteQuery mapToDeleteQuery(@NonNull T object) {
GalleryInfo info = object.getGalleryInfo();
return DeleteQuery.builder()
.table(tableName)
.where(COLUMN_GID + " = ?")
.whereArgs(info != null ? info.gid: 0)
.build();
}
}
}
@@ -0,0 +1,163 @@
/*
* 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.database;
/*
* Created by Hippo on 1/15/2017.
*/
import android.annotation.SuppressLint;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A collection of SQLite database create and update commands.
*/
public class MSQLite {
public static final String COLUMN_ID = "_id";
private static Map<Type, String> JAVA_TYPE_TO_SQLITE_TYPE = new HashMap<>();
static {
JAVA_TYPE_TO_SQLITE_TYPE.put(boolean.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(byte.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(short.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(int.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(long.class, "INTEGER NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(float.class, "REAL NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(double.class, "REAL NOT NULL DEFAULT 0");
JAVA_TYPE_TO_SQLITE_TYPE.put(String.class, "TEXT");
}
@SuppressLint("UseSparseArrays")
private Map<Integer, List<Command>> commandsMap = new HashMap<>();
private int version;
private List<Command> commands;
// Only MSQLiteOpenHelper should call it
MSQLite() {}
/**
* Bump database version.
*/
public MSQLite version(int version) {
if (this.version >= version) {
throw new IllegalArgumentException("New version must be bigger than current version. "
+ "current version: " + this.version + ", new version: " + version + ".");
}
this.version = version;
this.commands = new ArrayList<>();
commandsMap.put(this.version, this.commands);
return this;
}
private void checkState() {
if (version == 0) throw new IllegalStateException("Call version() first!");
if (commands == null) throw new IllegalStateException("Call version() first!");
}
static String javaTypeToSQLiteType(Type type) {
String dbType = JAVA_TYPE_TO_SQLITE_TYPE.get(type);
if (dbType == null) throw new IllegalArgumentException("Unknown type. "
+ "Type must be one of " + JAVA_TYPE_TO_SQLITE_TYPE.keySet().toString());
return dbType;
}
/**
* Creates a table.
*/
public MSQLite createTable(String table) {
return command(new StatementCommand(
"CREATE TABLE " + table + " (" + COLUMN_ID + " INTEGER PRIMARY KEY NOT NULL);"));
}
/**
* Creates a table with custom primary key.
*/
public MSQLite createTable(String table, String column, Type type) {
return command(new StatementCommand(
"CREATE TABLE " + table + " (" + column + " " + javaTypeToSQLiteType(type) + " PRIMARY KEY);"));
}
/**
* Drops a table.
*/
public MSQLite dropTable(String table) {
return command(new StatementCommand(
"DROP TABLE " + table + ";"));
}
/**
* Inserts a column to the table.
*/
public MSQLite insertColumn(String table, String column, Type type) {
return command(new StatementCommand(
"ALTER TABLE " + table + " ADD COLUMN " + column + " " + javaTypeToSQLiteType(type) + ";"));
}
/**
* Add a command.
*/
public MSQLite command(@NonNull Command command) {
checkState();
commands.add(command);
return this;
}
@NonNull
List<Command> getCommands(int oldVersion, int newVersion) {
List<Command> result = new ArrayList<>();
for (int i = oldVersion + 1; i <= newVersion; i++) {
List<Command> commands = commandsMap.get(i);
if (commands != null) {
result.addAll(commands);
}
}
return result;
}
/**
* One of commands to create or update {@code SQLiteDatabase}.
*/
public static abstract class Command {
public abstract void run(SQLiteDatabase db);
}
/**
* A {@link Command} to execute a statement.
*/
public static class StatementCommand extends Command {
private String statement;
public StatementCommand(@NonNull String statement) {
this.statement = statement;
}
@Override
public void run(SQLiteDatabase db) {
db.execSQL(statement);
}
}
}
@@ -0,0 +1,123 @@
/*
* 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.database;
/*
* Created by Hippo on 1/15/2017.
*/
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.VisibleForTesting;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
/**
* A {@code MSQLiteOpenHelper} is good at creating and updating database.
*/
// I can't find any library to make SQLiteOpenHelper easier.
// So I create this MSQLiteOpenHelper.
public abstract class MSQLiteOpenHelper extends SQLiteOpenHelper {
private int version;
private MSQLite ms;
public MSQLiteOpenHelper(Context context, String name, int version) {
super(context, name, null, version);
init(version);
}
public MSQLiteOpenHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
init(version);
}
public MSQLiteOpenHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version,
DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
init(version);
}
private void init(int version) {
this.version = version;
this.ms = new MSQLite();
onInit(ms);
}
/**
* Add commands to {@code MSQLite} here.
* <p>
* For example:<br>
* Version 1: table1<br>
* Version 2: table1 table2<br>
* Version 3: table2
* <pre>{@code
* ms.version(1)
* .createTable("table1");
* ms.version(2)
* .createTable("table2");
* ms.version(3)
* .dropTable("table1");
* }</pre>
*/
public abstract void onInit(MSQLite ms);
@Override
public void onCreate(SQLiteDatabase db) {
onUpgrade(db, 0, version);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
List<MSQLite.Command> commands = ms.getCommands(oldVersion, newVersion);
for (MSQLite.Command command: commands) {
command.run(db);
}
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
dropAllTables(db);
onCreate(db);
}
@VisibleForTesting
static void dropAllTables(SQLiteDatabase db) {
List<String> tables = new ArrayList<>();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table';", null);
while (c.moveToNext()) {
String table = c.getString(0);
if (!"android_metadata".equals(table)
&& !"sqlite_sequence".equals(table)
&& !TextUtils.isEmpty(table)) {
tables.add(table);
}
}
c.close();
for (String table: tables) {
db.execSQL("DROP TABLE IF EXISTS " + table + ";");
}
}
}
@@ -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.drawable;
/*
* Created by Hippo on 2/28/2017.
*/
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.graphics.drawable.DrawableWrapper;
import android.view.Gravity;
public class ScaleDrawable extends DrawableWrapper {
private static final float DO_NOT_SCALE = -1.0f;
private float scale = DO_NOT_SCALE;
private int gravity = Gravity.LEFT;
private final Rect tmpRect = new Rect();
public ScaleDrawable(Drawable drawable, int gravity, float scale) {
super(drawable);
this.scale = scale;
this.gravity = gravity;
}
public float getScale() {
return scale;
}
public void setScale(float scale) {
this.scale = scale;
onBoundsChange(getBounds());
}
@Override
protected void onBoundsChange(Rect bounds) {
final Drawable d = getWrappedDrawable();
final Rect r = tmpRect;
int w = bounds.width();
int h = bounds.height();
if (scale >= 0) {
w *= scale;
h *= scale;
}
Gravity.apply(gravity, w, h, bounds, r);
if (w >= 0 && h >= 0) {
d.setBounds(r.left, r.top, r.right, r.bottom);
}
}
}
@@ -0,0 +1,249 @@
/*
* 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.drawable;
/*
* Created by Hippo on 3/31/2017.
*/
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.FloatRange;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.hippo.yorozuya.StringUtils;
public class TextDrawable extends Drawable {
private TextState state;
private Paint backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private float x;
private float y;
private boolean textSizeDirty = true;
private boolean mutated;
public TextDrawable(String text, @FloatRange(from = 0.0f, to = 1.0f) float contentPercent) {
state = new TextState(text != null ? text : StringUtils.EMPTY, contentPercent);
}
/**
* Gets the drawable's text color value.
*/
public int getTextColor() {
return state.textColor;
}
/**
* Sets the drawable's text color value.
*/
public void setTextColor(int color) {
if (state.textColor != color) {
state.textColor = color;
invalidateSelf();
}
}
/**
* Gets the drawable's background color value.
*/
public int getBackgroundColor() {
return state.backgroundColor;
}
/**
* Sets the drawable's background color value.
*/
public void setBackgroundColor(int color) {
if (state.backgroundColor != color) {
state.backgroundColor = color;
invalidateSelf();
}
}
/**
* Gets the drawable's alpha value.
*/
@Override
public int getAlpha() {
return state.alpha;
}
/**
* Sets the drawable's background color value.
*/
@Override
public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
if (state.alpha != alpha) {
state.alpha = alpha;
invalidateSelf();
}
}
/**
* Sets the color filter applied to this color.
* <p>
* Only supported on version {@link android.os.Build.VERSION_CODES#LOLLIPOP} and
* above. Calling this method has no effect on earlier versions.
*
* @see android.graphics.drawable.Drawable#setColorFilter(ColorFilter)
*/
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
backgroundPaint.setColorFilter(colorFilter);
textPaint.setColorFilter(colorFilter);
invalidateSelf();
}
/**
* Gets the drawable's content percent value.
*/
public float getContentPercent() {
return state.contentPercent;
}
/**
* Gets the drawable's text value.
*/
public String getText() {
return state.text;
}
@NonNull
@Override
public ConstantState getConstantState() {
return state;
}
@Override
public int getOpacity() {
return getAlpha() != 0 ? PixelFormat.TRANSLUCENT : PixelFormat.TRANSPARENT;
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
textSizeDirty = true;
}
@Override
public void draw(@NonNull Canvas canvas) {
if (!getBounds().isEmpty() && getAlpha() != 0) {
// Draw background
backgroundPaint.setColor(state.backgroundColor);
backgroundPaint.setAlpha(state.alpha);
canvas.drawRect(getBounds(), backgroundPaint);
if (!TextUtils.isEmpty(state.text)) {
// Draw text
updateTextSizeIfDirty();
textPaint.setColor(state.textColor);
textPaint.setAlpha(state.alpha);
canvas.drawText(state.text, x, y, textPaint);
}
}
}
private void updateTextSizeIfDirty() {
if (!textSizeDirty) {
return;
}
textSizeDirty = false;
Rect bounds = getBounds();
int contentWidth = (int) (bounds.width() * state.contentPercent);
int contentHeight = (int) (bounds.height() * state.contentPercent);
float widthRatio = (float) contentWidth / state.textBounds.width();
float heightRatio = (float) contentHeight / state.textBounds.height();
float ratio = Math.min(widthRatio, heightRatio);
float textSize = TextState.STANDARD_TEXT_SIZE * ratio;
textPaint.setTextSize(textSize);
x = (bounds.width() - state.textBounds.width() * ratio) / 2 - state.textBounds.left * ratio;
y = (bounds.height() - state.textBounds.height() * ratio) / 2 - state.textBounds.top * ratio;
}
@NonNull
@Override
public Drawable mutate() {
if (!mutated && super.mutate() == this) {
state = new TextState(state);
mutated = true;
}
return this;
}
final static class TextState extends ConstantState {
private static final float STANDARD_TEXT_SIZE = 1000.0f;
private static final Paint STANDARD_PAINT;
static {
STANDARD_PAINT = new Paint();
STANDARD_PAINT.setTextSize(STANDARD_TEXT_SIZE);
}
private int textColor;
private int backgroundColor;
private int alpha;
private float contentPercent;
private String text;
/**
* 100.0f text size bounds
*/
private Rect textBounds;
TextState(String text, float contentPercent) {
this.text = text;
this.contentPercent = contentPercent;
this.textBounds = new Rect();
STANDARD_PAINT.getTextBounds(text, 0, text.length(), this.textBounds);
}
TextState(TextState state) {
textColor = state.textColor;
backgroundColor = state.backgroundColor;
alpha = state.alpha;
contentPercent = state.contentPercent;
text = state.text;
textBounds = state.textBounds;
}
@NonNull
@Override
public Drawable newDrawable() {
return new TextDrawable(this);
}
@Override
public int getChangingConfigurations() {
return 0;
}
}
private TextDrawable(TextState state) {
this.state = state;
}
}
@@ -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.network;
/*
* Created by Hippo on 2/12/2017.
*/
import android.support.annotation.Nullable;
import android.util.Log;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import okhttp3.Dns;
public abstract class ByteDns implements Dns {
private static final String LOG_TAG = ByteDns.class.getSimpleName();
@Nullable
public abstract byte[] address(String host);
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
byte[] addr = address(hostname);
if (addr != null) {
try {
InetAddress ia = InetAddress.getByAddress(hostname, addr);
return Collections.singletonList(ia);
} catch (UnknownHostException e) {
Log.e(LOG_TAG, "Bad byte address: " + Arrays.toString(addr));
}
}
return Arrays.asList(InetAddress.getAllByName(hostname));
}
}
@@ -0,0 +1,274 @@
/*
* 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.network;
/*
* Created by Hippo on 1/15/2017.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.support.annotation.Nullable;
import android.util.Log;
import com.hippo.ehviewer.database.MSQLite;
import com.hippo.ehviewer.database.MSQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import okhttp3.Cookie;
class CookieDatabase {
private static final String LOG_TAG = CookieDatabase.class.getSimpleName();
private static Map<String, Integer> columnIndexMap = new ConcurrentHashMap<>();
private OpenHelper helper;
private SQLiteDatabase db;
private Map<Cookie, Long> cookieIdMap = new HashMap<>();
private AtomicBoolean getAllCookiesCalled = new AtomicBoolean();
public CookieDatabase(Context context, String name) {
helper = new OpenHelper(context, name);
db = helper.getWritableDatabase();
}
// It is safe to cache column index to a thread-safe map,
// because the database schema can't change during app runtime.
private static int getColumnIndex(Cursor cursor, String column) {
Integer index = columnIndexMap.get(column);
if (index != null) return index;
index = cursor.getColumnIndexOrThrow(column);
columnIndexMap.put(column, index);
return index;
}
private static String getString(Cursor cursor, String column) {
return cursor.getString(getColumnIndex(cursor, column));
}
private static long getLong(Cursor cursor, String column) {
return cursor.getLong(getColumnIndex(cursor, column));
}
private static boolean getBoolean(Cursor cursor, String column) {
return cursor.getInt(getColumnIndex(cursor, column)) != 0;
}
// Return valid and not expired cookie or null
@Nullable
private static Cookie parse(Cursor cursor, long currentTimeMillis) {
try {
String name = getString(cursor, OpenHelper.COLUMN_NAME);
String value = getString(cursor, OpenHelper.COLUMN_VALUE);
long expiresAt = getLong(cursor, OpenHelper.COLUMN_EXPIRES_AT);
String domain = getString(cursor, OpenHelper.COLUMN_DOMAIN);
String path = getString(cursor, OpenHelper.COLUMN_PATH);
boolean secure = getBoolean(cursor, OpenHelper.COLUMN_SECURE);
boolean httpOnly = getBoolean(cursor, OpenHelper.COLUMN_HTTP_ONLY);
boolean persistent = getBoolean(cursor, OpenHelper.COLUMN_PERSISTENT);
boolean hostOnly = getBoolean(cursor, OpenHelper.COLUMN_HOST_ONLY);
// Check non-persistent or expired
if (!persistent || expiresAt <= currentTimeMillis) {
return null;
}
Cookie.Builder builder = new Cookie.Builder();
builder.name(name);
builder.value(value);
if (hostOnly) {
builder.hostOnlyDomain(domain);
} else {
builder.domain(domain);
}
builder.path(path);
builder.expiresAt(expiresAt);
if (secure) builder.secure();
if (httpOnly) builder.httpOnly();
return builder.build();
} catch (Throwable e) {
Log.e(LOG_TAG, "Can't parse a cookie in database", e);
return null;
}
}
// Return a domain-cookies map
public Map<String, CookieSet> getAllCookies() {
if (!getAllCookiesCalled.compareAndSet(false, true)) {
throw new IllegalStateException("Only call getAllCookies() once.");
}
long now = System.currentTimeMillis();
Map<String, CookieSet> map = new HashMap<>();
List<Long> toRemove = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + OpenHelper.TABLE_COOKIE + ";", null);
while (cursor.moveToNext()) {
long id = getLong(cursor, MSQLite.COLUMN_ID);
Cookie cookie = parse(cursor, now);
if (cookie == null) {
toRemove.add(id);
continue;
}
// Save id of the cookie in db
cookieIdMap.put(cookie, id);
CookieSet set = map.get(cookie.domain());
if (set == null) {
set = new CookieSet();
map.put(cookie.domain(), set);
}
set.add(cookie);
}
cursor.close();
// Remove invalid or expired cookie
if (!toRemove.isEmpty()) {
SQLiteStatement statement = db.compileStatement(
"DELETE FROM " + OpenHelper.TABLE_COOKIE + " WHERE " + MSQLite.COLUMN_ID + " = ?;");
db.beginTransaction();
try {
for (long id: toRemove) {
statement.bindLong(1, id);
statement.executeUpdateDelete();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
statement.close();
}
return map;
}
private static ContentValues getCookieContentValues(Cookie cookie) {
ContentValues values = new ContentValues();
values.put(OpenHelper.COLUMN_NAME, cookie.name());
values.put(OpenHelper.COLUMN_VALUE, cookie.value());
values.put(OpenHelper.COLUMN_EXPIRES_AT, cookie.expiresAt());
values.put(OpenHelper.COLUMN_DOMAIN, cookie.domain());
values.put(OpenHelper.COLUMN_PATH, cookie.path());
values.put(OpenHelper.COLUMN_SECURE, cookie.secure());
values.put(OpenHelper.COLUMN_HTTP_ONLY, cookie.httpOnly());
values.put(OpenHelper.COLUMN_PERSISTENT, cookie.persistent());
values.put(OpenHelper.COLUMN_HOST_ONLY, cookie.hostOnly());
return values;
}
public void add(Cookie cookie) {
long id = db.insert(OpenHelper.TABLE_COOKIE, null, getCookieContentValues(cookie));
if (id != -1) {
Long oldId = cookieIdMap.put(cookie, id);
if (oldId != null) Log.e(LOG_TAG, "Add a duplicate cookie");
} else {
Log.e(LOG_TAG, "An error occurred when insert a cookie");
}
}
public void update(Cookie from, Cookie to) {
Long id = cookieIdMap.get(from);
if (id == null) {
Log.e(LOG_TAG, "Can't get id when update the cookie");
return;
}
ContentValues values = getCookieContentValues(to);
String whereClause = MSQLite.COLUMN_ID + " = ?";
String[] whereArgs = new String[] { Long.toString(id) };
int count = db.update(OpenHelper.TABLE_COOKIE, values, whereClause, whereArgs);
if (count != 1) Log.e(LOG_TAG, "Bad result when update cookie: " + count);
// Update it in cookie-id map
cookieIdMap.remove(from);
cookieIdMap.put(to, id);
}
public void remove(Cookie cookie) {
Long id = cookieIdMap.get(cookie);
if (id == null) {
Log.e(LOG_TAG, "Can't get id when remove the cookie");
return;
}
String whereClause = MSQLite.COLUMN_ID + " = ?";
String[] whereArgs = new String[] { Long.toString(id) };
int count = db.delete(OpenHelper.TABLE_COOKIE, whereClause, whereArgs);
if (count != 1) Log.e(LOG_TAG, "Bad result when remove cookie: " + count);
// Remove it from cookie-id map
cookieIdMap.remove(cookie);
}
public void clear() {
db.delete(OpenHelper.TABLE_COOKIE, null, null);
cookieIdMap.clear();
}
public void close() {
db.close();
helper.close();
}
private static class OpenHelper extends MSQLiteOpenHelper {
private static int VERSION_1 = 1;
private static String TABLE_COOKIE = "OK_HTTP_3_COOKIE";
private static String COLUMN_NAME = "NAME";
private static String COLUMN_VALUE = "VALUE";
private static String COLUMN_EXPIRES_AT = "EXPIRES_AT";
private static String COLUMN_DOMAIN = "DOMAIN";
private static String COLUMN_PATH = "PATH";
private static String COLUMN_SECURE = "SECURE";
private static String COLUMN_HTTP_ONLY = "HTTP_ONLY";
private static String COLUMN_PERSISTENT = "PERSISTENT";
private static String COLUMN_HOST_ONLY = "HOST_ONLY";
private static int VERSION_CURRENT = VERSION_1;
public OpenHelper(Context context, String name) {
super(context, name, VERSION_CURRENT);
}
@Override
public void onInit(MSQLite ms) {
ms.version(1)
.createTable(TABLE_COOKIE)
.insertColumn(TABLE_COOKIE, COLUMN_NAME, String.class)
.insertColumn(TABLE_COOKIE, COLUMN_VALUE, String.class)
.insertColumn(TABLE_COOKIE, COLUMN_EXPIRES_AT, long.class)
.insertColumn(TABLE_COOKIE, COLUMN_DOMAIN, String.class)
.insertColumn(TABLE_COOKIE, COLUMN_PATH, String.class)
.insertColumn(TABLE_COOKIE, COLUMN_SECURE, boolean.class)
.insertColumn(TABLE_COOKIE, COLUMN_HTTP_ONLY, boolean.class)
.insertColumn(TABLE_COOKIE, COLUMN_PERSISTENT, boolean.class)
.insertColumn(TABLE_COOKIE, COLUMN_HOST_ONLY, boolean.class);
}
}
}
@@ -0,0 +1,195 @@
/*
* 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.network;
/*
* Created by Hippo on 1/15/2017.
*/
import static okhttp3.internal.Util.verifyAsIpAddress;
import android.content.Context;
import android.support.annotation.VisibleForTesting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
/**
* A Persistent {@code CookieJar} which store cookies to database.
*/
public class CookieRepository implements CookieJar {
private static final Comparator<Cookie> COOKIE_COMPARATOR =
(o1, o2) -> o2.path().length() - o1.path().length();
private final CookieDatabase db;
private final Map<String, CookieSet> map;
public CookieRepository(Context context, String dbName) {
db = new CookieDatabase(context, dbName);
map = db.getAllCookies();
}
@VisibleForTesting
Map<String, CookieSet> getCookieSetMap() {
return map;
}
private synchronized void addCookie(Cookie cookie) {
// For cookie database
Cookie toAdd = null;
Cookie toUpdate = null;
Cookie toRemove = null;
CookieSet set = map.get(cookie.domain());
if (set == null) {
set = new CookieSet();
map.put(cookie.domain(), set);
}
if (cookie.expiresAt() <= System.currentTimeMillis()) {
toRemove = set.remove(cookie);
// If the cookie is not persistent, it's not in database
if (toRemove != null && !toRemove.persistent()) {
toRemove = null;
}
} else {
toAdd = cookie;
toUpdate = set.add(cookie);
// If the cookie is not persistent, it's not in database
if (!toAdd.persistent()) toAdd = null;
if (toUpdate != null && !toUpdate.persistent()) toUpdate = null;
// Remove the cookie if it updates to null
if (toAdd == null && toUpdate != null) {
toRemove = toUpdate;
toUpdate = null;
}
}
if (toRemove != null) {
db.remove(toRemove);
}
if (toAdd != null) {
if (toUpdate != null) {
db.update(toUpdate, toAdd);
} else {
db.add(toAdd);
}
}
}
// okhttp3.Cookie.domainMatch(HttpUrl, String)
private static boolean domainMatch(HttpUrl url, String domain) {
String urlHost = url.host();
if (urlHost.equals(domain)) {
return true; // As in 'example.com' matching 'example.com'.
}
if (urlHost.endsWith(domain)
&& urlHost.charAt(urlHost.length() - domain.length() - 1) == '.'
&& !verifyAsIpAddress(urlHost)) {
return true; // As in 'example.com' matching 'www.example.com'.
}
return false;
}
private synchronized List<Cookie> getCookies(HttpUrl url) {
List<Cookie> accepted = new ArrayList<>();
List<Cookie> expired = new ArrayList<>();
for (Map.Entry<String, CookieSet> entry: map.entrySet()) {
if (domainMatch(url, entry.getKey())) {
entry.getValue().get(url, accepted, expired);
}
}
for (Cookie cookie: expired) {
if (cookie.persistent()) {
db.remove(cookie);
}
}
// RFC 6265 Section-5.4 step 2, sort the cookie-list
// Cookies with longer paths are listed before cookies with shorter paths.
// Ignore creation-time, we don't store them.
Collections.sort(accepted, COOKIE_COMPARATOR);
return accepted;
}
/**
* Remove all cookies in this {@code CookieRepository}.
*/
public synchronized void clear() {
map.clear();
db.clear();
}
/**
* Logcat all cookies
*/
public synchronized void logcat() {
for (Map.Entry<String, CookieSet> entry: map.entrySet()) {
entry.getValue().logcat();
}
}
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
for (Cookie cookie: cookies) {
if (PublicSuffix.isPublicSuffix(cookie.domain())) {
// RFC 6265 Section-5.3, step 5 and step 6
// If the domain of the cookie is a public suffix
// and is identical to the canonicalized request-host,
// set the cookie's host-only-flag to true,
// otherwise ignore the cookie entirely.
if (cookie.domain().equals(url.host())) {
if (!cookie.hostOnly()) {
Cookie.Builder builder = new Cookie.Builder();
builder.name(cookie.name());
builder.value(cookie.value());
builder.hostOnlyDomain(cookie.domain());
builder.path(cookie.path());
if (cookie.persistent()) builder.expiresAt(cookie.expiresAt());
if (cookie.secure()) builder.secure();
if (cookie.httpOnly()) builder.httpOnly();
cookie = builder.build();
}
} else {
continue;
}
}
addCookie(cookie);
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
return getCookies(url);
}
public void close() {
db.close();
}
}
Loaded 100 of 351 files, more files were not shown because too many files have changed in this diff. Show more