Compare commits

...
Author SHA1 Message Date
gdlbo 8d41d423f8 fix close dialog 2024-03-03 14:01:46 +03:00
gdlbo 37a4ba4462 rewritten ContactsSyncAcitvity 2024-03-03 13:33:36 +03:00
gdlbo 7fba308f99 rewritten ContactsSyncReporter 2024-03-03 12:55:27 +03:00
gdlbo 5ef2f2f6cd rewritten ContactsSyncUtils 2024-03-03 12:51:31 +03:00
gdlbo 522f6cd42b removed useless cache buttons 2024-03-03 09:53:02 +03:00
gdlbo 7dd9e5ff3a more gzip support 2024-03-02 23:33:18 +03:00
Artur Skubei 07f8542f56 SponsorPost vote system (#1562)
also added gzip support for all methods
2024-03-02 22:24:15 +03:00
Artur Skubei 6b1e6f07c5 Internal VK Proxy Support (#1579)
thanks @awers24 for tests
2024-03-02 21:47:34 +03:00
gdlbo 5466dd72dd some lastfm fixes 2024-03-01 22:50:31 +03:00
Artur Skubei 5ac3b9cf6e Another ndk fix (#1572) 2024-02-25 22:07:42 +03:00
Artur Skubei de6edc795a Update build.yml 2024-02-25 21:46:27 +03:00
Artur Skubei 19d36272cb ndk fix (#1571) 2024-02-25 21:43:08 +03:00
gdlbo d2fe435ad2 added music fragment
migration from media content
2024-02-25 19:47:23 +03:00
gdlbo b6e7d24979 Update VTVerifications.java 2024-02-20 11:48:35 +03:00
gdlbo d10d5eca4b fixed auto updating filters 2024-02-19 15:39:41 +03:00
gdlbo 67f1477907 Revert "improve code readability, remove redundant constructions"
This reverts commit b05a239b90.
2024-02-19 11:38:11 +03:00
gdlbo 18ef4eda21 Revert "rollback to for-loops with improvements"
This reverts commit 84cf9ba10a.
2024-02-19 11:38:10 +03:00
Tahgolov 84cf9ba10a rollback to for-loops with improvements 2024-02-18 23:07:19 +03:00
Tahgolov b05a239b90 improve code readability, remove redundant constructions 2024-02-18 23:05:31 +03:00
gdlbo 8959558c64 Fixed 5.1 false coloring and improved coloring speed/app performance (#1566) 2024-02-18 14:52:22 +03:00
gdlbo e19ed8845d fix #1343 2024-02-18 02:08:16 +03:00
gdlbo b5ae2662db fix noad 2024-02-17 22:27:56 +03:00
gdlbo d4710663ff disabler force traffic saver v2 2024-02-16 03:58:30 +03:00
gdlbo 18f40e0da9 fixed useless false visibility vkZ
ofc jk (vkx)
2024-02-14 23:12:20 +03:00
gdlbo 9ff8c1d9fe refactored FoafBase
added check for vk messenger accounts
rewritten all legacy code
2024-02-14 23:03:19 +03:00
gdlbo 91440e4f8b refactored VTVerifs
speedup processIds + removed getting 1337 verifs (depreciated)
2024-02-14 22:13:22 +03:00
gdlbo a195e05d7b refactored sig checker
support for new android versions
2024-02-14 22:10:59 +03:00
gdlbo 8866bf90c7 refactored webview injector
speedup by runtime injection evaluateJavascript
2024-02-14 22:10:33 +03:00
gdlbo eab5b7074e refactored superapp utils
removed old vk pay and events
2024-02-14 21:45:31 +03:00
gdlbo bdee6c08c0 disable events in superapp 2024-02-14 21:16:41 +03:00
gdlbo 0744613aa0 Update preferences_debug.xml 2024-02-14 19:31:02 +03:00
gdlbo f6de4c5bc9 some toggles fixes
probably may fixed slow messages load
fixed default feed
2024-02-14 19:11:16 +03:00
gdlbo f59e93aab6 fix #1551 2024-02-14 19:03:23 +03:00
gdlbo 2d97341886 video-covers disabler 2024-02-14 17:53:05 +03:00
gdlbo b247c5c090 some config network fixes 2024-02-14 17:06:35 +03:00
gdlbo fd6e866f6f fixed bug nonmilk
Reported by https://4pda.to/forum/index.php?showuser=1502902
2024-02-14 16:45:45 +03:00
gdlbo 780ebce3ff disable libverify by default
2fa fix
2024-02-12 12:31:06 +03:00
gdlbo 2a85b3a4f0 fixes for whitelists 2024-02-09 15:41:18 +03:00
gdlbo 413701d28e SponsorPost summ 2024-02-07 16:40:54 +03:00
gdlbo 016bd342c4 added summary for sponsorpost 2024-02-07 16:33:54 +03:00
gdlbo d04b2249f0 enable metadata by default 2024-02-07 16:07:59 +03:00
gdlbo 8eb7ded6ba fixed autoupdate filters 2024-02-07 15:49:04 +03:00
gdlbo 1f9c6fd80c added disabling sponsorpost 2024-02-07 15:47:05 +03:00
gdlbo 4ec84e3754 cleanup build gradle 2024-02-07 14:58:06 +03:00
gdlbo ad3f70f4ac Sponsorpost integration (#1553) 2024-02-07 13:55:53 +03:00
gdlbo 611f4d3159 updated run configs 2024-02-06 18:37:30 +03:00
mexanoz 7319714140 fix setting metadata for certain tracks (#1507) 2024-02-04 15:10:34 +03:00
gdlbo 857db4879a vkui theming fixes
thx @awers24
2024-02-02 14:27:35 +03:00
gdlbo b5db820733 new feature
useless
2024-02-01 23:40:10 +03:00
gdlbo c668105003 some translations update 2024-01-31 11:46:46 +03:00
gdlbo dd6bbcbc2c fix auto translation 2024-01-31 11:42:07 +03:00
gdlbo 4ed0749027 Revert "Profiles/Groups resp fixes (#1532)"
This reverts commit a6b56e0e87.
2024-01-31 03:22:06 +03:00
gdlbo 3b834c2688 Update Genius.java 2024-01-31 01:56:10 +03:00
gdlbo 0c5a40bedc enable stories 2024-01-31 00:46:57 +03:00
gdlbo 8146b863b1 fix crash 2024-01-30 12:21:53 +03:00
gdlbo c64f8a1b2d disabler force traffic saver 2024-01-30 11:47:08 +03:00
gdlbo dd6916c08a removed random proxy 2024-01-30 11:35:49 +03:00
gdlbo 58c14fbd4f added all server features disabler for users who doesnt have unlimited internet 2024-01-30 11:28:38 +03:00
gdlbo 3b830f5e2e added fragile user data pref 2024-01-30 11:08:19 +03:00
gdlbo c304313be9 updated deps 2024-01-13 19:14:51 +03:00
Denis 3068ff76c1 Fix crash (#1542) 2023-12-31 13:04:55 +03:00
gdlbo a6b56e0e87 Profiles/Groups resp fixes (#1532) 2023-12-13 23:08:32 +03:00
gdlbo 5360ca6c5e updated translations 2023-12-13 23:07:40 +03:00
gdlbo f2ac845797 Update FFMpeg.java 2023-10-14 16:05:51 +03:00
gdlbo a85e55a594 meta data pref 2023-10-12 22:45:43 +03:00
gdlbo e2775db4e5 fixed english translation 2023-10-12 20:19:17 +03:00
gdlbo 589e8928a0 Bitrate upgrade (#1498)
libvkmedia.so armv7/arm64
2023-10-12 19:57:00 +03:00
gdlbo cd189b1dda fixed id3v2 meta 2023-10-10 23:15:11 +03:00
gdlbo 14c111a3e6 some music fixes 2023-10-10 22:53:16 +03:00
gdlbo b506c56346 fixed compiling issue 2023-10-07 03:13:24 +03:00
gdlbo bbbc94e510 added facebook graph disabler 2023-10-07 03:07:31 +03:00
gdlbo 8cb2c380e7 fixed adding "null" to track name 2023-10-06 12:44:55 +03:00
gdlbo b9879f9ed7 updated appcenter 2023-10-04 19:44:24 +03:00
gdlbo cf05e051e8 added summary for advanced online info 2023-10-04 13:47:47 +03:00
gdlbo 963c4d81ba upped ver 2023-10-04 13:37:20 +03:00
gdlbo 099c699702 added vkn online fix disabler 2023-10-04 13:37:07 +03:00
gdlbo 1117fc19d4 added force tablet mode 2023-10-02 16:28:08 +03:00
gdlbo 78dca26063 fix #1489 2023-10-02 14:52:52 +03:00
gdlbo f5180f61d5 fixed empty text from ssfs 2023-09-30 14:37:49 +03:00
gdlbo 540fffdcc9 fixed download issue 2023-09-30 03:15:14 +03:00
gdlbo 5357c60eaa Update TelegramStickersGrabber.java 2023-09-30 02:33:52 +03:00
gdlbo c59f29121f Refactoted Telegram Stickers downloader and settings (#1485) 2023-09-29 19:58:33 +03:00
gdlbo bd38cab377 autoupdated disabler 2023-09-28 17:40:49 +03:00
gdlbo 0058431590 deleted useless summ and updated translation 2023-09-28 17:01:38 +03:00
gdlbo bf4cf2be53 adfree + free from server connection (#1481) 2023-09-28 16:10:30 +03:00
gdlbo aac86a9952 Update InstallGMSFragment.java
added inotia00 microg information
2023-09-28 11:09:40 +03:00
gdlbo ae00e72bac added more microg instructions 2023-09-27 23:55:56 +03:00
gdlbo fea984f6fd fixed null foaf crash app 2023-09-27 23:34:37 +03:00
gdlbo d870c2f984 Update VTSettings.java 2023-09-27 22:12:12 +03:00
gdlbo f7f43928cf cleanup and refactor code
also fixed ts merging
2023-09-25 14:44:27 +03:00
Vologhat 1accb45f12 Merge remote-tracking branch 'origin/main' 2023-09-24 18:43:40 +03:00
Vologhat d9f53920e5 optimize music cache logic 2023-09-24 18:39:12 +03:00
gdlbo 76d91332d7 added recommendation icons 2023-09-23 16:04:45 +03:00
gdlbo 728cbde683 added xiaomi battery dozing information 2023-09-23 14:58:13 +03:00
gdlbo 60c98cd998 some settings improves 2023-09-23 14:50:18 +03:00
gdlbo f1d106e0f0 added gms info in device info
installed microg/gms and push service
2023-09-23 11:17:43 +03:00
gdlbo c92194e90b app.revanced.android.gms support (#1474) 2023-09-23 10:53:05 +03:00
gdlbo 91683af807 deleted useless file 2023-09-23 01:50:43 +03:00
gdlbo c5c898aa4e added recommendations for app fixes + added more gmsless instructions 2023-09-23 01:22:13 +03:00
gdlbo 25634b2469 cache info/clean improvements 2023-09-22 23:27:08 +03:00
gdlbo b8e764d09d Update AboutAppFragment.smali 2023-09-15 19:31:09 +03:00
gdlbo 17ed32857a fixed information about cache settings 2023-09-15 19:05:34 +03:00
gdlbo d631d07e0f removed useless update toast 2023-09-15 19:03:14 +03:00
gdlbo 2ec4c69832 added "Data and storage" item to settings 2023-09-15 18:40:38 +03:00
abslike 6426c965c6 Fix button black text in bots 2023-09-15 18:38:27 +03:00
gdlbo 4f6d410185 stories disabled by default 2023-09-15 18:09:29 +03:00
gdlbo 18a899f439 updated and refactored vt settings 2023-09-15 18:08:28 +03:00
gdlbo 7e5b3fe233 superapp audio item fix 2023-09-14 12:08:16 +03:00
gdlbo 4abd0eec6c fix compile 2023-09-14 11:28:08 +03:00
gdlbo cf17ed64c7 fixed invert in cached playlist 2023-07-30 16:49:30 +03:00
gdlbo a2dd7c1e06 fixed strange code 2023-07-29 17:06:12 +03:00
gdlbo 021fe66bec invert cached tracks list 2023-07-29 16:48:30 +03:00
gdlbo 1b3896f4ca fix colors issue 2023-07-28 19:01:57 +03:00
gdlbo fc9ccf66d1 fix #1409 2023-07-28 18:49:11 +03:00
Vologhat d205f2894b rewrite StickersFragment.java
- move add tgs action to toolbar
- some optimizations
2023-07-14 12:53:57 +03:00
Vologhat 7afc04b2b2 fix tgs packs download 2023-07-14 12:48:45 +03:00
Vologhat 584ee96ee0 fix #1406 2023-07-14 12:37:50 +03:00
gdlbo 66f7ea1b79 Update VTVerifications.java 2023-07-11 21:47:53 +03:00
gdlbo 7b0a83458b Update README.md 2023-07-08 18:03:41 +03:00
gdlbo cdaf7909d4 fix old android crash accenting 2023-07-04 23:23:18 +03:00
gdlbo c70ab388c1 fixed account saving 2023-07-04 22:55:22 +03:00
gdlbo 50c66c2703 fix music metrics 2023-07-04 19:56:12 +03:00
gdlbo 357e520bb0 some code fixes 2023-07-04 18:57:06 +03:00
gdlbo 6379ce5741 cleanup code 2023-07-04 13:42:04 +03:00
Vologhat 02807739a1 fix #1394 2023-07-02 22:32:26 +03:00
gdlbo 40635ab75a fix #1388 2023-07-02 13:44:47 +03:00
gdlbo 32e1bfe6fd fix messages color accent 2023-07-02 00:04:10 +03:00
gdlbo 281a0e8499 updated translations 2023-07-01 18:45:45 +03:00
gdlbo 220c61afe1 Update preferences_themes.xml 2023-07-01 18:33:46 +03:00
Vologhat 7a632d5224 Update preferences_themes.xml 2023-07-01 18:31:23 +03:00
Vologhat 3218c1a46b add optionally theme cache invalidation every update 2023-07-01 18:29:47 +03:00
Vologhat b2028d86ba add optionally theme cache invalidation every update 2023-07-01 18:24:42 +03:00
gdlbo 45ed5879e6 Update build.gradle 2023-07-01 17:46:06 +03:00
gdlbo 48479dd064 removed old color engine prefs 2023-07-01 17:33:45 +03:00
gdlbo 3b556b81a1 Update StandartFilter.txt 2023-07-01 17:33:05 +03:00
gdlbo 526c9a607a auto refactor imports 2023-07-01 16:42:33 +03:00
Vologhat 81752895ab Revert "auto refactor code"
This reverts commit ad970d097a.
2023-07-01 16:39:36 +03:00
gdlbo ad970d097a auto refactor code 2023-07-01 16:38:42 +03:00
gdlbo bc2010b49d gradle downgrade 2023-07-01 16:34:27 +03:00
Vologhat ff4a4094ff add type validating of resource value 2023-07-01 16:15:20 +03:00
abslike 3629e71098 Update monet dark and amoled theme (nomilkshake) (#1378) 2023-06-27 22:21:45 +03:00
Vologhat b955ac355f fix #1386 2023-06-27 22:17:43 +03:00
Vologhat 409279eca0 fix apk path building 2023-06-27 17:32:28 +03:00
Vologhat ea0a0f1d93 Optimize build scripts
- rewrite the"exportDex" task group
- move  the logic of deleting temporary files into a gradle script
- fix "APPCENTER_KEY" property defining while debug building
2023-06-27 16:42:07 +03:00
gdlbo 3cc81dfddc fix #1376 2023-06-19 05:06:22 +03:00
gdlbo 86041e6031 invert exceptions filters 2023-06-19 01:40:22 +03:00
gdlbo e140ce2661 fixed monet msg colors 2023-06-19 00:46:27 +03:00
gdlbo f6f15132a2 Update build.yml 2023-06-18 18:35:53 +03:00
gdlbo e73751ecf3 Update build.yml 2023-06-18 18:26:12 +03:00
gdlbo 3c0516b4cd cleanup ThemesUtils.java 2023-06-18 18:20:48 +03:00
gdlbo 38d9f4a818 update gradle 2023-06-18 18:20:25 +03:00
gdlbo 207fa4f2e7 fixed memories vkui 2023-06-18 02:38:39 +03:00
abslikeandabslike f9f778b8f4 Updating light nonmilkshake theme (#1374)
Co-authored-by: abslike <abslike@vk.com>
2023-06-17 21:46:13 +03:00
gdlbo 962dcdec67 fixed search engine issue 2023-06-16 22:45:02 +03:00
gdlbo 486026b8aa updated translations 2023-06-14 17:36:34 +03:00
gdlbo e78d08fb94 added frag title for data sett 2023-06-12 16:32:47 +03:00
gdlbo a5e81dbd87 some data sett updated 2023-06-12 16:30:22 +03:00
gdlbo 49051dae9a added filtered buttons for profile #767 2023-06-12 15:28:37 +03:00
gdlbo 94236c87e3 fix incorrect sig 2023-06-10 20:32:06 +03:00
gdlbo 449ba8c768 cleanup NewsFeedFiltersUtils.java 2023-06-10 20:08:28 +03:00
gdlbo 0da81c01e9 fixed monet theme applying 2023-06-10 20:08:13 +03:00
gdlbo b4a0b7e1ea Fixed false filtering of users' own messages 2023-06-10 18:06:13 +03:00
abslikeandabslike f2209eca49 Updating Light and Dark milkshake monet theme (#1359)
Co-authored-by: abslike <abslike@vk.com>
2023-06-10 15:08:13 +03:00
gdlbo 4a004971c6 Update CatalogJsonInjector.java 2023-05-30 19:25:30 +03:00
gdlbo e400b8761c fixed false injection cache playlist in old audio catalog 2023-05-30 17:17:59 +03:00
Vologhat ff8e7b7f41 fix incorrect displaying of selected image searcher 2023-05-30 12:31:21 +03:00
gdlbo 2c501606be amoled vkui issues fix 2023-05-28 18:02:09 +03:00
gdlbo 73420fe1c4 updated vkui injection for new versions 2023-05-28 15:50:11 +03:00
Vologhat 337f81346c replace microsoft icon to bing icon 2023-05-27 20:13:04 +03:00
Vologhat 06f9a4545b added sauceNAO and trace.moe icons 2023-05-27 14:36:09 +03:00
gdlbo fa99df93c4 refactoring some code 2023-05-26 21:03:23 +03:00
Vologhat adcd2472d5 rewrite and fix PhotoViewer hook
- optimize code
- create SearchEngine enum for image searchers
- fix "search photo" on non-monet theme
- fix icon colors in photo viewer context menu
2023-05-26 16:46:43 +03:00
gdlbo 7527b9a07e added update button for all non-dev users 2023-05-26 14:47:49 +03:00
gdlbo 800c223baa fixed dropdown monet icons in menu 2023-05-26 14:37:06 +03:00
gdlbo d1123d3ccf Update MediaNative.java 2023-05-25 23:18:15 +03:00
gdlbo f61fc99d9c Revert "upgraded voice bitrate"
This reverts commit 64303b1709.
2023-05-25 23:04:09 +03:00
gdlbo 60653cc739 medianative converted to java 2023-05-25 23:03:00 +03:00
gdlbo d25bba10b0 fixed profiles crash 2023-05-25 17:06:48 +03:00
gdlbo 3b67ecaa5e deleted voip libs
-10 mb
2023-05-25 17:06:29 +03:00
gdlbo 6600f32392 some settings update 2023-05-25 16:48:04 +03:00
gdlbo 64303b1709 upgraded voice bitrate
opus_encoder_ctl

16000 -> 48000
2023-05-24 20:34:57 +03:00
gdlbo 5c7e50d61e delete pin fix
good fix
2023-05-24 15:18:39 +03:00
gdlbo f68ad105a6 Update Preferences.java 2023-05-24 01:32:02 +03:00
gdlbo 164479da1d disabled profiles/groups rename 2023-05-24 01:00:53 +03:00
gdlbo d93bf41d28 fixed discover bug 2023-05-23 23:43:23 +03:00
gdlbo 38a2b3f2b2 cleanup banner msg code 2023-05-23 23:17:20 +03:00
gdlbo 342534676c fixed another strange issue with banners 2023-05-23 23:08:53 +03:00
gdlbo 56a6a6de03 fixed messages issue 2023-05-23 23:03:10 +03:00
gdlbo d1445c2801 disable language change for miui
https://xiaomi.eu/community/threads/miui-14-per-app-language-support.69022

china number one!!!!!!!!!
2023-05-23 22:28:13 +03:00
gdlbo 6d3ddede38 Update WebViewColoringUtils.java 2023-05-22 19:01:39 +03:00
gdlbo 08dae9b342 Experimental proguard config with hooks refactoring (#1323)
fixed telegram stickers issue
speedup webview coloring
refactored VKUIHook
fixed duplication of eruda
added a check for duplication of adding styles for coloring vkui
2023-05-22 18:48:15 +03:00
gdlbo 8244b31631 fixed issue with aidl 2023-05-21 03:10:23 +03:00
gdlbo 8b29870df9 fixed vk classes crash 2023-05-21 02:57:07 +03:00
gdlbo ab1d0bde0d Update TelegramStickersGrabber.java 2023-05-21 00:59:40 +03:00
gdlbo 782f8a881d updated desugar runtime library 2023-05-21 00:58:39 +03:00
gdlbo b712630809 fixed logging issues 2023-05-21 00:58:19 +03:00
gdlbo b6698287a0 Update proguard-rules.pro 2023-05-21 00:21:59 +03:00
aliveoutside 1b5bfb0ea6 daily mix fix 2023-05-20 19:02:01 +03:00
gdlbo 59d5b83d7b fixed catalog injectors issues
cache playlist fixed
daily mix fixed
2023-05-20 16:32:33 +03:00
gdlbo 9c127931cf updated translations 2023-05-20 14:47:29 +03:00
gdlbo 6f552ee0cb some code cleanup 2023-05-20 14:36:47 +03:00
gdlbo ae1520e189 added logs shrink for release builds 2023-05-20 13:52:43 +03:00
gdlbo 8fae9e952f updated gradle version 2023-05-20 13:52:00 +03:00
gdlbo e6047ffe8a updated appcenter libs 2023-05-20 13:51:26 +03:00
gdlbo b987643ad7 Update arrays.xml 2023-05-19 20:19:43 +03:00
gdlbo b93ce2dd95 fixed issues with translation 2023-05-19 20:18:23 +03:00
gdlbo 1c845c5b34 added more translations 2023-05-19 20:13:51 +03:00
Denis c4af19432d Add compression types translation (#1312) 2023-05-19 19:49:23 +03:00
gdlbo 0c289f8bbb added support for many attachments 10+ (#1311) 2023-05-19 19:34:30 +03:00
Saoqq c68d424b59 Update ffmpeg libs (#1057)
* Update ffmpeg libs

* Bring back metadata writing
2023-05-17 17:45:45 +03:00
aliveoutside 46bac84276 fix daily mix title in playlist view 2023-05-17 11:39:50 +03:00
aliveoutside 16260c5666 temp daily mix fix 2023-05-17 10:55:02 +03:00
gdlbo 594f24d640 Refactored issues with photo compression (#1300)
Added new ways of compression
Added photo copy button
2023-05-15 21:28:45 +03:00
Denis 0deafb5606 Update features.md - editing the list of functions (#1297) 2023-05-15 12:19:27 +03:00
gdlbo 2e3b45a88f Revert "Multithreading verifs downloading"
This reverts commit 0e94efc4f7.
2023-05-14 17:30:14 +03:00
gdlbo 5a7a628117 Revert "added multithread download for some large methods"
This reverts commit 34a0615003.
2023-05-14 17:30:14 +03:00
gdlbo 2d96619c67 Create Multithreading.java 2023-05-13 15:43:29 +03:00
gdlbo 34a0615003 added multithread download for some large methods 2023-05-13 15:07:27 +03:00
gdlbo 0e94efc4f7 Multithreading verifs downloading 2023-05-13 14:38:29 +03:00
gdlbo a11a88e23f moved debug activation to long click of logo/appver 2023-05-12 22:22:27 +03:00
gdlbo 72eb342b98 updated version.properties parsing + cleanup code 2023-05-12 22:00:09 +03:00
gdlbo edb011ccbf Update About.java 2023-05-12 21:19:08 +03:00
gdlbo 8b32e16428 check_for_slow_speed (#1293) 2023-05-12 19:51:27 +03:00
gdlbo d4b457b01d fixed detection admin for kick button 2023-05-12 19:50:48 +03:00
Denis 3d61780240 Sort features in README.md (#1294) 2023-05-12 16:01:09 +03:00
gdlbo 44092032ca Update Requests.java 2023-05-10 19:47:00 +03:00
gdlbo 2800ccdaea refactored dnr/dnt modules 2023-05-10 19:40:33 +03:00
gdlbo a0cce72c64 kick button for admins in chats 2023-05-10 18:01:19 +03:00
gdlbo cbca43c929 Update README.md 2023-05-10 14:14:56 +03:00
gdlbo 0324c9edb7 updated docs for building 2023-05-10 14:13:17 +03:00
Denis c7d34ece2f added features in features list and sorting (#1119)
* added feature text feature

* Add new features in list

* fix text

* Update features.md

* Add dev feature "sync account" and backup settings

* Update - Add genius

* Update features.md - delete unreleased features
2023-05-09 19:38:34 +03:00
gdlbo 681dd177b8 fixed offline genius issue 2023-05-07 12:09:18 +03:00
gdlbo 4405b04285 removed useless conv bar recomms 2023-05-06 23:40:04 +03:00
gdlbo 3c4e981839 fixed lyrics for genius 2023-05-06 23:27:30 +03:00
gdlbo e318634e56 fix some genius issues 2023-05-06 22:49:12 +03:00
aliveoutside 5ea515f6f4 fetch the lyrics from genius even when vk didn't provide them 2023-05-06 19:23:22 +03:00
gdlbo 22cd1a8e22 some audio code cleanup 2023-05-06 12:24:37 +03:00
gdlbo ba0169cb4c fixed thumbnails in online cache catalog and shuffle 2023-05-06 11:51:23 +03:00
gdlbo 5f0458c587 refactored cache tracklist injector and added shuffle button 2023-05-06 11:03:40 +03:00
gdlbo 7b840a1721 added app category for oreo+ 2023-05-05 23:00:07 +03:00
gdlbo 78036bb3db deleted snet 2023-05-05 22:59:24 +03:00
gdlbo da52a7557f cleanup code 2023-05-05 20:48:39 +03:00
Vologhat 6eae209d04 fixed building drm key url and AES-128 decoding 2023-05-05 20:48:39 +03:00
Vologhat 683f0346e2 added null-check of base uri,fixed filename comparator 2023-05-05 20:48:39 +03:00
gdlbo c95b4e7f86 added new cache insert track method 2023-05-05 20:48:39 +03:00
Vologhat 64c55d4b01 init 2023-05-05 20:48:39 +03:00
gdlbo cc55d5ddaa new btn injector for groups 2023-04-29 19:24:55 +03:00
gdlbo 522290e4a5 Update GroupsCatalogInjector.java 2023-04-28 22:26:38 +03:00
gdlbo 78191b716a Update GroupsCatalogInjector.java 2023-04-28 22:16:20 +03:00
gdlbo dcf14266f2 cleanup catalog json injector 2023-04-28 22:11:53 +03:00
gdlbo a295e11a9d fixed issues with music 2023-04-28 21:58:14 +03:00
gdlbo 67ba4319f8 fixed groups fix for catalogs 2023-04-28 21:30:33 +03:00
aliveoutside f4d4c622eb fix #1235 2023-04-28 21:19:50 +03:00
gdlbo 0d61904b19 Update GmsUtils.java 2023-04-26 19:41:22 +03:00
gdlbo 8d9d025f11 some cleanup 2023-04-23 17:22:41 +03:00
gdlbo 6cac613f70 fixed microg pushes 2023-04-20 18:24:29 +03:00
gdlbo a5d0f1b730 microg settings and force microg usage 2023-04-20 16:14:52 +03:00
gdlbo 47465356fa fixed some spoof issues 2023-04-20 15:44:49 +03:00
gdlbo 4c6eed7dad added support for microg 2023-04-20 15:36:09 +03:00
gdlbo 7bdc8b21e4 updated jars 2023-04-20 15:31:59 +03:00
gdlbo 21fc171363 Update ThemesFragment.java 2023-04-03 21:11:55 +03:00
gdlbo fb09513ca7 samsung best fix 2023-04-03 17:43:55 +03:00
gdlbo dc49c75992 Update OEMDetector.java 2023-04-03 16:30:19 +03:00
gdlbo dd289f1933 another theme at start fix..? 2023-04-03 16:01:34 +03:00
gdlbo 360c5db990 fixed shit miui issue 2023-04-03 15:54:08 +03:00
gdlbo 0df490dc55 fixed perms 2023-04-03 15:46:16 +03:00
gdlbo 064f5d8b31 some wallpapers fixes 2023-04-02 21:37:06 +03:00
gdlbo 40f3d74f07 fixed strange bug 2023-04-02 19:54:52 +03:00
awers24 cd08354b5e ukrainian translation 2023-03-31 08:58:19 +03:00
mysh228 64a9a3c1e8 belarusian translation 2023-03-30 20:09:53 +03:00
gdlbo 8770712687 dockbar editor moved to dockbar settings in appearance sett 2023-03-30 14:25:05 +03:00
gdlbo 009f856b33 deleted useless vk apps menu in dockbar editor 2023-03-30 14:24:06 +03:00
gdlbo 022c264740 removed recomm menu in discover 2023-03-30 14:23:39 +03:00
gdlbo dd2d79e474 Update DataSettingsFragment.java 2023-03-29 00:07:40 +03:00
gdlbo f2fe2ec362 added language settings for a13+ 2023-03-28 22:42:45 +03:00
k1zn 46ef15d9c8 /ru/ translate [main] 2023-03-28 02:13:05 +05:00
k1zn 93a507a314 /ru/ localization 2023-03-28 01:36:38 +05:00
gdlbo a3853a012d Сохранение аккаунтов (#1165) 2023-03-27 21:55:57 +03:00
gdlbo 10ed61acfc new color engine now is optional 2023-03-27 21:00:40 +03:00
aliveoutside 8b434d4cae revert apktool 2023-03-27 19:00:13 +03:00
gdlbo 92a33995bd fixed adaptive icons 2023-03-27 17:35:47 +03:00
gdlbo d994439561 fixed cringe build update detection v2 2023-03-25 22:44:58 +03:00
gdlbo ed751bdc30 fixed cringe build update detection 2023-03-25 22:24:33 +03:00
gdlbo ababaad45f revert old theme engine for monet theme 2023-03-25 20:32:44 +03:00
gdlbo 9a76492c06 Update custom_thumb_selector.xml 2023-03-21 16:15:38 +03:00
gdlbo 2d19254d51 fixed start issue 2023-03-21 16:13:18 +03:00
gdlbo d557abe6e9 md3 switch 2023-03-21 16:05:55 +03:00
gdlbo 658c4bcaf6 fixed issue with system theme applying + crashes 2023-03-21 15:21:31 +03:00
gdlbo 7b12be3736 disabled switch coloring 2023-03-20 00:30:06 +03:00
gdlbo 9e2bfe83b8 Revert "disable out api inj for pinned msg"
This reverts commit 8ca73197d6.
2023-03-19 21:06:30 +03:00
gdlbo 817bdd8198 Update strings.xml 2023-03-19 21:06:22 +03:00
gdlbo 230f8e5cd3 Update GiftSendFragment$b.smali 2023-03-19 19:37:32 +03:00
gdlbo cfce4cd1ff fixed polls colors 2023-03-19 19:06:21 +03:00
gdlbo c9c602b1f9 added new icons 2023-03-19 18:14:25 +03:00
gdlbo 8ca73197d6 disable out api inj for pinned msg 2023-03-19 12:17:43 +03:00
gdlbo 2cf60aedac added enc key delete 2023-03-19 12:05:32 +03:00
gdlbo 207a63117e added identity frag support 2023-03-18 19:55:21 +03:00
gdlbo 14e92e7352 removed calls pref 2023-03-18 19:35:08 +03:00
gdlbo 23c60bdf2d reduced logging + reworked debug menu 2023-03-18 19:23:07 +03:00
gdlbo 680dcf9cf2 useCustomPrefsStyle optional 2023-03-18 13:36:36 +03:00
gdlbo 5249600b76 many build features upgrades 2023-03-18 13:10:12 +03:00
gdlbo bc5a401e0e useCustomPrefsStyle true 2023-03-18 11:37:43 +03:00
gdlbo 125c2d3d69 fix switches 2023-03-18 03:14:42 +03:00
gdlbo db95b53d41 added text coloring 2023-03-17 22:31:08 +03:00
gdlbo f29532b518 fix system theme changer 2023-03-15 23:49:25 +03:00
gdlbo ebb6d7d5fd update dev icon
vk premium shock content
2023-03-15 21:49:20 +03:00
gdlbo 46ad8635f1 fix all RadioButtons and SwitchCompats buttons 2023-03-15 21:29:50 +03:00
gdlbo 507dbee4c0 switch tricks 2023-03-15 20:45:59 +03:00
aliveoutside 1dfe5971be track opened settings 2023-03-15 19:18:48 +03:00
aliveoutside 898967128a fixup build 2023-03-15 16:02:45 +03:00
aliveoutside ffa71a8087 add buildtypes 2023-03-15 15:51:36 +03:00
aliveoutside fbb470ed74 remove duplicated crash logging 2023-03-15 15:20:19 +03:00
aliveoutside 0954c8de6e move exportDex task under deps 2023-03-15 13:17:31 +03:00
aliveoutside 39585b053b fix recursive method in AnalyticsHelper 2023-03-15 13:09:57 +03:00
gdlbo 20e966e039 updated start information 2023-03-15 11:07:59 +03:00
gdlbo 99e50e4122 fixed app crash 2023-03-15 11:00:09 +03:00
gdlbo e8477097b6 Update OtherFragment.java 2023-03-15 03:29:16 +03:00
gdlbo 241b6bace5 Update build.gradle 2023-03-15 03:27:26 +03:00
gdlbo 1a5a325ff3 Update OtherFragment.java 2023-03-15 02:36:20 +03:00
gdlbo 3352b0f01c fixed metrics disabler 2023-03-15 01:37:21 +03:00
gdlbo a90ae1be64 added appcenter metrics/crash logger 2023-03-15 01:19:25 +03:00
gdlbo 4d7ff28d97 added support for language config 2023-03-14 02:52:06 +03:00
gdlbo f72967b0d3 Update apktool framework to sdk 33 2023-03-14 02:51:49 +03:00
gdlbo ea2531eaca Update apktool.jar 2023-03-14 02:50:52 +03:00
gdlbo d36fe43541 fix action menu icons color 2023-03-12 00:27:38 +03:00
gdlbo 3acec6a29d Update ThemesFragment.java 2023-03-11 23:32:08 +03:00
gdlbo 5a73f8a4ed Update write_bar_audio.xml 2023-03-11 23:24:28 +03:00
gdlbo 6ecc44c29e Update M3UDownloader.java 2023-03-11 23:21:18 +03:00
gdlbo 2e180707db Update FriendRequestHolder.smali 2023-03-11 22:35:32 +03:00
gdlbo 5176a51c95 fixed crash 2023-03-11 22:33:28 +03:00
gdlbo 0f298b4fe3 Update M3UDownloader.java 2023-03-11 22:26:05 +03:00
gdlbo 51c94d7334 some fixes 2023-03-07 12:49:33 +03:00
spiky-s 07156f1c6a added VKWebAppGetConfig vkbridge event support (#1134) 2023-03-05 16:26:43 +03:00
gdlbo 4a933110e9 fixed false applying theme 2023-03-05 15:56:46 +03:00
gdlbo 8bf424f549 fixed choice icons for photo engine selection 2023-03-05 15:45:03 +03:00
gdlbo f477232cbe Update ThemesUtils.java 2023-03-05 15:05:11 +03:00
gdlbo 80af934df3 upgraded system theming 2023-03-05 14:55:53 +03:00
gdlbo 6d97ee38cd fixed theme applying 2023-03-05 14:09:01 +03:00
gdlbo dedf1a0b1c added debugging for webview + reworked vkui inj 2023-03-04 22:02:18 +03:00
gdlbo 692e7cefad Update VerifyInfoHelper.java 2023-03-02 18:06:08 +03:00
gdlbo dc91f59048 added dev verifs
test test
2023-03-02 15:56:47 +03:00
gdlbo 4b59f732e9 senseless reapplication of filters removed 2023-03-02 14:09:24 +03:00
gdlbo 7e0b083a9a Update AssetManagerHelper.java 2023-03-02 11:57:17 +03:00
gdlbo 60336238f2 fixes 2023-02-28 18:22:36 +03:00
gdlbo 1dd12c45ef Update ThemesCore.java 2023-02-28 18:07:29 +03:00
gdlbo 91fc6f4cad Update VTSettings.java 2023-02-28 18:05:47 +03:00
gdlbo 9e07ddcdf5 improvements 2023-02-25 19:24:37 +03:00
gdlbo 23e89c31eb Update MainActivityInjector.java 2023-02-25 19:14:32 +03:00
Vologhat 876478f2c6 add implementation of https://developer.android.com/reference/android/content/Intent#ACTION_APPLICATION_PREFERENCES 2023-02-25 18:27:05 +03:00
gdlbo 96b8f99e93 some fixes 2023-02-25 15:37:23 +03:00
gdlbo d31fa5cdcc Update AndroidManifest.xml 2023-02-25 15:26:12 +03:00
Vologhat cc034226a0 add navigation click action 2023-02-24 01:39:09 +03:00
Vologhat 785c51a64a fix mod apk making 2023-02-23 16:17:10 +03:00
gdlbo 478206e0ac Update .gitignore 2023-02-21 22:33:03 +03:00
aliveoutside 6f474408a5 update readme 2023-02-21 18:42:19 +03:00
Vologhat b74cbe54ed Performance improvements and cache invalidation fix
* Combining assets.zip and res.zip for better performance
* Fix apk path on cache invalidation
2023-02-21 11:31:49 +03:00
Saoqqandsaoq a45e6a7f2a Refactor wp (#944)
* Extract couple filters to separate classes

* Move ImageEffects to separate file

* Refactor effects to use bitmap

* Reformat code, extract last batch of effects to classes

* Shitty intermediate refactor

* Still intermediate sh**, buildable btw

* More refactoring, still looks disgusting, but a bit better)

* Add fixme about order

* Remove unused stuff

* Remove unused code, prevent re-creating of drawable

* Refactor img effects to native

* Add native lib sources

* Implement Dim, Mosaic and Blur in native

* Add pre-built libs

* Get rid of filter abstraction

* Include native build

* Force rust toolchains

* Fix typos

* Comment not used smali

* Simplify wallpapers handling

* Fixes after main merge

* Minor fixes, add prebuilt lib, disable auto re-builds for native

* Fix missed copyscpec for native builds

* Fix entry for dim effect

* Fix resizing to respect current image dimensions

* Wtf? who stole NDK from actions

* Learning GH actions

I don't want to read the docs

* Revert "Learning GH actions"

This reverts commit f6f9a97d10.

* Revert "Wtf? who stole NDK from actions"

This reverts commit 1d0f1b8879.

* Try out latest LTS just why not

---------

Co-authored-by: saoq <wfmfe@ya.ru>
2023-02-21 09:20:35 +03:00
gdlbo 0d8c52548f Update ThemesManager.java 2023-02-19 21:15:09 +03:00
gdlbo 973b4980a1 Update VKThemeHelper$b.smali 2023-02-19 19:35:46 +03:00
gdlbo b85305e416 fixed emoji 2023-02-19 19:10:46 +03:00
gdlbo 942f049bc5 fixed some hardcode 2023-02-19 18:51:33 +03:00
gdlbo e01322c8d5 fixed crash 2023-02-19 18:32:24 +03:00
gdlbo 1764dc015d fixed all theme bugs 2023-02-19 18:10:33 +03:00
gdlbo 44aff4f30d refactor code 2023-02-19 16:49:02 +03:00
Vologhat 9fd01db880 revert attribute hooks for monet 2023-02-19 16:48:20 +03:00
gdlbo 9264e7f5df Update DNRInjector.java 2023-02-19 16:17:15 +03:00
gdlbo 4fcbea2a35 Update Device.java 2023-02-19 16:01:48 +03:00
gdlbo 60dcb4fb87 fixes 2023-02-19 15:38:57 +03:00
Vologhat 314e4de27d new way of color modification 2023-02-19 15:31:50 +03:00
gdlbo c9eac43919 Update StickersFragment.java 2023-02-19 15:28:33 +03:00
gdlbo 52806a85cc genius 2023-02-19 14:43:22 +03:00
gdlbo e3512bc832 Update Genius.java 2023-02-18 17:03:47 +03:00
gdlbo d43aef7526 genius switch moved to mediacontent 2023-02-18 14:57:16 +03:00
gdlbo 46da6e1ee1 Update Genius.java 2023-02-18 14:55:08 +03:00
gdlbo ed1f99a490 fixed feat moment 2023-02-18 14:19:27 +03:00
gdlbo e46d078ec0 genius lyrics test
only for songs with vk lyrics
2023-02-17 23:09:22 +03:00
gdlbo 1c0048c57c Update AudioGetLyrics.java 2023-02-17 18:36:54 +03:00
gdlbo bb94460c35 added support for new lyrics
thanks @egormetlitsky
2023-02-17 18:36:22 +03:00
gdlbo 0fb5e5b17e splash a12+ 2023-02-15 22:02:23 +03:00
gdlbo 196610f5fe Update Device.java 2023-02-15 21:54:58 +03:00
gdlbo 46579a9f40 fixed translations 2023-02-15 21:53:27 +03:00
gdlbo 424413c3da Update LibVKXClient.java 2023-02-15 21:41:23 +03:00
gdlbo b0753eefcf Update preferences_feed.xml 2023-02-15 09:26:02 +03:00
gdlbo 39e72cf766 animated splash for sdk 12
not ready lol
2023-02-14 21:51:25 +03:00
gdlbo 4e51e65bc3 updated translations 2023-02-14 21:43:42 +03:00
gdlbo e3c694d7c3 added group stories adblock 2023-02-13 18:57:29 +03:00
gdlbo b44dae69a6 some proxy updates 2023-02-13 12:35:38 +03:00
gdlbo efb909ce64 fix artists catalog 2023-02-12 14:24:17 +03:00
Saoqqandsaoq 62c11b90dc Forward calls from msg to off VK apps (#1094)
Co-authored-by: saoq <wfmfe@ya.ru>
2023-02-12 02:18:27 +03:00
gdlbo a15cd9bd0b fixed compressing jpegs 2023-02-08 18:32:58 +03:00
gdlbo 6d9f4a23c8 added newsfeed update dialog 2023-02-08 18:00:36 +03:00
gdlbo 0677f77fde Update BackupManager.java 2023-02-08 17:55:26 +03:00
gdlbo 1b274fdb91 Update DockBarEditorManager.java 2023-02-08 17:08:22 +03:00
gdlbo c4bf9f8f88 some switch fixes 2023-02-08 16:41:56 +03:00
gdlbo e9a98afae9 Update ThemesCore.java 2023-02-07 01:35:36 +03:00
gdlbo 856bd63b43 updated VTSettings.java 2023-02-07 00:48:35 +03:00
gdlbo 606c908b90 some color fixes 2023-02-07 00:09:52 +03:00
gdlbo 0adc9ca3fd updated switch cases 2023-02-06 21:47:33 +03:00
gdlbo 3345382383 jdk upped to 14 2023-02-06 21:35:48 +03:00
gdlbo 7e7f8d0efa Update InterfaceFragment.java 2023-02-06 20:00:17 +03:00
gdlbo 84e0601b76 refactoring 2023-02-06 02:51:32 +03:00
gdlbo bc43b788d8 Update ThemesCore.java 2023-02-06 02:19:36 +03:00
gdlbo 22bd830353 fix #1062 2023-02-06 01:03:31 +03:00
gdlbo c2ff38044c fixed проксi moment 2023-02-05 23:53:28 +03:00
Pavel af312540df Escape character in values-be (#1088) 2023-02-04 21:44:00 +03:00
mysh228 1cee582dbf Apostrophes fixes in arrays 2023-02-04 00:52:05 +03:00
mysh228 664ea02dd0 Apostrophes fix 2023-02-04 00:52:05 +03:00
mysh228 4fe85d264d Belarusian translation 2023-02-04 00:52:05 +03:00
gdlbo e8a1d814c1 fixed false injection 2023-02-03 16:07:42 +03:00
gdlbo 76d0dd2ad6 disabled vigo 2023-02-03 15:56:17 +03:00
gdlbo 4658338fbb Update strings.xml 2023-02-03 15:25:07 +03:00
awers24 745ccd6e1d ukrainian translate (#1083)
* ukrainian translation
2023-02-02 20:52:24 +03:00
k1zn da76da8e35 Update strings.xml 2023-02-01 20:25:08 +05:00
gdlbo 249d1de1a1 Update R.java 2023-01-31 14:50:54 +03:00
gdlbo 1a82b40a7f Update RandomProxy.java 2023-01-31 14:43:01 +03:00
k1zn 83093be566 another translate 2023-01-31 15:58:24 +05:00
gdlbo 5994172095 fixed undelete msg
fixed all bugs omg
2023-01-30 21:36:13 +03:00
gdlbo a645e2fe32 Update CallsHook.java 2023-01-30 18:07:55 +03:00
gdlbo 87f59b2ea8 Update R.java 2023-01-29 15:44:26 +03:00
gdlbo 131bd0bdcc fixed def music catalog 2023-01-29 15:24:19 +03:00
gdlbo 7618c37d4c fix samsung awful icon system 2023-01-27 19:35:37 +03:00
gdlbo 41f978cc26 added monochrome for old icon 2023-01-27 18:44:58 +03:00
gdlbo 489246347f code cleanup 2023-01-27 17:37:49 +03:00
gdlbo a68e580436 fix null link crash for music tracks 2023-01-27 16:12:27 +03:00
gdlbo 0ef33f5c52 Update AndroidUtils.java 2023-01-27 15:41:02 +03:00
gdlbo daac037285 code cleanup 2023-01-24 18:12:01 +03:00
k1zn 09f9adafb0 translate 2023-01-24 15:26:08 +05:00
gdlbo f746753b15 updated translator 2023-01-21 17:28:00 +03:00
gdlbo 2b3da25099 Update AndroidUtils.java 2023-01-21 16:56:00 +03:00
gdlbo 94e8c49784 added links verif dialog 2023-01-21 16:50:23 +03:00
gdlbo afef886293 fixed calls moment 2023-01-21 15:58:37 +03:00
gdlbo acf3a77fe7 Implementation of domain verification 2023-01-16 17:42:03 +03:00
gdlbo 7de0d9a269 updated device info collector for simplify gh issues 2023-01-16 17:26:04 +03:00
dalvesrever 75732deb61 simplify OnPreferenceClickListener implementations
add NavigatorUtils
2023-01-15 19:45:12 +03:00
dalvesrever 923586cc33 close #1014; Make message text selectable 2023-01-15 18:30:15 +03:00
abslike eac9b2f83a Fix highlight on Amoled+Monet theme (#1041)
* Fix monet

* Try to fix part 2

* Fixed outgoing message

* Update styles.xml

* FIX MONET PART IV

* fix monet part of endless

* fix monet on white theme

* Fix highlight

* Fix highlight and other

* Fix text + highlight

* Fix highlight and text

* highlight

* Monet fixes

* Fix monet

* build fix

* build fixes

* Update styles.xml

* fix highlightes Amoled theme

* fix highlight Amoled theme
2023-01-14 12:53:48 +03:00
xsafter bfc718bc98 Рефактор Utils (#1000)
* Refactor:обновил Deprecated в новых Андроидах вызовы в некоторых утилитах

* Refactor:обновил Deprecated в новых Андроидах вызовы в некоторых утилитах

* Пофиксил
2023-01-11 13:41:46 +03:00
gdlbo effab03fd2 Merge pull request #1027 from Saoqq/vk-im-calls-forward
Quick calls integration with VK messenger app
2023-01-11 12:55:34 +03:00
saoq 6b1501b0fa Fix fun name 2023-01-10 23:52:58 +03:00
saoq 4f2d97fd7b Support VK off client 2023-01-10 23:39:48 +03:00
saoq 26b1db0900 Quick calls integration with VK messenger app 2023-01-10 19:21:24 +03:00
k1zn 6936079803 fix #1026 2023-01-10 20:51:25 +05:00
gdlbo eba6c43d4c dockbar and superapp editor moved 2023-01-06 18:48:49 +03:00
gdlbo 6667dc0be8 added manual verif data update 2023-01-06 16:32:14 +03:00
gdlbo 26e59629aa some settings refactoring 2023-01-06 16:25:58 +03:00
gdlbo 14f9f6dcf8 fixed msg preview 2023-01-06 16:10:41 +03:00
gdlbo 0a8ecd8b0a Update FeedFragment.java 2023-01-06 14:47:23 +03:00
gdlbo a4113ba6d5 auto refactor xmls 2023-01-06 14:47:16 +03:00
gdlbo 4f5193f170 Update Preferences.java 2023-01-06 14:28:52 +03:00
gdlbo 81a62d5400 some code updates 2023-01-03 13:59:39 +03:00
gdlbo 1a7031ead1 fixed init filters 2023-01-01 18:43:05 +03:00
Vologhat 40a1ab64cb add generateRjava task to gradle script 2023-01-01 18:30:48 +03:00
gdlbo 78f0eae9c3 fix #1001 2023-01-01 18:23:32 +03:00
Vologhat b5de88a370 update R.java 2023-01-01 18:19:32 +03:00
Vologhat 1e9a6c6840 fix shell script 2023-01-01 18:12:46 +03:00
gdlbo eb8939021d Update styles.xml 2023-01-01 18:04:34 +03:00
Vologhat a53f90367e fix item swipe disappearance 2023-01-01 17:45:01 +03:00
gdlbo f19aae542e fixed dialog stats from dialogs list 2023-01-01 16:15:38 +03:00
gdlbo f34b895485 added some photo quality magic 2023-01-01 16:13:48 +03:00
gdlbo 5c194891ba disabled more stats 2023-01-01 15:45:25 +03:00
Vologhat e7c08406a5 replace tags with ids 2023-01-01 15:29:42 +03:00
Vologhat c3a08ea7a8 change item width to match_parent 2023-01-01 15:23:25 +03:00
Vologhat 69ea193771 refactor CategorizedAdapter, DockBarEditor, SuperAppEditor 2023-01-01 15:08:32 +03:00
gdlbo 562bfc0ed0 added webview wrapper 2023-01-01 15:08:22 +03:00
Vologhat 919d7cb19d refactor CategorizedAdapter, DockBarEditor, SuperAppEditor 2023-01-01 15:06:55 +03:00
gdlbo 0a766038da updated icon for dialog stats 2022-12-31 23:04:26 +03:00
gdlbo dabc79cdb2 chat stats 2022-12-31 21:42:42 +03:00
gdlbo 4cb73d669a Update StickerPackAdapter.java 2022-12-30 17:50:03 +03:00
gdlbo dfddb13d2d Update CatalogJsonInjector.java 2022-12-30 17:45:39 +03:00
Vologhat f17c57bac2 add tgs stickers preview in settings 2022-12-30 17:32:14 +03:00
Vologhat a6c4c376c3 fix tgs stickers updating on keyboard stickers panel 2022-12-30 17:12:16 +03:00
gdlbo 3e4f14678e fixed nonmilk profile hide 2022-12-30 16:35:20 +03:00
gdlbo f860eb2cc0 Merge pull request #995 from psamur/main
New icons in profile buttons
2022-12-30 16:01:46 +03:00
gdlbo 2a6b9da4ef ImBanner cleanup code 2022-12-30 15:58:10 +03:00
Pavel 6224a4afdf new icons in profile buttons 2022-12-30 15:54:12 +03:00
gdlbo 8650124860 refactored ssfs utils 2022-12-30 15:35:55 +03:00
gdlbo 5e35a61473 refactored profile buttons injector 2022-12-30 14:52:29 +03:00
Vologhat 578f1a2221 add launch task 2022-12-30 14:28:30 +03:00
gdlbo 0fb3ff6c53 deleted useless logs 2022-12-30 02:38:28 +03:00
abslike 7fbfbd1e1e Fix Monet on nonmilkshake (#991) 2022-12-30 02:35:08 +03:00
gdlbo 71de558e5c ssfs update
added support for im banners
2022-12-30 02:31:09 +03:00
gdlbo 606b89a4ec ssfs update
added profile hide
2022-12-30 01:34:15 +03:00
Vologhat b4bdb3070a fix tgs preference summary 2022-12-29 20:53:01 +03:00
Vologhat 9f4b5990b7 refactor PreferencesUtil.java to PreferenceFragmentUtils.java 2022-12-29 19:08:15 +03:00
Vologhat 93b28b0a8f add non-null annotation 2022-12-29 19:04:11 +03:00
gdlbo ed0587b9b6 Merge pull request #988 from psamur/main
"View all..." normal translation
2022-12-29 10:43:16 +03:00
Pavel 6ce72dfc8b - bad translate + normal translate requested in VKTCH 2022-12-29 01:21:10 +03:00
gdlbo 65f44d32ca Update ThemesUtils.java 2022-12-28 23:41:45 +03:00
k1zn 8e57d5ab44 fix crash notf name and translate
crash
2022-12-29 00:52:17 +05:00
gdlbo c2b6bffb17 added articles colors inj 2022-12-28 22:17:43 +03:00
gdlbo 550fbf8f6c Merge pull request #982 from abslike/patch-2
Fix monet in messages(nomilkshake)
2022-12-28 22:01:49 +03:00
gdlbo 79d3287143 fixed #969 again for muted accent 2022-12-28 21:56:34 +03:00
gdlbo 2242e37315 fixed outgoing msg highlighted status 2022-12-28 21:50:21 +03:00
gdlbo 7099da0387 fixed searchDialog 2022-12-28 21:39:56 +03:00
k1zn 9b29288351 fix #986 2022-12-28 22:07:03 +05:00
abslike e000bd7971 Fix monet in messages(nomilkshake) 2022-12-28 00:40:24 +05:00
gdlbo 8eb725148f added search engine selection 2022-12-27 18:05:54 +03:00
gdlbo af1d175415 fix #969 2022-12-27 16:28:19 +03:00
Vologhat 92edbd4686 add keyaboard popup 2022-12-27 16:20:31 +03:00
gdlbo 8d9812ebe0 fix #978 2022-12-27 15:54:55 +03:00
gdlbo 33477e809c fixed #974 2022-12-27 15:22:10 +03:00
Vologhat 04f4f7d2ad fix #972 2022-12-27 11:54:08 +03:00
gdlbo 80b8399cb8 added link to bot in tg stickers info 2022-12-27 01:05:51 +03:00
gdlbo 483c9eda4d added more anime pic search engine 2022-12-27 00:38:38 +03:00
gdlbo c76a7a5332 fixed crash SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 2022-12-26 23:20:07 +03:00
gdlbo c470062d70 fixed crash getColor 2022-12-26 23:11:42 +03:00
1333 changed files with 58777 additions and 37793 deletions
+1 -4
View File
@@ -19,9 +19,6 @@ assignees: ''
**Скриншот ошибки**
**Информация об устройстве:**
- Устройство: Samsung Galaxy J1 Mini
- OS: Android 9 | OneUi 3.0
- Коммит: fa12e8f (В О Приложении написана версия коммита)
**Скопируйте сюда информацию об устройстве нажав на кнопку "Скопировать информацию об устройстве" в Настройках -> Другое и удалите этот текст**
**Дополнительная информация о баге или мыслях почему оно может происходить (если есть)**
+59 -51
View File
@@ -1,49 +1,22 @@
### Все функции модификации
### Весь функционал модификации
* Лента
* Блокировка рекламы в ленте
* Блокировка постов через фильтры
* Возможность добавлять в вайтлист фильтров группы, чтобы в них не удалялись посты
# Реклама
* Блокировка рекламы в ленте +
* Блокировка историй с возможной рекламой +
* Блокировка постов:
* С источником
* С MiniApp
* Через фильтры групп, слов
* Возможность добавлять в вайтлист фильтров группы, чтобы в них не удалялись посты+
* Возможность отключить рекомендации от ВК
* Медиаконтент
* Отключение отправки метрики
# Интерфейс и внешний вид
* Округление дат
* 1 января в 4:20
* 1 января в 4:20:00
* 1 января 2000 в 4:20:00
* Округление чисел
* Сокращение постов **(Показать полностью)**
* Результаты опросов без участия
* Возможность указывать папку для загрузки фото/видео/музыки/всего
* Интеграция с <a href="https://www.last.fm/">LAST.FM</a> (а также возможность скробблинга)
* Возможность **кешировать музыку / автокешировать ее при прослушивании**
* Возможность выбирать раздел музыки, открываемый по умолчанию
* Возможность скачивать видео, очищать историю просмотра видео
* Возможность найти фотографию через поисковые системы
* Интеграция с <a href="https://vkx.app/">VK X</a>
* Возможность кешировать треки в приложении
* Сообщения
* Обои в сообщениях
* Возможность выключения кнопки записи голосовых сообщений
* Возможность скрыть блок рекомендаций в сообщениях
* Режим **VK Me**
* Возможность вернуть вкладку уведомлений для режима VK Me
* Встроенный переводчик текста для сообщений
* Возможность выбрать язык перевода
* Автоматический перевод ваших сообщений на выбранный язык
* Альтернативный дизайн эмодзи меню
* Возможность использовать системные эмодзи
* Возможнсть использовать Enter с аппаратной клавиатуры
* Панель ввода из приложения VK для iOS
* Telegram Стикеры
* Возможность загружать свои стикерпаки из Telegram во ВКонтакте
* Внешний вид
* Возможность отключать новый дизайн версий VK (Milkshake)
* Название заголовков в докбаре
* Возможность использовать акцент для иконок
* Возможность отключить счётчики в докбаре
* Смена иконки приложения (содержит много уникальных иконок для донатеров)
* Возможность покрасить панель навигации, веб-страницы
* Интерфейс
* Округление чисел
* Возможность отключить блок историй наверху ленты
* Возможность отключить боковую камеру в разделе «Новости»
* Возможность отключить блок «Что у вас нового?» в разделе «Новости»
@@ -56,23 +29,58 @@
* Возможность отключить сокращение названий разделов в меню
* Возможность скрыть блок рекомендаций друзей в разделе «Друзья»
* Возможность скрыть подписи в настройках
* Редактор докбара
* Редактор элементов Superapp
* Активность
* Анимированный экран входа для Android 12+
* Редактор докбара
* Редактор элементов Superapp
* Возможность отключать новый дизайн версий VK (Milkshake)
* Название заголовков в докбаре
* Возможность использовать свой акцент для иконок
* Возможность отключить счётчики в докбаре
* Смена иконки приложения (содержит много уникальных иконок для донатеров)
* Возможность покрасить панель навигации, веб-страницы
* Обои в сообщениях
* Возможность выключения кнопки записи голосовых сообщений
* Возможность скрыть блок рекомендаций в сообщениях
* Режим **VK Me**
* Возможность вернуть вкладку уведомлений для режима VK Me
* Встроенный переводчик текста для сообщений
* Альтернативный дизайн эмодзи меню
* Возможность использовать системные эмодзи
* Панель ввода из приложения VK для iOS
* Сокращение постов **(Показать полностью)**
* Результаты опросов без участия
# Медиаконтент
* Интеграция с <a href="https://www.last.fm/">LAST.FM</a> (а также возможность скробблинга)
* Возможность **кешировать музыку / автокешировать ее при прослушивании**
* Возможность выбирать раздел музыки, открываемый по умолчанию
* Возможность скачивать видео, очищать историю просмотра видео
* Возможность найти фотографию через поисковые системы ?
* Интеграция с <a href="https://vkx.app/">VK X</a>
* Поддержка новых текстов в музыке (и с Genius в том числе)
# Сообщения
* Шифрование сообщений
* Возможность видеть удаленные сообщения
* Функционал, позволяющий оставаться в «оффлайне» (принудительный оффлайн/не отправлять статус онлайна и т.п.)
* Нечиталка/неписалка для ЛС/бесед/ботов/групп
* Возможность загружать свои стикерпаки из Telegram во ВКонтакте
* Возможнсть использовать Enter с аппаратной клавиатуры
# Активность
* Возможность сохранять удалённые сообщения
* Функционал, позволяющий оставаться в «оффлайне» (принудительный оффлайн/не отправлять статус онлайна и т.п.)
* Возможность отключить информацию о том, что вы просмотрели историю/прослушали голосовое сообщение
* Возможность видеть онлайн пользователей, если у вас скрыт онлайн через VK Messenger
* Возможность сохранять настройки бесшумных сообщений/сообщений-бомбочек
* Отключить уведомление о том, что вы сделали скриншот в беседе
* Отключение редиректа через away.php
* Отключение отправки метрики
* Прокси
* Отключение бизнес-уведомлений
# Прокси
* Поддержка сторонних прокси, таких как: Zaborona, VikaMobile, рандомные прокси и прочие
* Возможность использовать **HTTP/HTTPS/SOCKS** прокси, менять домены **API/OAuth/Static**
* Другое
* Синхронизация контактов с VK
* Очистка кеша приложения (**всё/стикеры/изображения/видео/сообщения/WebView**)
* Возможность использовать **HTTP/HTTPS/SOCKS** прокси, менять домены **API/OAuth/Static**
# Другое
* Автоочистка кеша при достижении указанного вами значения (**100/500 MB, 1/2/5 GB**)
* Функционал для **дебага приложения/бэкап возможности/верификации VTosters**
* Возможность создания резервной копии (бекапа) настроек и аккаунтов
Binary file not shown.

After

Width:  |  Height:  |  Size: 545 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 819 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 730 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

+18 -6
View File
@@ -21,14 +21,21 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up JDK 11
- name: Checkout
uses: actions/checkout@v3
- name: Set up NDK
uses: nttld/setup-ndk@v1
with:
ndk-version: r25c
add-to-path: false
- name: Set up JDK
uses: actions/setup-java@v3
with:
java-version: '11'
java-version: '17'
distribution: 'adopt'
- uses: actions/checkout@v3
- name: Download tools
run: |
sudo apt update
@@ -37,13 +44,18 @@ jobs:
sudo apt install zipalign
chmod +x scripts/apktool.jar
chmod +x scripts/apksigner.jar
rustup target add armv7-linux-androideabi
rustup target add aarch64-linux-android
- name: Build VTLite
run: |
gradle prepareDexForMerge
gradle generateBuildTasks
gradle prepareDexForMergeDev
java -jar scripts/apktool.jar b smali -o smali/VTLite.apk --use-aapt2 -p scripts/framework/
zipalign -p -f 4 smali/VTLite.apk smali/VTLite.apk_aligned
mv smali/VTLite.apk_aligned smali/VTLite.apk
env:
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
- name: Sign and verify the apk
run: |
+2
View File
@@ -31,3 +31,5 @@ smali/assets/version.properties
*.keystore
gradle.properties
scripts/build.sh
smali/lib/arm64-v8a/libnative_effects.so
smali/lib/armeabi-v7a/libnative_effects.so
+28
View File
@@ -0,0 +1,28 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="RClass Regeneration" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/scripts/rclass_regenerator.sh" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="/bin/zsh" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="true" />
<option name="EXECUTE_SCRIPT_FILE" value="true" />
<envs />
<method v="2" />
</configuration>
<configuration default="false" name="RClass Regeneration" type="BatchConfigurationType" factoryName="Batch">
<option name="INTERPRETER_OPTIONS" value="" />
<option name="WORKING_DIRECTORY" value="" />
<option name="PARENT_ENVS" value="true" />
<module name="" />
<option name="SCRIPT_NAME" value="./scripts/rclass_regenerator.bat" />
<option name="PARAMETERS" value="" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>
+17
View File
@@ -0,0 +1,17 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Update APKs Jars (MacOS)" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/scripts/update_jars_brew.sh" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="/bin/zsh" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="true" />
<option name="EXECUTE_SCRIPT_FILE" value="true" />
<envs />
<method v="2" />
</configuration>
</component>
+17
View File
@@ -0,0 +1,17 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Update APKs Jars" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/scripts/update_jars.sh" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="/bin/zsh" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="true" />
<option name="EXECUTE_SCRIPT_FILE" value="true" />
<envs />
<method v="2" />
</configuration>
</component>
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:buildAndInstallVTLBeta]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:buildAndInstallVTLBeta" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:buildAndInstallVTLDev]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:buildAndInstallVTLDev" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:buildAndInstallVTLRelease]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:buildAndInstallVTLRelease" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:buildAndLaunchVTLBeta]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:buildAndLaunchVTLBeta" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:buildAndLaunchVTLDev]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:buildAndLaunchVTLDev" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:buildAndLaunchVTLRelease]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:buildAndLaunchVTLRelease" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
+24
View File
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:buildVTLBeta]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:buildVTLBeta" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
+24
View File
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:buildVTLDev]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:buildVTLDev" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
+24
View File
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:buildVTLRelease]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:buildVTLRelease" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
+24
View File
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:exportDexBeta]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:exportDexBeta" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
+24
View File
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:exportDexDev]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:exportDexDev" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
+24
View File
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:exportDexRelease]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:exportDexRelease" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:prepareDexForMergeDev]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:prepareDexForMergeDev" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="lite [app:prepareDexForMergeRelease]" type="GradleRunConfiguration" factoryName="Gradle" nameIsGenerated="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="app:prepareDexForMergeRelease" />
</list>
</option>
<option name="vmOptions" value="-Xms4g -Xmx4g" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>
+19 -6
View File
@@ -37,7 +37,7 @@
* Стабильные сборки находятся в [Releases](https://github.com/vtosters/lite/releases)
Зеркало на нашем [<img src="https://git.maki.su/assets/img/logo.svg" align="center" width="20" height="20"/> Git](https://git.maki.su/gdlbo/lite)
Зеркало на нашем [<img src="https://gitea.com/assets/img/logo.svg" align="center" width="20" height="20"/> Git](https://git.maki.su/vtosters/lite)
### Быстрая навигация
@@ -117,14 +117,27 @@
* Все необходимые скрипты/.jar файлы для компиляции APK, его подписывании и не только находятся в `/scripts`
### Необходимые зависимости
<a href="https://www.oracle.com/java/technologies/downloads/"><img src="https://i.imgur.com/z8ZN19a.png" align="center" width="20" height="23"/> **JDK**</a> >11 версии
<img src="https://i.imgur.com/z8ZN19a.png" align="center" width="20" height="23"/> [**JDK**](https://adoptium.net/temurin/releases/) >14 версии
<img src="https://www.rust-lang.org/logos/rust-logo-32x32.png" align="center" width="20" height="20"/> [**Rust**](https://www.rust-lang.org/learn/get-started) с Android ARM тулчейнами: `rustup target add aarch64-linux-android armv7-linux-androideabi`
<img src="https://developer.android.com/static/images/logos/android.svg" align="center" width="20" height="20"/> Android SDK и NDK (устанавливаются через
[sdkmanager](https://developer.android.com/studio/command-line/sdkmanager) или [Android Studio](https://developer.android.com/studio))
<a href="https://developer.android.com/studio"><img src="https://i.imgur.com/cPvvFDP.png" align="center" width="20" height="23"/> **Android Studio**</a>
### Linux/macOS/Windows
Для сборки необходимо вызвать одну из следующих gradle tasks:
+ `./gradlew buildVTL` - соберет и подпишет APK
+ `./gradlew buildAndInstallVTL` - соберет, подпишет и попытается установить через ADB
+ [FOR DEVS] `./gradlew prepareDexForMerge` - соберет все необходимое для сборки в `smali/`
+ `./gradlew buildVTL + <Build Type>` - соберет и подпишет APK
+ `./gradlew buildAndInstallVTL + <Build Type>` - соберет, подпишет и попытается установить через ADB
+ `./gradlew buildAndLaunchVTL + <Build Type>` - соберет, подпишет, попытается установить через ADB и запустит на устройстве
+ [FOR DEVS] `./gradlew prepareDexForMerge + <Build Type>` - соберет все необходимое для сборки в `smali/`
+ [FOR DEVS] `./gradlew exportDex + <Build Type>` - экспортирование дексов из собранного приложения для переноса в `smali/`
```
Build types:
Dev
Beta
Release
```
+148 -96
View File
@@ -1,17 +1,28 @@
import java.nio.file.Files
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipInputStream
import org.apache.tools.ant.taskdefs.condition.Os
import java.util.zip.ZipFile
plugins {
id 'com.android.application'
id 'net.nemerosa.versioning' version '2.15.1'
id 'org.mozilla.rust-android-gradle.rust-android'
}
cargo {
profile = 'release'
module = '../native-effects'
libname = 'native-effects'
targets = ["arm", "arm64"]
prebuiltToolchains = true
pythonCommand = "python3"
}
def smaliFolder = projectDir.toPath().resolve("../smali").normalize()
def scriptsFolder = projectDir.toPath().resolve("../scripts").normalize()
//you can add own folders with decompiled smali code
def dexes = smaliFolder.toFile()
.listFiles({ f -> f.isDirectory() && f.name.startsWith("smali") } as FileFilter)
.size()
versionFile {
file = projectDir.toPath().resolve("src/main/assets/version.properties").toFile()
@@ -21,61 +32,6 @@ task cleanVersionFile {
projectDir.toPath().resolve("src/main/assets/version.properties").toFile().delete()
}
task exportDex {
doLast {
try {
File moduleDir = projectDir
ZipInputStream inputStream = new ZipInputStream(new FileInputStream(moduleDir.getAbsolutePath() + "/build/outputs/apk/release/app-release-unsigned.apk"))
ZipFile file = new ZipFile(moduleDir.getAbsolutePath() + "/build/outputs/apk/release/app-release-unsigned.apk");
ZipEntry entry
while ((entry = inputStream.nextEntry) != null) {
if (entry.getName().equals("classes.dex")) {
print('classes.dex found!')
FileOutputStream output = new FileOutputStream(new File(moduleDir.getAbsoluteFile(), "classes6.dex"))
byte[] buffer = new byte[1024]
int len = 0
while ((len = inputStream.read(buffer)) > 0) {
output.write(buffer, 0, len)
}
output.close()
}
if (entry.getName().equals("classes2.dex")) {
print('\nclasses2.dex found!')
FileOutputStream output = new FileOutputStream(new File(moduleDir.getAbsoluteFile(), "classes7.dex"))
byte[] buffer = new byte[1024]
int len = 0
while ((len = inputStream.read(buffer)) > 0) {
output.write(buffer, 0, len)
}
output.close()
}
}
for (ZipEntry e : Collections.list(file.entries())) {
if (e.getName().endsWith("assets/version.properties")) {
var is = file.getInputStream(e)
FileOutputStream output = new FileOutputStream(new File(moduleDir.getAbsoluteFile(), "version.properties"))
byte[] buffer = new byte[1024]
int len = 0
while ((len = is.read(buffer)) > 0) {
output.write(buffer, 0, len)
}
output.close()
print('\nversion.properties found!')
}
}
} catch (Exception e) {
e.printStackTrace()
}
}
}
android {
compileSdkVersion 32
buildToolsVersion '32.0.0'
@@ -95,61 +51,157 @@ android {
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
buildConfigField 'String', 'APPCENTER_KEY', '""'
proguardFile 'proguard-rules.pro'
}
rc {
minifyEnabled true
buildConfigField 'String', 'APPCENTER_KEY', '""'
proguardFile 'proguard-rules.pro'
}
dev {
minifyEnabled false
buildConfigField 'String', 'APPCENTER_KEY', '""'
}
beta {
minifyEnabled false
buildConfigField 'String', 'APPCENTER_KEY', '""'
}
}
compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
sourceCompatibility JavaVersion.VERSION_14
targetCompatibility JavaVersion.VERSION_14
}
namespace 'ru.vtosters.lite'
ndkVersion '25.2.9519653'
buildFeatures {
aidl true
}
}
task testClasses {
doLast {
println 'This is a dummy testClasses task'
}
}
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
implementation 'com.microsoft.appcenter:appcenter-analytics:5.0.4'
implementation 'com.microsoft.appcenter:appcenter-crashes:5.0.4'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.4'
implementation 'net.sourceforge.streamsupport:streamsupport-minifuture:1.7.4'
implementation 'com.google.guava:guava:32.0.0-android'
implementation fileTree(dir: 'libs', include: ['*.aar'])
compileOnly fileTree(dir: 'libs', include: ['*.jar'])
}
task prepareDexForMerge(type: Copy) {
dependsOn('exportDex')
into smaliFolder.toString()
from(projectDir) {
include 'classes6.dex'
include 'classes7.dex'
}
from(projectDir) {
include 'version.properties'
into("assets")
}
doLast {
new File(projectDir, "classes6.dex").delete()
new File(projectDir, "classes7.dex").delete()
new File(projectDir, "version.properties").delete()
task generateBuildTasks() {
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def buildType = output.name.toString().capitalize()
if (buildType == "Base") return
task "exportDex$buildType"() {
dependsOn('assemble' + buildType)
doLast {
try {
def suffix = buildType.toLowerCase()
String apkPath = projectDir.getAbsolutePath() + "/build/outputs/apk/$suffix/app-$suffix"
def apk = new File(apkPath + "-unsigned.apk")
if (!apk.exists()) apk = new File(apkPath + ".apk")
def zip = new ZipFile(apk)
def dexCounter = dexes
zip.stream()
.filter(entry -> entry.name.matches("^classes(?:(?=\\d)2|)\\.dex\$") || entry.name == "assets/version.properties")
.forEach(entry -> {
String filename
if (entry.name.matches("^classes(?:(?=\\d)2|)\\.dex\$")) filename = "classes${++dexCounter}.dex"
else filename = "version.properties"
println("Exporting " + entry.name)
def tmpFile = new File(projectDir, filename)
try (def is = zip.getInputStream(entry); def fos = new FileOutputStream(tmpFile)) {
def buff = new byte[0x800]
int len
while ((len = is.read(buff)) > 0) fos.write(buff, 0, len)
}
});
} catch (Exception e) {
e.printStackTrace()
}
}
}
task "prepareDexForMerge$buildType"(type: Copy) {
dependsOn('exportDex' + buildType)
// Remove comment for native lib build
//dependsOn('cargoBuild')
into smaliFolder.toString()
from(projectDir) {
into '../smali'
include "classes*.dex"
}
from(projectDir) {
include 'version.properties'
into 'assets'
}
from('../native-effects/target/aarch64-linux-android/release') {
include 'libnative_effects.so'
into 'lib/arm64-v8a'
}
from('../native-effects/target/armv7-linux-androideabi/release') {
include 'libnative_effects.so'
into 'lib/armeabi-v7a'
}
}
task "cleanTemporaryFiles$buildType"(type: Delete)
{
delete fileTree(dir: projectDir, include: ["*.dex", "version.properties"])
delete fileTree(dir: smaliFolder, include: ['*.dex', "assets/version.properties"])
}
task "buildVTL$buildType"(type: Exec) {
dependsOn('prepareDexForMerge' + buildType)
workingDir(projectDir.parentFile)
finalizedBy "cleanTemporaryFiles$buildType"
if (Os.isFamily("unix") || Os.isFamily("mac")) {
commandLine 'bash', '-c', './scripts/build.sh'
} else {
commandLine 'cmd', '/C', '.\\scripts\\build.bat'
}
}
task "buildAndInstallVTL$buildType"(type: Exec) {
dependsOn('buildVTL' + buildType)
workingDir(scriptsFolder.toString())
ignoreExitValue true
if (Os.isFamily("unix") || Os.isFamily("mac")) {
commandLine 'bash', '-c', 'adb install VTLite.apk'
} else {
commandLine 'adb', 'install', 'VTLite.apk'
}
}
task "buildAndLaunchVTL$buildType"(type: Exec) {
dependsOn('buildAndInstallVTL' + buildType)
if (Os.isFamily("unix") || Os.isFamily("mac"))
commandLine 'bash', '-c', 'adb shell monkey -p com.vtosters.lite -c android.intent.category.LAUNCHER 1'
else
commandLine 'adb', 'shell', 'monkey', '-p', 'com.vtosters.lite', '-c', 'android.intent.category.LAUNCHER', '1'
}
}
}
}
task buildVTL(type: Exec) {
dependsOn('prepareDexForMerge')
task generateRjava(type: Exec) {
workingDir(projectDir.parentFile)
if (Os.isFamily("unix") || Os.isFamily("mac")) {
commandLine 'bash', '-c', './scripts/build.sh'
} else {
commandLine 'cmd', '/C', '.\\scripts\\build.bat'
}
if (Os.isFamily("unix") || Os.isFamily("mac"))
commandLine "bash", "-c", "./scripts/rclass_regenerator.sh"
else
commandLine "cmd", "/C", ".\\scripts\\rclass_regenerator.sh"
}
task buildAndInstallVTL(type: Exec) {
dependsOn('buildVTL')
workingDir(scriptsFolder.toString())
ignoreExitValue true
if (Os.isFamily("unix") || Os.isFamily("mac")) {
commandLine 'bash', '-c', 'adb install VTLite.apk'
} else {
commandLine 'adb', 'install', 'VTLite.apk'
}
}
exportDex.dependsOn('assembleRelease')
clean.dependsOn('cleanVersionFile')
versionFile.dependsOn('cleanVersionFile')
preBuild.dependsOn('versionFile')
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+26 -1
View File
@@ -18,4 +18,29 @@
## If you keep the line number information, uncomment this to
## hide the original source file name.
##-renamesourcefileattribute SourceFile
#-keepclassmembers class fq
#-keepclassmembers class fq
-assumenosideeffects class android.util.Log {
public static boolean isLoggable(java.lang.String, int);
public static int v(...);
public static int i(...);
public static int w(...);
public static int d(...);
public static int e(...);
}
-repackageclasses
-allowaccessmodification
-optimizations
-optimizationpasses 5
-keepattributes SourceFile, LineNumberTable
-keep,allowoptimization class ru.vtosters.hooks.**, ru.vtosters.sponsorpost.internal.Native, ru.vtosters.lite.utils.AndroidUtils, ru.vtosters.lite.utils.NetworkUtils, ru.vtosters.lite.utils.CrashReporter, ru.vtosters.lite.ui.activities.**, ru.vtosters.lite.services.**, ru.vtosters.lite.ui.fragments.**, ru.vtosters.lite.themes.**, ru.vtosters.lite.music.hook.**, ru.vtosters.lite.music.cache.injectors.**, ru.vtosters.lite.ui.wallpapers.NativeEffects, com.aefyr.tsg.g2.TelegramStickersService {
public <fields>;
public <methods>;
public <init>(...);
}
-keep class com.vtosters.lite.** { *; }
-keep class com.vk.** { *; }
-keep class bruhcollective.itaysonlab.libvkx.client.** { *; }
+11 -9
View File
@@ -1,15 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" android:maxSdkVersion="22"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" android:maxSdkVersion="22"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"></application>
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"></application>
</manifest>
@@ -1,20 +1,19 @@
package bruhcollective.itaysonlab.libvkx.client;
import static ru.vtosters.lite.utils.AndroidUtils.getGlobalContext;
import static ru.vtosters.lite.utils.Preferences.getBoolValue;
import static ru.vtosters.lite.utils.Preferences.isValidSignature;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.RemoteException;
import bruhcollective.itaysonlab.libvkx.ILibVkxService;
import com.vk.dto.music.MusicTrack;
import com.vk.music.common.MusicPlaybackLaunchContext;
import ru.vtosters.hooks.other.Preferences;
import java.util.ArrayList;
import java.util.List;
import bruhcollective.itaysonlab.libvkx.ILibVkxService;
import static ru.vtosters.hooks.other.Preferences.getBoolValue;
import static ru.vtosters.hooks.other.Preferences.isValidSignature;
import static ru.vtosters.lite.utils.AndroidUtils.getGlobalContext;
public class LibVKXClient {
@SuppressLint("StaticFieldLeak")
@@ -35,7 +34,7 @@ public class LibVKXClient {
public static boolean isVkxInstalled() {
try {
getGlobalContext().getPackageManager().getPackageInfo("ua.itaysonlab.vkx", 0);
return isValidSignature();
return isValidSignature() && !Preferences.serverFeaturesDisable();
} catch (Exception unused) {
return false;
}
@@ -56,37 +55,33 @@ public class LibVKXClient {
}
public static void lambdaplay(List<MusicTrack> list, MusicTrack musicTrack, ILibVkxService iLibVkxService, MusicPlaybackLaunchContext playerRefer) {
var playbackContext = "";
if (playerRefer != null) {
playbackContext = playerRefer.v0();
}
int indexOf = list.indexOf(musicTrack);
var ids = new ArrayList<String>();
for (var track : list) {
ids.add(asId(track));
}
if (indexOf == -1) {
indexOf = 0;
}
try {
var playbackContext = "";
if (playerRefer != null) {
playbackContext = playerRefer.v0();
}
int indexOf = list.indexOf(musicTrack);
var ids = new ArrayList<String>();
for (var track : list) {
ids.add(asId(track));
}
if (indexOf == -1) {
indexOf = 0;
}
iLibVkxService.play(ids, indexOf, playbackContext);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public static void lambdaplay(List<MusicTrack> list, MusicTrack musicTrack, ILibVkxService iLibVkxService){
public static void lambdaplay(List<MusicTrack> list, MusicTrack musicTrack, ILibVkxService iLibVkxService) {
lambdaplay(list, musicTrack, iLibVkxService, null);
}
public static String asId(MusicTrack musicTrack) {
String id = musicTrack.e + "_" + musicTrack.d;
if (musicTrack.O != null && !musicTrack.O.equals("")) {
id += "_" + musicTrack.O;
}
return id;
return musicTrack.y1();
}
}
@@ -1,7 +1,5 @@
package bruhcollective.itaysonlab.libvkx.client;
import static ru.vtosters.lite.utils.AccountManagerUtils.getUserId;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -10,10 +8,11 @@ import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.IBinder;
import android.os.RemoteException;
import bruhcollective.itaysonlab.libvkx.ILibVkxService;
import java.util.List;
import bruhcollective.itaysonlab.libvkx.ILibVkxService;
import static ru.vtosters.lite.utils.AccountManagerUtils.getUserId;
public class LibVKXClientImpl {
private ILibVkxService serviceInstance;
@@ -5,24 +5,21 @@ import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
import com.aefyr.tsg.g2.stickersgrabber.TelegramStickersGrabber;
import com.vtosters.lite.R;
import ru.vtosters.lite.utils.AndroidUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import ru.vtosters.lite.utils.AndroidUtils;
/**
* Created by Aefyr on 20.05.2018.
*/
public class NotificationsHelper {
// private static final int NOTIFICATION_ID_BASE = 3921337;
// private static final int NOTIFICATION_ID_BASE = 3921337;
private static final String NOTIFICATION_CHANNEL_ID = "tgss_chan_v5";
private static final int MAX_UPDATE_NOTIFICATIONS_PER_SECOND = 3;
private static final int MIN_TIME_BETWEEN_UPDATE_NOTIFICATIONS = 1000 / MAX_UPDATE_NOTIFICATIONS_PER_SECOND;
@@ -3,7 +3,6 @@ package com.aefyr.tsg.g2;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@@ -37,10 +36,8 @@ public class TelegramStickersPack extends CustomStickersPack {
public HashMap<String, List<Integer>> emojis = new HashMap<>();
public TelegramStickersPack(String id) {
final var idLowerCase = id.toLowerCase();
this.id = idLowerCase;
this.hash = idLowerCase.hashCode();
title = id;
this.id = this.title = id;
this.hash = id.hashCode();
}
public JSONObject encodeEmojis() throws JSONException {
@@ -104,7 +101,7 @@ public class TelegramStickersPack extends CustomStickersPack {
@Override
public boolean equals(Object obj) {
return obj instanceof TelegramStickersPack && ((TelegramStickersPack) obj).id.equalsIgnoreCase(id);
return obj instanceof TelegramStickersPack && ((TelegramStickersPack) obj).id.equals(id);
}
@Override
@@ -1,16 +1,15 @@
package com.aefyr.tsg.g2;
import static ru.vtosters.lite.utils.AndroidUtils.getGlobalContext;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.aefyr.tsg.g2.sql.TelegramStickersDbHelper;
import com.aefyr.tsg.g2.stickersgrabber.TelegramStickersGrabber;
import com.aefyr.tsg.g2.stickersgrabber.TelegramStickersPackInfo;
import ru.vtosters.lite.ui.fragments.VTSettings;
import ru.vtosters.lite.ui.fragments.tgstickers.StickersFragment;
import java.io.File;
import java.util.ArrayList;
@@ -19,7 +18,7 @@ import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import ru.vtosters.lite.ui.fragments.tgstickers.StickersFragment;
import static ru.vtosters.lite.utils.AndroidUtils.getGlobalContext;
/**
* Created by Aefyr on 19.05.2018.
@@ -27,19 +26,13 @@ import ru.vtosters.lite.ui.fragments.tgstickers.StickersFragment;
public class TelegramStickersService {
private static final String TAG = "TGStickersService";
private static TelegramStickersService instance;
private final Context c;
private final ArrayList<TelegramStickersPack> packs;
private final ArrayList<TelegramStickersPack> activePacks;
private final ArrayList<TelegramStickersPack> inactivePacks;
private final ArrayList<StickersEventsListener> listeners;
private final HashSet<String> currentlyDownloading;
private final Handler uiThreadHandler;
private final TelegramStickersGrabber grabber;
private final TelegramStickersDbHelper dbHelper;
private final ArrayList<Runnable> queuedTasks;
private final ThreadPoolExecutor executor;
@@ -49,16 +42,14 @@ public class TelegramStickersService {
private TelegramStickersService(Context context) {
instance = this;
this.c = context.getApplicationContext();
listeners = new ArrayList<>();
currentlyDownloading = new HashSet<>();
uiThreadHandler = new Handler(Looper.getMainLooper());
grabber = new TelegramStickersGrabber(null);
dbHelper = new TelegramStickersDbHelper(c);
dbHelper = new TelegramStickersDbHelper(context);
queuedTasks = new ArrayList<>();
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
notificationsHelper = new NotificationsHelper(c);
notificationsHelper = new NotificationsHelper(context);
packs = new ArrayList<>();
activePacks = new ArrayList<>();
@@ -71,11 +62,11 @@ public class TelegramStickersService {
return instance == null ? new TelegramStickersService(c) : instance;
}
private void updatePacks(final boolean notify) {
private void updatePacks(boolean notify) {
packs.clear();
dbHelper.getAllPacks(new TelegramStickersDbHelper.PacksLoadingListener() {
@Override
public void onPackLoaded(final TelegramStickersPack pack) {
public void onPackLoaded(TelegramStickersPack pack) {
runOnUiThread(() -> {
packs.add(pack);
@@ -104,14 +95,6 @@ public class TelegramStickersService {
});
}
public void addStickersEventsListener(StickersEventsListener listener) {
listeners.add(listener);
}
public void removeStickersEventsListener(StickersEventsListener listener) {
listeners.remove(listener);
}
private void notifyPackAdded(TelegramStickersPack pack, int atIndex) {
getGlobalContext().sendBroadcast(new Intent(StickersFragment.ACTION_RELOAD));
if (listeners.isEmpty())
@@ -154,6 +137,7 @@ public class TelegramStickersService {
private void notifyActivePacksListChanged() {
getGlobalContext().sendBroadcast(new Intent(StickersFragment.ACTION_RELOAD));
getGlobalContext().sendBroadcast(new Intent(VTSettings.ACTION_INVALIDATE_TGS_COUNT));
if (listeners.isEmpty())
return;
@@ -188,20 +172,16 @@ public class TelegramStickersService {
return inactivePacks;
}
public boolean isDoneLoading() {
return ready;
}
public boolean requestPackDownload(final String id, File packFolder) {
public void requestPackDownload(String id, File packFolder) {
if (currentlyDownloading.contains(id)) {
Log.e(TAG, String.format("Got request to download pack %s which is already downloading", id));
return false;
return;
}
if (!ready) {
final File folder = packFolder;
File folder = packFolder;
queuedTasks.add(() -> requestPackDownload(id, folder));
return true;
return;
}
TelegramStickersPack pack = new TelegramStickersPack(id);
@@ -221,84 +201,86 @@ public class TelegramStickersService {
notifyPackAdded(pack, packs.size() - 1);
}
final TelegramStickersPack newPack = pack;
final boolean isUpdate = update;
TelegramStickersPack newPack = pack;
boolean isUpdate = update;
currentlyDownloading.add(id.toLowerCase());
currentlyDownloading.add(id);
notificationsHelper.packStartedDownloading(newPack);
grabber.enableProxy();
grabber.grabPack(id, packFolder, pack.version, new TelegramStickersGrabber.PackDownloadListener() {
@Override
public void onPackDownloaded(TelegramStickersPackInfo packInfo, boolean newVersionFound) {
runOnUiThread(() -> {
newPack.state = TelegramStickersPack.DOWNLOADED;
notifyPackChanged(newPack, packs.indexOf(newPack));
currentlyDownloading.remove(newPack.id);
syncPack(newPack);
if (isUpdate) {
if (newPack.enabled)
notifyActivePacksListChanged();
} else {
activePacks.add(newPack);
notifyActivePacksListChanged();
}
});
notificationsHelper.packDoneDownloading(newPack, true, isUpdate, null);
}
@Override
public void onPackDownloadError(final Exception e) {
runOnUiThread(() -> {
Log.e(TAG, "Error while downloading pack " + newPack.id);
e.printStackTrace();
if (!isUpdate) {
int index = packs.indexOf(newPack);
packs.remove(index);
notifyPackRemoved(newPack, index);
} else {
// try-catch block to handle possible timeout exception
try {
grabber.grabPack(id, packFolder, pack.version, new TelegramStickersGrabber.PackDownloadListener() {
@Override
public void onPackDownloaded(TelegramStickersPackInfo packInfo, boolean newVersionFound) {
runOnUiThread(() -> {
newPack.state = TelegramStickersPack.DOWNLOADED;
notifyPackChanged(newPack, packs.indexOf(newPack));
}
currentlyDownloading.remove(newPack.id);
syncPack(newPack);
notifyPackDownloadError(newPack, e);
currentlyDownloading.remove(newPack.id);
});
notificationsHelper.packDoneDownloading(newPack, false, isUpdate, e);
}
if (isUpdate) {
if (newPack.enabled)
notifyActivePacksListChanged();
} else {
activePacks.add(newPack);
notifyActivePacksListChanged();
}
});
notificationsHelper.packDoneDownloading(newPack, true, isUpdate, null);
}
@Override
public void onGotPackInfo(final TelegramStickersPackInfo packInfo) {
runOnUiThread(() -> {
newPack.title = packInfo.title;
newPack.stickersCount = packInfo.stickersCount;
newPack.version = packInfo.version;
notifyPackChanged(newPack, packs.indexOf(newPack));
});
@Override
public void onPackDownloadError(Exception e) {
runOnUiThread(() -> {
Log.e(TAG, "Error while downloading pack " + newPack.id);
e.printStackTrace();
notificationsHelper.packDownloadUpdated(newPack, 0);
}
if (!isUpdate) {
int index = packs.indexOf(newPack);
packs.remove(index);
notifyPackRemoved(newPack, index);
} else {
newPack.state = TelegramStickersPack.DOWNLOADED;
notifyPackChanged(newPack, packs.indexOf(newPack));
}
@Override
public void onStickerDownloaded(String pack, File sticker, String boundEmoji, int stickerIndex, int downloadedStickersCount, int totalStickersCount) {
stickerIndex--;
notifyPackDownloadError(newPack, e);
currentlyDownloading.remove(newPack.id);
});
notificationsHelper.packDoneDownloading(newPack, false, isUpdate, e);
}
List<Integer> list = newPack.emojis.get(boundEmoji);
if (list == null) list = new ArrayList<>();
list.add(stickerIndex);
newPack.emojis.put(boundEmoji, list);
@Override
public void onGotPackInfo(TelegramStickersPackInfo packInfo) {
runOnUiThread(() -> {
newPack.title = packInfo.title;
newPack.stickersCount = packInfo.stickersCount;
newPack.version = packInfo.version;
notifyPackChanged(newPack, packs.indexOf(newPack));
});
notificationsHelper.packDownloadUpdated(newPack, downloadedStickersCount);
}
});
notificationsHelper.packDownloadUpdated(newPack, 0);
}
return true;
@Override
public void onStickerDownloaded(String pack, File sticker, String boundEmoji, int stickerIndex, int downloadedStickersCount, int totalStickersCount) {
stickerIndex--;
List<Integer> list = newPack.emojis.get(boundEmoji);
if (list == null) list = new ArrayList<>();
list.add(stickerIndex);
newPack.emojis.put(boundEmoji, list);
notificationsHelper.packDownloadUpdated(newPack, downloadedStickersCount);
}
});
} catch (Exception e) {
// handle other possible exceptions
e.printStackTrace();
}
}
public void setPackEnabled(final TelegramStickersPack pack, final boolean enabled, final boolean notify) {
public void setPackEnabled(TelegramStickersPack pack, boolean enabled, boolean notify) {
if (!ready) {
queuedTasks.add(() -> setPackEnabled(pack, enabled, notify));
return;
@@ -324,7 +306,7 @@ public class TelegramStickersService {
}
}
public void deletePack(final TelegramStickersPack pack) {
public void deletePack(TelegramStickersPack pack) {
if (!ready) {
queuedTasks.add(() -> deletePack(pack));
return;
@@ -333,7 +315,6 @@ public class TelegramStickersService {
boolean d = dbHelper.deletePack(pack);
Log.d(TAG, "Delete from DB=" + d);
int index = packs.indexOf(pack);
packs.remove(index);
notifyPackRemoved(pack, index);
@@ -354,7 +335,7 @@ public class TelegramStickersService {
uiThreadHandler.post(r);
}
private void syncPack(final TelegramStickersPack pack) {
private void syncPack(TelegramStickersPack pack) {
if (!ready) {
queuedTasks.add(() -> syncPack(pack));
return;
@@ -383,7 +364,7 @@ public class TelegramStickersService {
getPacksListReference().set(li1, p2);
}
interface StickersEventsListener {
public interface StickersEventsListener {
void onPackAdded(TelegramStickersPack pack, int atIndex);
void onPackRemoved(TelegramStickersPack pack, int atIndex);
@@ -396,6 +377,4 @@ public class TelegramStickersService {
void onInactivePacksListChanged();
}
}
@@ -8,9 +8,7 @@ import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.util.Log;
import com.aefyr.tsg.g2.TelegramStickersPack;
import org.json.JSONException;
import org.json.JSONObject;
@@ -5,47 +5,42 @@ import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.aefyr.tsg.g2.stickersgrabber.util.Flag;
import com.aefyr.tsg.g2.stickersgrabber.util.GoalCounter;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import ru.vtosters.lite.di.singleton.VtOkHttpClient;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import ru.vtosters.lite.net.NetCall;
import ru.vtosters.lite.net.NetCallback;
import ru.vtosters.lite.net.NetClient;
import ru.vtosters.lite.net.NetRequest;
import ru.vtosters.lite.net.NetResponse;
/**
* Created by Aefyr on 11.05.2018.
*/
public class TelegramStickersGrabber {
private static final String TAG = "TSG";
public static String REAL_TG_IP = null;
public static String PROXY_IP = null;
public static int PROXY_PORT = -1;
public static String PROXY_USER = null;
public static String PROXY_PASS = null;
public static boolean PROXY_SOCKS = true;
public static boolean HAS_PASS = false;
public static boolean USE_PROXY = false;
private static final OkHttpClient sClient = VtOkHttpClient.getInstance();
private static final int MAX_RETRIES = 2;
private static final AtomicInteger retryCount = new AtomicInteger();
private static final int STICKER_QUALITY = 100;
private static final String STICKER_FILE_NAME_FORMAT = "%03d.png";
private static final String STICKERS_KEY = "stickers";
private static final String FILE_ID_KEY = "file_id";
private static final String EMOJI_KEY = "emoji";
private static final String IS_ANIMATED_KEY = "is_animated";
private static final String IS_VIDEO_KEY = "is_video";
private static final String THUMB_KEY = "thumb";
private static final String NAME_KEY = "name";
private static final String TITLE_KEY = "title";
private static String BOT_API_BASE_URL;
private static String GET_STICKER_SET_URL;
private static String GET_FILE_URL;
@@ -57,17 +52,15 @@ public class TelegramStickersGrabber {
private final MessageDigest sha256;
private final Handler uiThreadHandler;
private String botApiKey = "";
private NetClient httpClient;
private String botApiKey;
public TelegramStickersGrabber(String botApiKey) {
this.botApiKey = botApiKey;
httpClient = new NetClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build();
uiThreadHandler = new Handler(Looper.getMainLooper());
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
Log.wtf(TAG, "No support for SHA-256");
Log.d(TAG, "No support for SHA-256");
e.printStackTrace();
throw new RuntimeException(e);
}
@@ -76,81 +69,12 @@ public class TelegramStickersGrabber {
public static void updateURLs() {
BOT_API_BASE_FILE_URL = "https://api.telegram.org/file/bot%s/%s";
BOT_API_BASE_URL = REAL_TG_IP != null ? "https://" + REAL_TG_IP + "/bot%s/" : "https://api.telegram.org/bot%s/";
BOT_API_BASE_URL = "https://api.telegram.org/bot%s/";
GET_STICKER_SET_URL = BOT_API_BASE_URL + "getStickerSet?name=%s";
GET_FILE_URL = BOT_API_BASE_URL + "getFile?file_id=%s";
}
public static boolean isTelegramBlocked() {
NetClient client = new NetClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build();
try {
if (PROXY_IP != null) {
Socket socket = new Socket(PROXY_IP, PROXY_PORT);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socket.getRemoteSocketAddress());
NetClient.Builder b = new NetClient.Builder().proxy(proxy);
if (PROXY_USER != null) {
b = b.proxyAuthenticator(new PasswordAuthentication(PROXY_USER, PROXY_PASS.toCharArray()));
}
client = b.build();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
NetRequest req = new NetRequest.Builder().url(REAL_TG_IP != null ? "https://" + REAL_TG_IP + "/test/" : "https://api.telegram.org/test/").build();
try {
NetResponse res = client.newCall(req).execute();
String s = res.getDataString();
if (!s.equals("{\"ok\":false,\"error_code\":404,\"description\":\"Not Found\"}"))
return true;
} catch (Exception e) {
return true;
}
return false;
}
public void resetProxy() {
httpClient = new NetClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build();
}
public void enableProxy() {
Thread kostil = new Thread() {
@Override
public void run() {
try {
if (PROXY_IP != null) {
Socket socket = new Socket(PROXY_IP, PROXY_PORT);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socket.getRemoteSocketAddress());
NetClient.Builder b = httpClient.newBuilder().proxy(proxy);
if (PROXY_USER != null) {
httpClient = b.proxyAuthenticator(new PasswordAuthentication(PROXY_USER, PROXY_PASS.toCharArray())).build();
}
httpClient = b.build();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
kostil.start();
try {
kostil.join();
Log.d(TAG, "Proxy set");
} catch (InterruptedException e) {
Log.e(TAG, "Unable to set proxy:");
e.printStackTrace();
}
}
public void grabPack(String id, File packFolder, String installedVersion, final PackDownloadListener listener) {
public void grabPack(String id, File packFolder, String installedVersion, PackDownloadListener listener) {
getPackInfo(id, packFolder, installedVersion, listener);
}
@@ -158,264 +82,247 @@ public class TelegramStickersGrabber {
botApiKey = key;
}
public void checkKey(final KeyCheckListener listener) {
public void checkKey(KeyCheckListener listener) {
Log.d(TAG, "Checking key: " + botApiKey);
NetRequest request = new NetRequest.Builder().get().url(String.format(BOT_API_BASE_URL + "getMe", botApiKey)).build();
httpClient.newCall(request).enqueue(new NetCallback() {
// Create a request object with the URL and bot API key
Request request = new Request.a()
.b(String.format(BOT_API_BASE_URL + "getMe", botApiKey))
.a();
// Create a new call object and enqueue it to run asynchronously
sClient.a(request).a(new Callback() {
@Override
public void onFailure(NetCall call, IOException e) {
e.printStackTrace();
public void a(Call call, IOException e) {
// Handle the failure case
Log.d(TAG, e.getMessage());
runOnUiThread(listener::onNetError);
}
@Override
public void onResponse(NetCall call, final NetResponse response) throws IOException {
runOnUiThread(() -> listener.onKeyChecked(response.code() == 200));
public void a(Call call, Response response) {
Log.d(TAG, response.toString());
runOnUiThread(() -> listener.onKeyChecked(response.h()));
}
});
}
private void getPackInfo(final String packName, final File packFolder, final String installedVersion, final PackDownloadListener listener) {
NetRequest packInfoRequest = new NetRequest.Builder().get().url(String.format(GET_STICKER_SET_URL, botApiKey, packName)).build();
httpClient.newCall(packInfoRequest).enqueue(new NetCallback() {
private void getPack(StickerSet set, File packFolder, TelegramStickersPackInfo packInfo, PackDownloadListener listener) {
GoalCounter downloadedStickers = new GoalCounter(set.stickers.size(), () -> {
Log.d(TAG, String.format("Pack %s has been downloaded to %s", set.id, packFolder.getAbsolutePath()));
listener.onPackDownloaded(packInfo, true);
});
Flag deathFlag = new Flag();
for (int i = 0; i < set.stickers.size(); i++) {
Sticker sticker = set.stickers.get(i);
String getFileUrl = String.format(GET_FILE_URL, botApiKey, sticker.fileId);
Request fileInfoRequest = new Request.a()
.b(getFileUrl)
.a();
int stickerIndex = i + 1;
sClient.a(fileInfoRequest).a(new Callback() {
@Override
public void a(Call call, IOException e) {
handleFailure(deathFlag, listener, e, downloadedStickers, call, fileInfoRequest, this);
}
@Override
public void a(Call call, Response response) {
if (deathFlag.up())
return;
if (!response.h()) {
retryRequest(call, fileInfoRequest, this);
return;
}
try (ResponseBody responseBody = response.a()) {
JSONObject fileInfoResponse = new JSONObject(responseBody.g()).getJSONObject("result");
String filePath = fileInfoResponse.getString("file_path");
if (botApiKey == null) botApiKey = "";
String fileDownloadUrl = String.format(BOT_API_BASE_FILE_URL, botApiKey, filePath);
Request fileDownloadRequest = new Request.a()
.b(fileDownloadUrl)
.a();
sClient.a(fileDownloadRequest).a(new Callback() {
@Override
public void a(Call call, IOException e) {
handleFailure(deathFlag, listener, e, downloadedStickers, call, fileDownloadRequest, this);
}
@Override
public void a(Call call, Response response) {
if (deathFlag.up())
return;
if (!response.h()) {
retryRequest(call, fileDownloadRequest, this);
return;
}
try (ResponseBody responseBody = response.a()) {
if (responseBody == null) {
handleFailure(deathFlag, listener, new TSGException("Response body for a sticker is null :/"), downloadedStickers, call, fileDownloadRequest, this);
return;
}
InputStream stickerInputStream = responseBody.a();
Bitmap stickerImage = BitmapFactory.decodeStream(stickerInputStream);
if (stickerImage == null) {
handleFailure(deathFlag, listener, new TSGException("Unable to decode sticker image"), downloadedStickers, call, fileDownloadRequest, this);
return;
}
File stickerFile = new File(packFolder, String.format(STICKER_FILE_NAME_FORMAT, stickerIndex));
try {
saveStickerImage(stickerImage, stickerFile);
} catch (TSGException e) {
throw new RuntimeException(e);
}
listener.onStickerDownloaded(set.name, stickerFile, sticker.emoji, stickerIndex,
downloadedStickers.value() + 1, set.stickers.size());
downloadedStickers.increase();
}
}
});
} catch (Exception e) {
handleFailure(deathFlag, listener, e, downloadedStickers, call, fileInfoRequest, this);
}
}
});
}
}
private void handleFailure(Flag deathFlag, PackDownloadListener listener, Exception e, GoalCounter downloadedStickers, Call call, Request request, Callback callback) {
if ((e instanceof IOException || e instanceof TSGException) && retryCount.get() > MAX_RETRIES) {
Log.e(TAG, "Unable to download sticker: " + e.getMessage());
downloadedStickers.increase();
return;
} else if (retryCount.get() < MAX_RETRIES) {
retryRequest(call, request, callback);
return;
}
if (deathFlag.up()) {
return;
}
deathFlag.raise();
listener.onPackDownloadError(e);
}
private void retryRequest(Call call, Request request, Callback callback) {
retryCount.incrementAndGet();
if (retryCount.get() > MAX_RETRIES) {
Log.e(TAG, "retryRequest: max retries");
callback.a(call, new IOException());
} else {
Log.e(TAG, "retryRequest");
sClient.a(request).a(callback);
}
}
private void saveStickerImage(Bitmap image, File file) throws TSGException {
try (FileOutputStream fos = new FileOutputStream(file)) {
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (IOException e) {
throw new TSGException("Unable to save sticker image");
}
}
private void getPackInfo(String packName, File packFolder, String installedVersion, PackDownloadListener listener) {
String getStickerSetUrl = String.format(GET_STICKER_SET_URL, botApiKey, packName);
Request packInfoRequest = new Request.a()
.b(getStickerSetUrl)
.a();
sClient.a(packInfoRequest).a(new Callback() {
@Override
public void onFailure(NetCall call, IOException e) {
public void a(Call call, IOException e) {
Log.d(TAG, e.getMessage());
listener.onPackDownloadError(e);
}
@Override
public void onResponse(NetCall call, NetResponse response) {
if (!response.isSuccessful()) {
if (response.getData() != null)
listener.onPackDownloadError(new TSGException(response.getDataString() + "\nURL: " + call.request().url()));
else
listener.onPackDownloadError(new TSGException("Unknown Exception, no response body"));
public void a(Call call, Response response) throws IOException {
Log.d(TAG, response.toString());
if (!response.h()) {
String errorMessage = response.a() != null ? response.a().g() + "\nURL: " + call.m0().g() : "Unknown Exception, no response body";
listener.onPackDownloadError(new TSGException(errorMessage));
return;
}
StickerSet set;
try {
JSONObject jPackInfo = new JSONObject(response.getDataString()).getJSONObject("result");
String packVersion = new String(sha256.digest(jPackInfo.toString().getBytes(StandardCharsets.UTF_8)));
try (ResponseBody responseBody = response.a()) {
JSONObject packInfoResponse = new JSONObject(responseBody.g()).getJSONObject("result");
String packVersion = new String(sha256.digest(packInfoResponse.toString().getBytes(StandardCharsets.UTF_8)));
if (packVersion.equals(installedVersion)) {
listener.onPackDownloaded(null, false);
return;
}
JSONArray jStickers = jPackInfo.getJSONArray("stickers");
JSONArray stickersArray = packInfoResponse.getJSONArray(STICKERS_KEY);
if (jStickers.length() == 0) {
if (stickersArray.length() == 0) {
listener.onPackDownloadError(new TSGException("No stickers in pack"));
return;
}
ArrayList<Sticker> stickers = new ArrayList<>(jStickers.length());
ArrayList<Sticker> stickers = parseStickers(stickersArray);
Log.d(TAG, String.format("Parsing stickers in pack %s", packName));
StickerSet set = new StickerSet(packInfoResponse.getString(NAME_KEY), packInfoResponse.getString(TITLE_KEY), packVersion, stickers);
for (int i = 0; i < jStickers.length(); i++) {
JSONObject jSticker = jStickers.getJSONObject(i);
if (jSticker.optBoolean("is_animated") || jSticker.optBoolean("is_video")) {
if (jSticker.has("thumb")) {
stickers.add(new Sticker(jSticker.getJSONObject("thumb").getString("file_id"), jSticker.getString("emoji")));
} else {
listener.onPackDownloadError(new TSGException("Animated and video stickerpacks without thumbs are not supported!"));
return;
}
} else {
stickers.add(new Sticker(jSticker.getString("file_id"), jSticker.getString("emoji")));
}
if (!packFolder.exists() && !packFolder.mkdirs()) {
// Handle the folder creation failure case
listener.onPackDownloadError(new IOException("Can't create folder for the pack!"));
return;
}
set = new StickerSet(jPackInfo.getString("name"), jPackInfo.getString("title"), packVersion, stickers);
Log.d(TAG, String.format("Got info for pack %s, now downloading stickers to %s", packName, packFolder.getAbsolutePath()));
TelegramStickersPackInfo packInfo = new TelegramStickersPackInfo(packName, set.name, set.stickers.size(), set.version);
listener.onGotPackInfo(packInfo);
getPack(set, packFolder, packInfo, listener);
} catch (Exception e) {
listener.onPackDownloadError(e);
return;
}
if (!packFolder.exists() && !packFolder.mkdirs()) {
listener.onPackDownloadError(new IOException("Can't create folder for the pack!"));
return;
}
Log.d(TAG, String.format("Got info for pack %s, now downloading stickers to %s", packName, packFolder.getAbsolutePath()));
TelegramStickersPackInfo packInfo = new TelegramStickersPackInfo(packName, set.name, set.stickers.size(), set.version);
listener.onGotPackInfo(packInfo);
getPack(set, packFolder, packInfo, listener);
}
});
}
private void getPack(final StickerSet set, final File packFolder, final TelegramStickersPackInfo packInfo, final PackDownloadListener listener) {
final GoalCounter downloadedStickers = new GoalCounter(set.stickers.size(), () -> {
Log.d(TAG, String.format("Pack %s has been downloaded to %s", set.id, packFolder.getAbsolutePath()));
private ArrayList<Sticker> parseStickers(JSONArray stickersArray) throws JSONException, TSGException {
ArrayList<Sticker> stickers = new ArrayList<>(stickersArray.length());
listener.onPackDownloaded(packInfo, true);
});
final Flag deathFlag = new Flag();
for (int i = 0; i < stickersArray.length(); i++) {
JSONObject stickerObject = stickersArray.getJSONObject(i);
boolean isAnimated = stickerObject.optBoolean(IS_ANIMATED_KEY);
boolean isVideo = stickerObject.optBoolean(IS_VIDEO_KEY);
String fileId = stickerObject.getString(FILE_ID_KEY);
String emoji = stickerObject.getString(EMOJI_KEY);
AtomicInteger retryed = new AtomicInteger();
for (int i = 0; i < set.stickers.size(); i++) {
final Sticker sticker = set.stickers.get(i);
NetRequest fileInfoRequest = new NetRequest.Builder().get().url(String.format(GET_FILE_URL, botApiKey, sticker.fileId)).build();
final int stickerIndex = i + 1;
AtomicBoolean sync = new AtomicBoolean();
httpClient.newCall(fileInfoRequest).enqueue(new NetCallback() {
@Override
public void onFailure(NetCall call, IOException e) {
if (deathFlag.up())
return;
deathFlag.raise();
listener.onPackDownloadError(e);
sync.set(true);
if (isAnimated || isVideo) {
if (stickerObject.has(THUMB_KEY)) {
fileId = stickerObject.getJSONObject(THUMB_KEY).getString(FILE_ID_KEY);
} else {
throw new TSGException("Animated and video stickerpacks without thumbs are not supported!");
}
}
@Override
public void onResponse(NetCall call, NetResponse response) throws IOException {
if (deathFlag.up())
return;
if (response.code() != 200) {
retryed.incrementAndGet();
if (retryed.get() > 5)
onFailure(call, new IOException());
else httpClient.newCall(fileInfoRequest)
.enqueue(this);
return;
}
String filePath;
try {
JSONObject jFileInfo = new JSONObject(response.getDataString()).getJSONObject("result");
filePath = jFileInfo.getString("file_path");
} catch (Exception e) {
deathFlag.raise();
listener.onPackDownloadError(e);
sync.set(true);
return;
}
if (botApiKey == null) botApiKey = "";
NetRequest fileDownloadRequest = new NetRequest.Builder().get().url(String.format(BOT_API_BASE_FILE_URL, botApiKey, filePath)).build();
httpClient.newCall(fileDownloadRequest).enqueue(new NetCallback() {
@Override
public void onFailure(NetCall call, IOException e) {
if (deathFlag.up())
return;
deathFlag.raise();
listener.onPackDownloadError(e);
sync.set(true);
}
@Override
public void onResponse(NetCall call, NetResponse response) throws IOException {
if (deathFlag.up())
return;
if (response.code() != 200) {
retryed.incrementAndGet();
if (retryed.get() > 5)
onFailure(call, new IOException());
else httpClient.newCall(fileDownloadRequest)
.enqueue(this);
return;
}
if (response.getData() == null) {
deathFlag.raise();
listener.onPackDownloadError(new TSGException("Response body for a sticker is null :/"));
sync.set(true);
return;
}
InputStream stickerInputStream = response.getDataStream();
Bitmap stickerImage = BitmapFactory.decodeStream(stickerInputStream);
try {
stickerInputStream.close();
} catch (IOException e) {
e.printStackTrace();
deathFlag.raise();
listener.onPackDownloadError(e);
sync.set(true);
return;
}
if (stickerImage == null) {
deathFlag.raise();
listener.onPackDownloadError(new TSGException("Unable to decode sticker image"));
sync.set(true);
return;
}
File stickerFile = new File(packFolder, String.format("%03d.png", stickerIndex));
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(stickerFile);
} catch (Exception e) {
e.printStackTrace();
deathFlag.raise();
listener.onPackDownloadError(e);
sync.set(true);
return;
}
if (!stickerImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) {
stickerImage.recycle();
deathFlag.raise();
listener.onPackDownloadError(new TSGException("Unable to compress sticker to a png file at path: " + stickerFile.getAbsolutePath()));
sync.set(true);
return;
}
stickerImage.recycle();
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
deathFlag.raise();
listener.onPackDownloadError(e);
sync.set(true);
return;
}
listener.onStickerDownloaded(set.name, stickerFile, sticker.emoji, stickerIndex, downloadedStickers.value() + 1, set.stickers.size());
downloadedStickers.increase();
sync.set(true);
}
});
}
});
while (!sync.get())
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
stickers.add(new Sticker(fileId, emoji));
}
return stickers;
}
private void runOnUiThread(Runnable r) {
@@ -438,15 +345,13 @@ public class TelegramStickersGrabber {
void onNetError();
}
public class TSGException extends Exception {
private static final long serialVersionUID = 7866915509988422944L;
public static class TSGException extends Exception {
private TSGException(String message) {
super(message);
}
}
private class StickerSet {
private static class StickerSet {
String id;
String name;
String version;
@@ -460,7 +365,7 @@ public class TelegramStickersGrabber {
}
}
private class Sticker {
private static class Sticker {
String emoji;
String fileId;
@@ -2,7 +2,6 @@ package com.arthenica.ffmpegkit;
import android.os.Build;
import android.util.Log;
import com.arthenica.smartexception.java.Exceptions;
import java.util.Collections;
@@ -0,0 +1,323 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import java.util.*;
import java.util.Map.Entry;
/**
* Analyzes an APK to:
*
* <ul>
* <li>Blame resource configurations on their entry count (entries keeping the config around).
* <li>Blame strings in resources.arsc that have no base configuration.
* <li>Blame resources on their different configurations.
* </ul>
*/
public class ArscBlamer {
/**
* Maps package key pool indices to blamed resources.
*/
private final Map<PackageChunk, List<ResourceEntry>[]> keyToBlame = new HashMap<>();
/**
* Maps types to blamed resources.
*/
private final Map<PackageChunk, List<ResourceEntry>[]> typeToBlame = new HashMap<>();
/**
* Maps package to blamed resources.
*/
private final Multimap<PackageChunk, ResourceEntry> packageToBlame = HashMultimap.create();
/**
* Maps string indices to blamed resources.
*/
private final List<ResourceEntry>[] stringToBlame;
/**
* Maps type chunk entries to blamed resources.
*/
private final Multimap<TypeChunk.Entry, ResourceEntry> typeEntryToBlame = HashMultimap.create();
/**
* This is the {@link ResourceTableChunk} inside of the resources.arsc file in the APK.
*/
private final ResourceTableChunk resourceTable;
/**
* Maps resources to the type chunk entries they reference.
*/
private Multimap<ResourceEntry, TypeChunk.Entry> resourceEntries;
/**
* Maps resources which have no base config to the type chunk entries they reference.
*/
private Multimap<ResourceEntry, TypeChunk.Entry> baselessKeys;
/**
* Contains all of the type chunks in {@link #resourceTable}.
*/
private List<TypeChunk> typeChunks;
/**
* Creates a new {@link ArscBlamer}.
*
* @param resourceTable The resources.arsc resource table to blame.
*/
public ArscBlamer(ResourceTableChunk resourceTable) {
this.resourceTable = resourceTable;
this.stringToBlame = createEntryListArray(resourceTable.getStringPool().getStringCount());
}
private static List<ResourceEntry>[] createEntryListArray(int size) {
ArrayListResourceEntry[] result = new ArrayListResourceEntry[size];
for (int i = 0; i < size; ++i) {
result[i] = new ArrayListResourceEntry();
}
return result;
}
/**
* Generates blame mappings.
*/
public void blame() {
Multimap<ResourceEntry, TypeChunk.Entry> entries = getResourceEntries();
for (Entry<ResourceEntry, Collection<TypeChunk.Entry>> entry : entries.asMap().entrySet()) {
ResourceEntry resourceEntry = entry.getKey();
PackageChunk packageChunk = Preconditions.checkNotNull(
resourceTable.getPackage(resourceEntry.packageName()));
int keyCount = packageChunk.getKeyStringPool().getStringCount();
int typeCount = packageChunk.getTypeStringPool().getStringCount();
for (TypeChunk.Entry chunkEntry : entry.getValue()) {
blameKeyOrType(keyToBlame, packageChunk, chunkEntry.keyIndex(), resourceEntry, keyCount);
blameKeyOrType(typeToBlame, packageChunk, chunkEntry.parent().getId() - 1, resourceEntry,
typeCount);
blameFromTypeChunkEntry(chunkEntry);
}
blamePackage(packageChunk, resourceEntry);
}
Multimaps.invertFrom(entries, typeEntryToBlame);
for (TypeChunk.Entry entry : typeEntryToBlame.keySet()) {
blameFromTypeChunkEntry(entry);
}
}
private void blameKeyOrType(Map<PackageChunk, List<ResourceEntry>[]> keyOrType,
PackageChunk packageChunk, int keyIndex, ResourceEntry entry, int entryCount) {
if (!keyOrType.containsKey(packageChunk)) {
keyOrType.put(packageChunk, createEntryListArray(entryCount));
}
keyOrType.get(packageChunk)[keyIndex].add(entry);
}
private void blamePackage(PackageChunk packageChunk, ResourceEntry entry) {
packageToBlame.put(packageChunk, entry);
}
private void blameFromTypeChunkEntry(TypeChunk.Entry chunkEntry) {
for (BinaryResourceValue value : getAllResourceValues(chunkEntry)) {
for (ResourceEntry entry : typeEntryToBlame.get(chunkEntry)) {
switch (value.type()) {
case STRING:
blameString(value.data(), entry);
break;
default:
break;
}
}
}
}
/**
* Returns all {@link BinaryResourceValue} for a single {@code entry}.
*/
private Collection<BinaryResourceValue> getAllResourceValues(TypeChunk.Entry entry) {
Set<BinaryResourceValue> values = new HashSet<BinaryResourceValue>();
BinaryResourceValue binaryResourceValue = entry.value();
if (binaryResourceValue != null) {
values.add(binaryResourceValue);
}
for (BinaryResourceValue value : entry.values().values()) {
values.add(value);
}
return values;
}
private void blameString(int stringIndex, ResourceEntry entry) {
stringToBlame[stringIndex].add(entry);
}
/**
* Must first call {@link #blame}.
*/
public Map<PackageChunk, List<ResourceEntry>[]> getKeyToBlamedResources() {
return Collections.unmodifiableMap(keyToBlame);
}
/**
* Must first call {@link #blame}.
*/
public Map<PackageChunk, List<ResourceEntry>[]> getTypeToBlamedResources() {
return Collections.unmodifiableMap(typeToBlame);
}
/**
* Must first call {@link #blame}.
*/
public Multimap<PackageChunk, ResourceEntry> getPackageToBlamedResources() {
return Multimaps.unmodifiableMultimap(packageToBlame);
}
/**
* Must first call {@link #blame}.
*/
public List<ResourceEntry>[] getStringToBlamedResources() {
return stringToBlame;
}
/**
* Must first call {@link #blame}.
*/
public Multimap<TypeChunk.Entry, ResourceEntry> getTypeEntryToBlamedResources() {
return Multimaps.unmodifiableMultimap(typeEntryToBlame);
}
/**
* Returns a multimap of keys for which there is no default resource.
*/
public Multimap<ResourceEntry, TypeChunk.Entry> getBaselessKeys() {
if (baselessKeys != null) {
return baselessKeys;
}
Multimap<ResourceEntry, TypeChunk.Entry> result = HashMultimap.create();
for (Entry<ResourceEntry, Collection<TypeChunk.Entry>> entry
: getResourceEntries().asMap().entrySet()) {
Collection<TypeChunk.Entry> chunkEntries = entry.getValue();
if (!hasBaseConfiguration(chunkEntries)) {
result.putAll(entry.getKey(), chunkEntries);
}
}
baselessKeys = result;
return result;
}
/**
* Returns a multimap of resource entries to the chunk entries they reference in this APK.
*/
public Multimap<ResourceEntry, TypeChunk.Entry> getResourceEntries() {
if (resourceEntries != null) {
return resourceEntries;
}
Multimap<ResourceEntry, TypeChunk.Entry> result = HashMultimap.create();
for (TypeChunk typeChunk : getTypeChunks()) {
for (TypeChunk.Entry entry : typeChunk.getEntries().values()) {
result.put(ResourceEntry.create(entry), entry);
}
}
resourceEntries = result;
return result;
}
/**
* Returns all {@link TypeChunk} in resources.arsc.
*/
public List<TypeChunk> getTypeChunks() {
if (typeChunks != null) {
return typeChunks;
}
List<TypeChunk> result = new ArrayList<>();
for (PackageChunk packageChunk : resourceTable.getPackages()) {
for (TypeChunk typeChunk : packageChunk.getTypeChunks()) {
result.add(typeChunk);
}
}
typeChunks = result;
return result;
}
private boolean hasBaseConfiguration(Collection<TypeChunk.Entry> entries) {
for (TypeChunk.Entry entry : entries) {
if (entry.parent().getConfiguration().isDefault()) {
return true;
}
}
return false;
}
/**
* Allows creation of concrete parameterized type arr {@link ArscBlamer#createEntryListArray}.
*/
private static class ArrayListResourceEntry extends ArrayList<ResourceEntry> {
private ArrayListResourceEntry() {
super(2); // ~90-95% of these lists end up with only 1 or 2 elements.
}
}
/**
* Describes a single resource entry.
*/
public static class ResourceEntry {
private final String packageName;
private final String typeName;
private final String entryName;
private ResourceEntry(String packageName, String typeName, String entryName) {
this.packageName = packageName;
this.typeName = typeName;
this.entryName = entryName;
}
static ResourceEntry create(TypeChunk.Entry entry) {
PackageChunk packageChunk = Preconditions.checkNotNull(entry.parent().getPackageChunk());
String packageName = packageChunk.getPackageName();
String typeName = entry.typeName();
String entryName = entry.key();
return new ResourceEntry(packageName, typeName, entryName);
}
public String packageName() {
return packageName;
}
public String typeName() {
return typeName;
}
public String entryName() {
return entryName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ResourceEntry that = (ResourceEntry) o;
return Objects.equals(packageName, that.packageName) &&
Objects.equals(typeName, that.typeName) &&
Objects.equals(entryName, that.entryName);
}
@Override
public int hashCode() {
return Objects.hash(packageName, typeName, entryName);
}
}
}
@@ -0,0 +1,726 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedBytes;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
import static java.nio.charset.StandardCharsets.US_ASCII;
/**
* Describes a particular resource configuration.
*/
public class BinaryResourceConfiguration implements SerializableResource {
/**
* The below constants are from android.content.res.Configuration.
*/
private static final int DENSITY_DPI_UNDEFINED = 0;
private static final int DENSITY_DPI_LDPI = 120;
private static final int DENSITY_DPI_MDPI = 160;
private static final int DENSITY_DPI_TVDPI = 213;
private static final int DENSITY_DPI_HDPI = 240;
private static final int DENSITY_DPI_XHDPI = 320;
private static final int DENSITY_DPI_XXHDPI = 480;
private static final int DENSITY_DPI_XXXHDPI = 640;
private static final int DENSITY_DPI_ANY = 0xFFFE;
private static final int DENSITY_DPI_NONE = 0xFFFF;
private static final Map<Integer, String> DENSITY_DPI_VALUES =
ImmutableMap.<Integer, String>builder()
.put(DENSITY_DPI_UNDEFINED, "")
.put(DENSITY_DPI_LDPI, "ldpi")
.put(DENSITY_DPI_MDPI, "mdpi")
.put(DENSITY_DPI_TVDPI, "tvdpi")
.put(DENSITY_DPI_HDPI, "hdpi")
.put(DENSITY_DPI_XHDPI, "xhdpi")
.put(DENSITY_DPI_XXHDPI, "xxhdpi")
.put(DENSITY_DPI_XXXHDPI, "xxxhdpi")
.put(DENSITY_DPI_ANY, "anydpi")
.put(DENSITY_DPI_NONE, "nodpi")
.build();
private static final int KEYBOARD_NOKEYS = 1;
private static final int KEYBOARD_QWERTY = 2;
private static final int KEYBOARD_12KEY = 3;
private static final Map<Integer, String> KEYBOARD_VALUES = ImmutableMap.of(
KEYBOARD_NOKEYS, "nokeys",
KEYBOARD_QWERTY, "qwerty",
KEYBOARD_12KEY, "12key");
private static final int KEYBOARDHIDDEN_MASK = 0x03;
private static final int KEYBOARDHIDDEN_NO = 1;
private static final int KEYBOARDHIDDEN_YES = 2;
private static final int KEYBOARDHIDDEN_SOFT = 3;
private static final Map<Integer, String> KEYBOARDHIDDEN_VALUES = ImmutableMap.of(
KEYBOARDHIDDEN_NO, "keysexposed",
KEYBOARDHIDDEN_YES, "keyshidden",
KEYBOARDHIDDEN_SOFT, "keyssoft");
private static final int NAVIGATION_NONAV = 1;
private static final int NAVIGATION_DPAD = 2;
private static final int NAVIGATION_TRACKBALL = 3;
private static final int NAVIGATION_WHEEL = 4;
private static final Map<Integer, String> NAVIGATION_VALUES = ImmutableMap.of(
NAVIGATION_NONAV, "nonav",
NAVIGATION_DPAD, "dpad",
NAVIGATION_TRACKBALL, "trackball",
NAVIGATION_WHEEL, "wheel");
private static final int NAVIGATIONHIDDEN_MASK = 0x0C;
private static final int NAVIGATIONHIDDEN_NO = 0x04;
private static final int NAVIGATIONHIDDEN_YES = 0x08;
private static final Map<Integer, String> NAVIGATIONHIDDEN_VALUES = ImmutableMap.of(
NAVIGATIONHIDDEN_NO, "navexposed",
NAVIGATIONHIDDEN_YES, "navhidden");
private static final int ORIENTATION_PORTRAIT = 0x01;
private static final int ORIENTATION_LANDSCAPE = 0x02;
private static final Map<Integer, String> ORIENTATION_VALUES = ImmutableMap.of(
ORIENTATION_PORTRAIT, "port",
ORIENTATION_LANDSCAPE, "land");
private static final int SCREENLAYOUT_LAYOUTDIR_MASK = 0xC0;
private static final int SCREENLAYOUT_LAYOUTDIR_LTR = 0x40;
private static final int SCREENLAYOUT_LAYOUTDIR_RTL = 0x80;
private static final Map<Integer, String> SCREENLAYOUT_LAYOUTDIR_VALUES = ImmutableMap.of(
SCREENLAYOUT_LAYOUTDIR_LTR, "ldltr",
SCREENLAYOUT_LAYOUTDIR_RTL, "ldrtl");
private static final int SCREENLAYOUT_LONG_MASK = 0x30;
private static final int SCREENLAYOUT_LONG_NO = 0x10;
private static final int SCREENLAYOUT_LONG_YES = 0x20;
private static final Map<Integer, String> SCREENLAYOUT_LONG_VALUES = ImmutableMap.of(
SCREENLAYOUT_LONG_NO, "notlong",
SCREENLAYOUT_LONG_YES, "long");
private static final int SCREENLAYOUT_ROUND_MASK = 0x03;
private static final int SCREENLAYOUT_ROUND_NO = 0x01;
private static final int SCREENLAYOUT_ROUND_YES = 0x02;
private static final Map<Integer, String> SCREENLAYOUT_ROUND_VALUES = ImmutableMap.of(
SCREENLAYOUT_ROUND_NO, "notround",
SCREENLAYOUT_ROUND_YES, "round");
private static final int SCREENLAYOUT_SIZE_MASK = 0x0F;
private static final int SCREENLAYOUT_SIZE_SMALL = 0x01;
private static final int SCREENLAYOUT_SIZE_NORMAL = 0x02;
private static final int SCREENLAYOUT_SIZE_LARGE = 0x03;
private static final int SCREENLAYOUT_SIZE_XLARGE = 0x04;
private static final Map<Integer, String> SCREENLAYOUT_SIZE_VALUES = ImmutableMap.of(
SCREENLAYOUT_SIZE_SMALL, "small",
SCREENLAYOUT_SIZE_NORMAL, "normal",
SCREENLAYOUT_SIZE_LARGE, "large",
SCREENLAYOUT_SIZE_XLARGE, "xlarge");
private static final int TOUCHSCREEN_NOTOUCH = 1;
private static final int TOUCHSCREEN_FINGER = 3;
private static final Map<Integer, String> TOUCHSCREEN_VALUES = ImmutableMap.of(
TOUCHSCREEN_NOTOUCH, "notouch",
TOUCHSCREEN_FINGER, "finger");
private static final int UI_MODE_NIGHT_MASK = 0x30;
private static final int UI_MODE_NIGHT_NO = 0x10;
private static final int UI_MODE_NIGHT_YES = 0x20;
private static final Map<Integer, String> UI_MODE_NIGHT_VALUES = ImmutableMap.of(
UI_MODE_NIGHT_NO, "notnight",
UI_MODE_NIGHT_YES, "night");
private static final int UI_MODE_TYPE_MASK = 0x0F;
private static final int UI_MODE_TYPE_DESK = 0x02;
private static final int UI_MODE_TYPE_CAR = 0x03;
private static final int UI_MODE_TYPE_TELEVISION = 0x04;
private static final int UI_MODE_TYPE_APPLIANCE = 0x05;
private static final int UI_MODE_TYPE_WATCH = 0x06;
private static final int UI_MODE_TYPE_VR_HEADSET = 0x07;
// start - miui
private static final int UI_MODE_TYPE_GODZILLAUI = 0x0b;
private static final int UI_MODE_TYPE_SMALLUI = 0x0c;
private static final int UI_MODE_TYPE_MEDIUMUI = 0x0d;
private static final int UI_MODE_TYPE_LARGEUI = 0x0e;
private static final int UI_MODE_TYPE_HUGEUI = 0x0f;
private static final Map<Integer, String> UI_MODE_TYPE_VALUES =
ImmutableMap.<Integer, String>builder()
.put(UI_MODE_TYPE_DESK, "desk")
.put(UI_MODE_TYPE_CAR, "car")
.put(UI_MODE_TYPE_TELEVISION, "television")
.put(UI_MODE_TYPE_APPLIANCE, "appliance")
.put(UI_MODE_TYPE_WATCH, "watch")
.put(UI_MODE_TYPE_VR_HEADSET, "vrheadset")
.put(UI_MODE_TYPE_GODZILLAUI, "godzillaui")
.put(UI_MODE_TYPE_SMALLUI, "smallui")
.put(UI_MODE_TYPE_MEDIUMUI, "mediumui")
.put(UI_MODE_TYPE_LARGEUI, "largeui")
.put(UI_MODE_TYPE_HUGEUI, "hugeui").build();
/**
* The minimum size in bytes that this configuration must be to contain screen config info.
*/
private static final int SCREEN_CONFIG_MIN_SIZE = 32;
/**
* The minimum size in bytes that this configuration must be to contain screen dp info.
*/
private static final int SCREEN_DP_MIN_SIZE = 36;
/**
* The minimum size in bytes that this configuration must be to contain locale info.
*/
private static final int LOCALE_MIN_SIZE = 48;
/**
* The minimum size in bytes that this config must be to contain the screenConfig extension.
*/
private static final int SCREEN_CONFIG_EXTENSION_MIN_SIZE = 52;
private final int size;
private final int mcc;
private final int mnc;
private final byte[] language;
private final byte[] region;
private final int orientation;
private final int touchscreen;
private final int density;
private final int keyboard;
private final int navigation;
private final int inputFlags;
private final int screenWidth;
private final int screenHeight;
private final int sdkVersion;
private final int minorVersion;
private final int screenLayout;
private final int uiMode;
private final int smallestScreenWidthDp;
private final int screenWidthDp;
private final int screenHeightDp;
private final byte[] localeScript;
private final byte[] localeVariant;
// end - miui
private final int screenLayout2;
private final byte[] unknown;
private BinaryResourceConfiguration(int size,
int mcc,
int mnc,
byte[] language,
byte[] region,
int orientation,
int touchscreen,
int density,
int keyboard,
int navigation,
int inputFlags,
int screenWidth,
int screenHeight,
int sdkVersion,
int minorVersion,
int screenLayout,
int uiMode,
int smallestScreenWidthDp,
int screenWidthDp,
int screenHeightDp,
byte[] localeScript,
byte[] localeVariant,
int screenLayout2,
byte[] unknown) {
this.size = size;
this.mcc = mcc;
this.mnc = mnc;
this.language = language;
this.region = region;
this.orientation = orientation;
this.touchscreen = touchscreen;
this.density = density;
this.keyboard = keyboard;
this.navigation = navigation;
this.inputFlags = inputFlags;
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.sdkVersion = sdkVersion;
this.minorVersion = minorVersion;
this.screenLayout = screenLayout;
this.uiMode = uiMode;
this.smallestScreenWidthDp = smallestScreenWidthDp;
this.screenWidthDp = screenWidthDp;
this.screenHeightDp = screenHeightDp;
this.localeScript = localeScript;
this.localeVariant = localeVariant;
this.screenLayout2 = screenLayout2;
this.unknown = unknown;
}
static BinaryResourceConfiguration create(ByteBuffer buffer) {
int startPosition = buffer.position(); // The starting buffer position to calculate bytes read.
int size = buffer.getInt();
int mcc = buffer.getShort() & 0xFFFF;
int mnc = buffer.getShort() & 0xFFFF;
byte[] language = new byte[2];
buffer.get(language);
byte[] region = new byte[2];
buffer.get(region);
int orientation = UnsignedBytes.toInt(buffer.get());
int touchscreen = UnsignedBytes.toInt(buffer.get());
int density = buffer.getShort() & 0xFFFF;
int keyboard = UnsignedBytes.toInt(buffer.get());
int navigation = UnsignedBytes.toInt(buffer.get());
int inputFlags = UnsignedBytes.toInt(buffer.get());
buffer.get(); // 1 byte of padding
int screenWidth = buffer.getShort() & 0xFFFF;
int screenHeight = buffer.getShort() & 0xFFFF;
int sdkVersion = buffer.getShort() & 0xFFFF;
int minorVersion = buffer.getShort() & 0xFFFF;
// At this point, the configuration's size needs to be taken into account as not all
// configurations have all values.
int screenLayout = 0;
int uiMode = 0;
int smallestScreenWidthDp = 0;
int screenWidthDp = 0;
int screenHeightDp = 0;
byte[] localeScript = new byte[4];
byte[] localeVariant = new byte[8];
int screenLayout2 = 0;
if (size >= SCREEN_CONFIG_MIN_SIZE) {
screenLayout = UnsignedBytes.toInt(buffer.get());
uiMode = UnsignedBytes.toInt(buffer.get());
smallestScreenWidthDp = buffer.getShort() & 0xFFFF;
}
if (size >= SCREEN_DP_MIN_SIZE) {
screenWidthDp = buffer.getShort() & 0xFFFF;
screenHeightDp = buffer.getShort() & 0xFFFF;
}
if (size >= LOCALE_MIN_SIZE) {
buffer.get(localeScript);
buffer.get(localeVariant);
}
if (size >= SCREEN_CONFIG_EXTENSION_MIN_SIZE) {
screenLayout2 = UnsignedBytes.toInt(buffer.get());
buffer.get(); // Reserved padding
buffer.getShort(); // More reserved padding
}
// After parsing everything that's known, account for anything that's unknown.
int bytesRead = buffer.position() - startPosition;
byte[] unknown = new byte[size - bytesRead];
buffer.get(unknown);
return new BinaryResourceConfiguration(size, mcc, mnc, language, region, orientation,
touchscreen, density, keyboard, navigation, inputFlags, screenWidth, screenHeight,
sdkVersion, minorVersion, screenLayout, uiMode, smallestScreenWidthDp, screenWidthDp,
screenHeightDp, localeScript, localeVariant, screenLayout2, unknown);
}
/**
* The number of bytes that this resource configuration takes up.
*/
public int size() {
return size;
}
public int mcc() {
return mcc;
}
public int mnc() {
return mnc;
}
/**
* Returns a packed 2-byte language code.
*/
@SuppressWarnings("mutable")
public byte[] language() {
return language;
}
/**
* Returns {@link #language} as an unpacked string representation.
*/
public final String languageString() {
return unpackLanguage();
}
/**
* Returns a packed 2-byte region code.
*/
@SuppressWarnings("mutable")
public byte[] region() {
return region;
}
/**
* Returns {@link #region} as an unpacked string representation.
*/
public final String regionString() {
return unpackRegion();
}
public int orientation() {
return orientation;
}
public int touchscreen() {
return touchscreen;
}
public int density() {
return density;
}
public int keyboard() {
return keyboard;
}
public int navigation() {
return navigation;
}
public int inputFlags() {
return inputFlags;
}
public final int keyboardHidden() {
return inputFlags() & KEYBOARDHIDDEN_MASK;
}
public final int navigationHidden() {
return inputFlags() & NAVIGATIONHIDDEN_MASK;
}
public int screenWidth() {
return screenWidth;
}
public int screenHeight() {
return screenHeight;
}
public int sdkVersion() {
return sdkVersion;
}
/**
* Returns a copy of this resource configuration with a different {@link #sdkVersion}, or this
* configuration if the {@code sdkVersion} is the same.
*
* @param sdkVersion The SDK version of the returned configuration.
* @return A copy of this configuration with the only difference being #sdkVersion.
*/
public final BinaryResourceConfiguration withSdkVersion(int sdkVersion) {
if (sdkVersion == sdkVersion()) {
return this;
}
return new BinaryResourceConfiguration(size(), mcc(), mnc(), language(), region(),
orientation(), touchscreen(), density(), keyboard(), navigation(), inputFlags(),
screenWidth(), screenHeight(), sdkVersion, minorVersion(), screenLayout(), uiMode(),
smallestScreenWidthDp(), screenWidthDp(), screenHeightDp(), localeScript(), localeVariant(),
screenLayout2(), unknown());
}
public int minorVersion() {
return minorVersion;
}
public int screenLayout() {
return screenLayout;
}
public final int screenLayoutDirection() {
return screenLayout() & SCREENLAYOUT_LAYOUTDIR_MASK;
}
public final int screenLayoutSize() {
return screenLayout() & SCREENLAYOUT_SIZE_MASK;
}
public final int screenLayoutLong() {
return screenLayout() & SCREENLAYOUT_LONG_MASK;
}
public final int screenLayoutRound() {
return screenLayout2() & SCREENLAYOUT_ROUND_MASK;
}
public int uiMode() {
return uiMode;
}
public final int uiModeType() {
return uiMode() & UI_MODE_TYPE_MASK;
}
public final int uiModeNight() {
return uiMode() & UI_MODE_NIGHT_MASK;
}
public int smallestScreenWidthDp() {
return smallestScreenWidthDp;
}
public int screenWidthDp() {
return screenWidthDp;
}
public int screenHeightDp() {
return screenHeightDp;
}
/**
* The ISO-15924 short name for the script corresponding to this configuration.
*/
@SuppressWarnings("mutable")
public byte[] localeScript() {
return localeScript;
}
/**
* A single BCP-47 variant subtag.
*/
@SuppressWarnings("mutable")
public byte[] localeVariant() {
return localeVariant;
}
/**
* An extension to {@link #screenLayout}. Contains round/notround qualifier.
*/
public int screenLayout2() {
return screenLayout2;
}
/**
* Any remaining bytes in this resource configuration that are unaccounted for.
*/
@SuppressWarnings("mutable")
public byte[] unknown() {
return unknown;
}
private String unpackLanguage() {
return unpackLanguageOrRegion(language(), 0x61);
}
private String unpackRegion() {
return unpackLanguageOrRegion(region(), 0x30);
}
private String unpackLanguageOrRegion(byte[] value, int base) {
Preconditions.checkState(value.length == 2, "Language or region value must be 2 bytes.");
if (value[0] == 0 && value[1] == 0) {
return "";
}
if ((UnsignedBytes.toInt(value[0]) & 0x80) != 0) {
byte[] result = new byte[3];
result[0] = (byte) (base + (value[1] & 0x1F));
result[1] = (byte) (base + ((value[1] & 0xE0) >>> 5) + ((value[0] & 0x03) << 3));
result[2] = (byte) (base + ((value[0] & 0x7C) >>> 2));
return new String(result, US_ASCII);
}
return new String(value, US_ASCII);
}
/**
* Returns true if this is the default "any" configuration.
*/
public final boolean isDefault() {
return mcc() == 0
&& mnc() == 0
&& Arrays.equals(language(), new byte[2])
&& Arrays.equals(region(), new byte[2])
&& orientation() == 0
&& touchscreen() == 0
&& density() == 0
&& keyboard() == 0
&& navigation() == 0
&& inputFlags() == 0
&& screenWidth() == 0
&& screenHeight() == 0
&& sdkVersion() == 0
&& minorVersion() == 0
&& screenLayout() == 0
&& uiMode() == 0
&& smallestScreenWidthDp() == 0
&& screenWidthDp() == 0
&& screenHeightDp() == 0
&& Arrays.equals(localeScript(), new byte[4])
&& Arrays.equals(localeVariant(), new byte[8])
&& screenLayout2() == 0;
}
@Override
public final byte[] toByteArray() {
return toByteArray(false);
}
@Override
public final byte[] toByteArray(boolean shrink) {
ByteBuffer buffer = ByteBuffer.allocate(size()).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(size());
buffer.putShort((short) mcc());
buffer.putShort((short) mnc());
buffer.put(language());
buffer.put(region());
buffer.put((byte) orientation());
buffer.put((byte) touchscreen());
buffer.putShort((short) density());
buffer.put((byte) keyboard());
buffer.put((byte) navigation());
buffer.put((byte) inputFlags());
buffer.put((byte) 0); // Padding
buffer.putShort((short) screenWidth());
buffer.putShort((short) screenHeight());
buffer.putShort((short) sdkVersion());
buffer.putShort((short) minorVersion());
if (size() >= SCREEN_CONFIG_MIN_SIZE) {
buffer.put((byte) screenLayout());
buffer.put((byte) uiMode());
buffer.putShort((short) smallestScreenWidthDp());
}
if (size() >= SCREEN_DP_MIN_SIZE) {
buffer.putShort((short) screenWidthDp());
buffer.putShort((short) screenHeightDp());
}
if (size() >= LOCALE_MIN_SIZE) {
buffer.put(localeScript());
buffer.put(localeVariant());
}
if (size() >= SCREEN_CONFIG_EXTENSION_MIN_SIZE) {
buffer.putInt(screenLayout2()); // Writing an unsigned byte + 3 padding
}
buffer.put(unknown());
return buffer.array();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BinaryResourceConfiguration that = (BinaryResourceConfiguration) o;
return size == that.size &&
mcc == that.mcc &&
mnc == that.mnc &&
orientation == that.orientation &&
touchscreen == that.touchscreen &&
density == that.density &&
keyboard == that.keyboard &&
navigation == that.navigation &&
inputFlags == that.inputFlags &&
screenWidth == that.screenWidth &&
screenHeight == that.screenHeight &&
sdkVersion == that.sdkVersion &&
minorVersion == that.minorVersion &&
screenLayout == that.screenLayout &&
uiMode == that.uiMode &&
smallestScreenWidthDp == that.smallestScreenWidthDp &&
screenWidthDp == that.screenWidthDp &&
screenHeightDp == that.screenHeightDp &&
screenLayout2 == that.screenLayout2 &&
Arrays.equals(language, that.language) &&
Arrays.equals(region, that.region) &&
Arrays.equals(localeScript, that.localeScript) &&
Arrays.equals(localeVariant, that.localeVariant) &&
Arrays.equals(unknown, that.unknown);
}
@Override
public int hashCode() {
return Objects
.hash(size, mcc, mnc, Arrays.hashCode(language), Arrays.hashCode(region), orientation, touchscreen, density, keyboard, navigation, inputFlags, screenWidth,
screenHeight,
sdkVersion, minorVersion, screenLayout, uiMode, smallestScreenWidthDp, screenWidthDp, screenHeightDp, Arrays.hashCode(localeScript),
Arrays.hashCode(localeVariant),
screenLayout2, Arrays.hashCode(unknown));
}
@Override
public final String toString() {
if (isDefault()) { // Prevent the default configuration from returning the empty string
return "default";
}
Collection<String> parts = toStringParts().values();
parts.removeAll(Collections.singleton(""));
return Joiner.on('-').join(parts);
}
/**
* Returns a map of the configuration parts for {@link #toString}.
*
* <p>If a configuration part is not defined for this {@link BinaryResourceConfiguration}, its value
* will be the empty string.
*/
public final Map<Type, String> toStringParts() {
Map<Type, String> result = new LinkedHashMap<>(); // Preserve order for #toString().
result.put(Type.MCC, mcc() != 0 ? "mcc" + mcc() : "");
result.put(Type.MNC, mnc() != 0 ? "mnc" + mnc() : "");
result.put(Type.LANGUAGE_STRING, !languageString().isEmpty() ? languageString() : "");
result.put(Type.REGION_STRING, !regionString().isEmpty() ? "r" + regionString() : "");
result.put(Type.SCREEN_LAYOUT_DIRECTION,
getOrDefault(SCREENLAYOUT_LAYOUTDIR_VALUES, screenLayoutDirection(), ""));
result.put(Type.SMALLEST_SCREEN_WIDTH_DP,
smallestScreenWidthDp() != 0 ? "sw" + smallestScreenWidthDp() + "dp" : "");
result.put(Type.SCREEN_WIDTH_DP, screenWidthDp() != 0 ? "w" + screenWidthDp() + "dp" : "");
result.put(Type.SCREEN_HEIGHT_DP, screenHeightDp() != 0 ? "h" + screenHeightDp() + "dp" : "");
result.put(Type.SCREEN_LAYOUT_SIZE,
getOrDefault(SCREENLAYOUT_SIZE_VALUES, screenLayoutSize(), ""));
result.put(Type.SCREEN_LAYOUT_LONG,
getOrDefault(SCREENLAYOUT_LONG_VALUES, screenLayoutLong(), ""));
result.put(Type.SCREEN_LAYOUT_ROUND,
getOrDefault(SCREENLAYOUT_ROUND_VALUES, screenLayoutRound(), ""));
result.put(Type.ORIENTATION, getOrDefault(ORIENTATION_VALUES, orientation(), ""));
result.put(Type.UI_MODE_TYPE, getOrDefault(UI_MODE_TYPE_VALUES, uiModeType(), ""));
result.put(Type.UI_MODE_NIGHT, getOrDefault(UI_MODE_NIGHT_VALUES, uiModeNight(), ""));
result.put(Type.DENSITY_DPI, getOrDefault(DENSITY_DPI_VALUES, density(), density() + "dpi"));
result.put(Type.TOUCHSCREEN, getOrDefault(TOUCHSCREEN_VALUES, touchscreen(), ""));
result.put(Type.KEYBOARD_HIDDEN, getOrDefault(KEYBOARDHIDDEN_VALUES, keyboardHidden(), ""));
result.put(Type.KEYBOARD, getOrDefault(KEYBOARD_VALUES, keyboard(), ""));
result.put(Type.NAVIGATION_HIDDEN,
getOrDefault(NAVIGATIONHIDDEN_VALUES, navigationHidden(), ""));
result.put(Type.NAVIGATION, getOrDefault(NAVIGATION_VALUES, navigation(), ""));
result.put(Type.SDK_VERSION, sdkVersion() != 0 ? "v" + sdkVersion() : "");
return result;
}
private <K, V> V getOrDefault(Map<K, V> map, K key, V defaultValue) {
// TODO(acornwall): Remove this when Java 8's Map#getOrDefault is available.
// Null is not returned, even if the map contains a key whose value is null. This is intended.
V value = map.get(key);
return value != null ? value : defaultValue;
}
/**
* The different types of configs that can be present in a {@link BinaryResourceConfiguration}.
*/
public enum Type {
MCC,
MNC,
LANGUAGE_STRING,
REGION_STRING,
SCREEN_LAYOUT_DIRECTION,
SMALLEST_SCREEN_WIDTH_DP,
SCREEN_WIDTH_DP,
SCREEN_HEIGHT_DP,
SCREEN_LAYOUT_SIZE,
SCREEN_LAYOUT_LONG,
SCREEN_LAYOUT_ROUND,
ORIENTATION,
UI_MODE_TYPE,
UI_MODE_NIGHT,
DENSITY_DPI,
TOUCHSCREEN,
KEYBOARD_HIDDEN,
KEYBOARD,
NAVIGATION_HIDDEN,
NAVIGATION,
SDK_VERSION
}
}
@@ -0,0 +1,80 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Given an arsc file, maps the contents of the file.
*/
public final class BinaryResourceFile implements SerializableResource {
/**
* The chunks contained in this resource file.
*/
private final List<Chunk> chunks = new ArrayList<>();
public BinaryResourceFile(byte[] buf) {
ByteBuffer buffer = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN);
while (buffer.remaining() > 0) {
chunks.add(Chunk.newInstance(buffer));
}
}
/**
* Given an input stream, reads the stream until the end and returns a {@link BinaryResourceFile}
* representing the contents of the stream.
*
* @param is The input stream to read from.
* @return BinaryResourceFile represented by the @{link InputStream}.
* @throws IOException
*/
public static BinaryResourceFile fromInputStream(InputStream is) throws IOException {
byte[] buf = ByteStreams.toByteArray(is);
return new BinaryResourceFile(buf);
}
/**
* Returns the chunks in this resource file.
*/
public List<Chunk> getChunks() {
return Collections.unmodifiableList(chunks);
}
@Override
public byte[] toByteArray() throws IOException {
return toByteArray(false);
}
@Override
public byte[] toByteArray(boolean shrink) throws IOException {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
for (Chunk chunk : chunks) {
output.write(chunk.toByteArray(shrink));
}
return output.toByteArray();
}
}
@@ -0,0 +1,123 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import com.google.common.base.Preconditions;
import java.util.Objects;
/**
* Resources in a {@link ResourceTableChunk} are identified by an integer of the form 0xpptteeee,
* where pp is the {@link PackageChunk} id, tt is the {@link TypeChunk} id, and eeee is the index of
* the entry in the {@link TypeChunk}.
*/
public class BinaryResourceIdentifier {
/**
* The {@link PackageChunk} id mask for a packed resource id of the form 0xpptteeee.
*/
private static final int PACKAGE_ID_MASK = 0xFF000000;
private static final int PACKAGE_ID_SHIFT = 24;
/**
* The {@link TypeChunk} id mask for a packed resource id of the form 0xpptteeee.
*/
private static final int TYPE_ID_MASK = 0x00FF0000;
private static final int TYPE_ID_SHIFT = 16;
/**
* The {@link TypeChunk.Entry} id mask for a packed resource id of the form 0xpptteeee.
*/
private static final int ENTRY_ID_MASK = 0xFFFF;
private static final int ENTRY_ID_SHIFT = 0;
private final int packageId;
private final int typeId;
private final int entryId;
private BinaryResourceIdentifier(int packageId, int typeId, int entryId) {
this.packageId = packageId;
this.typeId = typeId;
this.entryId = entryId;
}
/**
* Returns a {@link BinaryResourceIdentifier} from a {@code resourceId} of the form 0xpptteeee.
*/
public static BinaryResourceIdentifier create(int resourceId) {
int packageId = (resourceId & PACKAGE_ID_MASK) >>> PACKAGE_ID_SHIFT;
int typeId = (resourceId & TYPE_ID_MASK) >>> TYPE_ID_SHIFT;
int entryId = (resourceId & ENTRY_ID_MASK) >>> ENTRY_ID_SHIFT;
return create(packageId, typeId, entryId);
}
/**
* Returns a {@link BinaryResourceIdentifier} with the given identifiers.
*/
public static BinaryResourceIdentifier create(int packageId, int typeId, int entryId) {
Preconditions.checkState((packageId & 0xFF) == packageId, "packageId must be <= 0xFF.");
Preconditions.checkState((typeId & 0xFF) == typeId, "typeId must be <= 0xFF.");
Preconditions.checkState((entryId & 0xFFFF) == entryId, "entryId must be <= 0xFFFF.");
return new BinaryResourceIdentifier(packageId, typeId, entryId);
}
/**
* The (1-based) id of the {@link PackageChunk} containing this resource.
*/
public int packageId() {
return packageId;
}
/**
* The (1-based) id of the {@link TypeChunk} containing this resource.
*/
public int typeId() {
return typeId;
}
/**
* The (0-based) index of the entry in a {@link TypeChunk} containing this resource.
*/
public int entryId() {
return entryId;
}
public int resId() {
return packageId << PACKAGE_ID_SHIFT | typeId << TYPE_ID_SHIFT | entryId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BinaryResourceIdentifier that = (BinaryResourceIdentifier) o;
return packageId == that.packageId &&
typeId == that.typeId &&
entryId == that.entryId;
}
@Override
public int hashCode() {
return Objects.hash(packageId, typeId, entryId);
}
@Override
public String toString() {
int v = packageId << PACKAGE_ID_SHIFT | typeId << TYPE_ID_SHIFT | entryId;
return String.format("0x%1$08x", v);
}
}
@@ -0,0 +1,169 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.UnsignedBytes;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import static java.nio.charset.StandardCharsets.UTF_16LE;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Provides utilities to decode/encode a String packed in an arsc resource file.
*/
public final class BinaryResourceString {
private BinaryResourceString() {
} // Private constructor
/**
* Given a buffer and an offset into the buffer, returns a String. The {@code offset} is the
* 0-based byte offset from the start of the buffer where the string resides. This should be the
* location in memory where the string's character count, followed by its byte count, and then
* followed by the actual string is located.
*
* <p>Here's an example UTF-8-encoded string of ab©:
* <pre>
* 03 04 61 62 C2 A9 00
* ^ Offset should be here
* </pre>
*
* @param buffer The buffer containing the string to decode.
* @param offset Offset into the buffer where the string resides.
* @param type The encoding type that the {@link BinaryResourceString} is encoded in.
* @return The decoded string.
*/
public static String decodeString(ByteBuffer buffer, int offset, Type type) {
int length;
int characterCount = decodeLength(buffer, offset, type);
offset += computeLengthOffset(characterCount, type);
// UTF-8 strings have 2 lengths: the number of characters, and then the encoding length.
// UTF-16 strings, however, only have 1 length: the number of characters.
if (type == Type.UTF8) {
length = decodeLength(buffer, offset, type);
offset += computeLengthOffset(length, type);
} else {
length = characterCount * 2;
}
return new String(buffer.array(), offset, length, type.charset());
}
/**
* Encodes a string in either UTF-8 or UTF-16 and returns the bytes of the encoded string.
* Strings are prefixed by 2 values. The first is the number of characters in the string.
* The second is the encoding length (number of bytes in the string).
*
* <p>Here's an example UTF-8-encoded string of ab©:
* <pre>03 04 61 62 C2 A9 00</pre>
*
* @param str The string to be encoded.
* @param type The encoding type that the {@link BinaryResourceString} should be encoded in.
* @return The encoded string.
*/
public static byte[] encodeString(String str, Type type) {
byte[] bytes = str.getBytes(type.charset());
// The extra 5 bytes is for metadata (character count + byte count) and the NULL terminator.
ByteArrayDataOutput output = ByteStreams.newDataOutput(bytes.length + 5);
encodeLength(output, str.length(), type);
if (type == Type.UTF8) { // Only UTF-8 strings have the encoding length.
encodeLength(output, bytes.length, type);
}
output.write(bytes);
// NULL-terminate the string
if (type == Type.UTF8) {
output.write(0);
} else {
output.writeShort(0);
}
return output.toByteArray();
}
private static void encodeLength(ByteArrayDataOutput output, int length, Type type) {
if (length < 0) {
output.write(0);
return;
}
if (type == Type.UTF8) {
if (length > 0x7F) {
output.write(((length & 0x7F00) >> 8) | 0x80);
}
output.write(length & 0xFF);
} else { // UTF-16
// TODO(acornwall): Replace output with a little-endian output.
if (length > 0x7FFF) {
int highBytes = ((length & 0x7FFF0000) >> 16) | 0x8000;
output.write(highBytes & 0xFF);
output.write((highBytes & 0xFF00) >> 8);
}
int lowBytes = length & 0xFFFF;
output.write(lowBytes & 0xFF);
output.write((lowBytes & 0xFF00) >> 8);
}
}
private static int computeLengthOffset(int length, Type type) {
return (type == Type.UTF8 ? 1 : 2) * (length >= (type == Type.UTF8 ? 0x80 : 0x8000) ? 2 : 1);
}
private static int decodeLength(ByteBuffer buffer, int offset, Type type) {
return type == Type.UTF8 ? decodeLengthUTF8(buffer, offset) : decodeLengthUTF16(buffer, offset);
}
private static int decodeLengthUTF8(ByteBuffer buffer, int offset) {
// UTF-8 strings use a clever variant of the 7-bit integer for packing the string length.
// If the first byte is >= 0x80, then a second byte follows. For these values, the length
// is WORD-length in big-endian & 0x7FFF.
int length = UnsignedBytes.toInt(buffer.get(offset));
if ((length & 0x80) != 0) {
length = ((length & 0x7F) << 8) | UnsignedBytes.toInt(buffer.get(offset + 1));
}
return length;
}
private static int decodeLengthUTF16(ByteBuffer buffer, int offset) {
// UTF-16 strings use a clever variant of the 7-bit integer for packing the string length.
// If the first word is >= 0x8000, then a second word follows. For these values, the length
// is DWORD-length in big-endian & 0x7FFFFFFF.
int length = (buffer.getShort(offset) & 0xFFFF);
if ((length & 0x8000) != 0) {
length = ((length & 0x7FFF) << 16) | (buffer.getShort(offset + 2) & 0xFFFF);
}
return length;
}
/**
* Type of {@link BinaryResourceString} to encode / decode.
*/
public enum Type {
UTF8(UTF_8),
UTF16(UTF_16LE);
private final Charset charset;
Type(Charset charset) {
this.charset = charset;
}
public Charset charset() {
return charset;
}
}
}
@@ -0,0 +1,199 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.primitives.UnsignedBytes;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Map;
import java.util.Objects;
/**
* Represents a single typed resource value.
*/
public class BinaryResourceValue implements SerializableResource {
/**
* The serialized size in bytes of a {@link BinaryResourceValue}.
*/
public static final int SIZE = 8;
public int size;
public Type type;
public int data;
public BinaryResourceValue(int size, Type type, int data) {
this.size = size;
this.type = type;
this.data = data;
}
public static BinaryResourceValue create(ByteBuffer buffer) {
int size = (buffer.getShort() & 0xFFFF);
buffer.get(); // Unused
Type type = Type.fromCode(buffer.get());
int data = buffer.getInt();
return new BinaryResourceValue(size, type, data);
}
/**
* The length in bytes of this value.
*/
public int size() {
return size;
}
/**
* The raw data type of this value.
*/
public Type type() {
return type;
}
/**
* The actual 4-byte value; interpretation of the value depends on {@code dataType}.
*/
public int data() {
return data;
}
@Override
public byte[] toByteArray() {
return toByteArray(false);
}
@Override
public byte[] toByteArray(boolean shrink) {
ByteBuffer buffer = ByteBuffer.allocate(SIZE).order(ByteOrder.LITTLE_ENDIAN);
buffer.putShort((short) size());
buffer.put((byte) 0); // Unused
buffer.put(type().code());
buffer.putInt(data());
return buffer.array();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BinaryResourceValue that = (BinaryResourceValue) o;
return size == that.size &&
data == that.data &&
type == that.type;
}
@Override
public int hashCode() {
return Objects.hash(size, type, data);
}
/**
* Resource type codes.
*/
public enum Type {
/**
* {@code data} is either 0 (undefined) or 1 (empty).
*/
NULL(0x00),
/**
* {@code data} holds a {@link ResourceTableChunk} entry reference.
*/
REFERENCE(0x01),
/**
* {@code data} holds an attribute resource identifier.
*/
ATTRIBUTE(0x02),
/**
* {@code data} holds an index into the containing resource table's string pool.
*/
STRING(0x03),
/**
* {@code data} holds a single-precision floating point number.
*/
FLOAT(0x04),
/**
* {@code data} holds a complex number encoding a dimension value, such as "100in".
*/
DIMENSION(0x05),
/**
* {@code data} holds a complex number encoding a fraction of a container.
*/
FRACTION(0x06),
/**
* {@code data} holds a dynamic {@link ResourceTableChunk} entry reference.
*/
DYNAMIC_REFERENCE(0x07),
/**
* {@code data} holds a dynamic attribute resource identifier.
*/
DYNAMIC_ATTRIBUTE(0x08),
/**
* {@code data} is a raw integer value of the form n..n.
*/
INT_DEC(0x10),
/**
* {@code data} is a raw integer value of the form 0xn..n.
*/
INT_HEX(0x11),
/**
* {@code data} is either 0 (false) or 1 (true).
*/
INT_BOOLEAN(0x12),
/**
* {@code data} is a raw integer value of the form #aarrggbb.
*/
INT_COLOR_ARGB8(0x1c),
/**
* {@code data} is a raw integer value of the form #rrggbb.
*/
INT_COLOR_RGB8(0x1d),
/**
* {@code data} is a raw integer value of the form #argb.
*/
INT_COLOR_ARGB4(0x1e),
/**
* {@code data} is a raw integer value of the form #rgb.
*/
INT_COLOR_RGB4(0x1f);
private static final Map<Byte, Type> FROM_BYTE;
static {
Builder<Byte, Type> builder = ImmutableMap.builder();
for (Type type : values()) {
builder.put(type.code(), type);
}
FROM_BYTE = builder.build();
}
private final byte code;
Type(int code) {
this.code = UnsignedBytes.checkedCast(code);
}
public static Type fromCode(byte code) {
return Preconditions.checkNotNull(FROM_BYTE.get(code), "Unknown resource type: %s", code);
}
public byte code() {
return code;
}
}
}
@@ -0,0 +1,319 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.io.LittleEndianDataOutputStream;
import com.google.common.primitives.Shorts;
import java.io.ByteArrayOutputStream;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Map;
/**
* Represents a generic chunk.
*/
public abstract class Chunk implements SerializableResource {
/**
* The byte boundary to pad chunks on.
*/
public static final int PAD_BOUNDARY = 4;
/**
* The number of bytes in every chunk that describes chunk type, header size, and chunk size.
*/
public static final int METADATA_SIZE = 8;
/**
* The offset in bytes, from the start of the chunk, where the chunk size can be found.
*/
private static final int CHUNK_SIZE_OFFSET = 4;
/**
* Size of the chunk header in bytes.
*/
protected final int headerSize;
/**
* headerSize + dataSize. The total size of this chunk.
*/
protected final int chunkSize;
/**
* Offset of this chunk from the start of the file.
*/
protected final int offset;
/**
* The parent to this chunk, if any.
*/
@Nullable
private final Chunk parent;
protected Chunk(ByteBuffer buffer, @Nullable Chunk parent) {
this.parent = parent;
offset = buffer.position() - 2;
headerSize = (buffer.getShort() & 0xFFFF);
chunkSize = buffer.getInt();
}
/**
* Creates a new chunk whose contents start at {@code buffer}'s current position.
*
* @param buffer A buffer positioned at the start of a chunk.
* @return new chunk
*/
public static Chunk newInstance(ByteBuffer buffer) {
return newInstance(buffer, null);
}
/**
* Creates a new chunk whose contents start at {@code buffer}'s current position.
*
* @param buffer A buffer positioned at the start of a chunk.
* @param parent The parent to this chunk (or null if there's no parent).
* @return new chunk
*/
public static Chunk newInstance(ByteBuffer buffer, @Nullable Chunk parent) {
Chunk result;
Type type = Type.fromCode(buffer.getShort());
switch (type) {
case STRING_POOL:
result = new StringPoolChunk(buffer, parent);
break;
case TABLE:
result = new ResourceTableChunk(buffer, parent);
break;
case XML:
result = new XmlChunk(buffer, parent);
break;
case XML_START_NAMESPACE:
result = new XmlNamespaceStartChunk(buffer, parent);
break;
case XML_END_NAMESPACE:
result = new XmlNamespaceEndChunk(buffer, parent);
break;
case XML_START_ELEMENT:
result = new XmlStartElementChunk(buffer, parent);
break;
case XML_END_ELEMENT:
result = new XmlEndElementChunk(buffer, parent);
break;
case XML_CDATA:
result = new XmlCdataChunk(buffer, parent);
break;
case XML_RESOURCE_MAP:
result = new XmlResourceMapChunk(buffer, parent);
break;
case TABLE_PACKAGE:
result = new PackageChunk(buffer, parent);
break;
case TABLE_TYPE:
result = new TypeChunk(buffer, parent);
break;
case TABLE_TYPE_SPEC:
result = new TypeSpecChunk(buffer, parent);
break;
case TABLE_LIBRARY:
result = new LibraryChunk(buffer, parent);
break;
default:
result = new UnknownChunk(buffer, parent);
}
result.init(buffer);
result.seekToEndOfChunk(buffer);
return result;
}
/**
* Finishes initialization of a chunk. This should be called immediately after the constructor.
* This is separate from the constructor so that the header of a chunk can be fully initialized
* before the payload of that chunk is initialized for chunks that require such behavior.
*
* @param buffer The buffer that the payload will be initialized from.
*/
protected void init(ByteBuffer buffer) {
}
/**
* Returns the parent to this chunk, if any. A parent is a chunk whose payload contains this
* chunk. If there's no parent, null is returned.
*/
@Nullable
public Chunk getParent() {
return parent;
}
protected abstract Type getType();
/**
* Returns the size of this chunk's header.
*/
public final int getHeaderSize() {
return headerSize;
}
/**
* Returns the size of this chunk when it was first read from a buffer. A chunk's size can deviate
* from this value when its data is modified (e.g. adding an entry, changing a string).
*
* <p>A chunk's current size can be determined from the length of the byte array returned from
* {@link #toByteArray}.
*/
public final int getOriginalChunkSize() {
return chunkSize;
}
/**
* Reposition the buffer after this chunk. Use this at the end of a Chunk constructor.
*
* @param buffer The buffer to be repositioned.
*/
private final void seekToEndOfChunk(ByteBuffer buffer) {
buffer.position(offset + chunkSize);
}
/**
* Writes the type and header size. We don't know how big this chunk will be (it could be
* different since the last time we checked), so this needs to be passed in.
*
* @param output The buffer that will be written to.
* @param chunkSize The total size of this chunk in bytes, including the header.
*/
protected final void writeHeader(ByteBuffer output, int chunkSize) {
int start = output.position();
output.putShort(getType().code());
output.putShort((short) headerSize);
output.putInt(chunkSize);
writeHeader(output);
int headerBytes = output.position() - start;
Preconditions.checkState(headerBytes == getHeaderSize(),
"Written header is wrong size. Got %s, want %s", headerBytes, getHeaderSize());
}
/**
* Writes the remaining header (after the type, {@code headerSize}, and {@code chunkSize}).
*
* @param output The buffer that the header will be written to.
*/
protected void writeHeader(ByteBuffer output) {
}
/**
* Writes the chunk payload. The payload is data in a chunk which is not in
* the first {@code headerSize} bytes of the chunk.
*
* @param output The stream that the payload will be written to.
* @param header The already-written header. This can be modified to fix payload offsets.
* @param shrink True if this payload should be optimized for size.
* @throws IOException Thrown if {@code output} could not be written to (out of memory).
*/
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
}
/**
* Pads {@code output} until {@code currentLength} is on a 4-byte boundary.
*
* @param output The {@link DataOutput} that will be padded.
* @param currentLength The current length, in bytes, of {@code output}
* @return The new length of {@code output}
* @throws IOException Thrown if {@code output} could not be written to.
*/
protected int writePad(DataOutput output, int currentLength) throws IOException {
while (currentLength % PAD_BOUNDARY != 0) {
output.write(0);
++currentLength;
}
return currentLength;
}
@Override
public final byte[] toByteArray() throws IOException {
return toByteArray(false);
}
/**
* Converts this chunk into an array of bytes representation. Normally you will not need to
* override this method unless your header changes based on the contents / size of the payload.
*/
@Override
public final byte[] toByteArray(boolean shrink) throws IOException {
ByteBuffer header = ByteBuffer.allocate(getHeaderSize()).order(ByteOrder.LITTLE_ENDIAN);
writeHeader(header, 0); // The chunk size isn't known yet. This will be filled in later.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (LittleEndianDataOutputStream payload = new LittleEndianDataOutputStream(baos)) {
writePayload(payload, header, shrink);
}
byte[] payloadBytes = baos.toByteArray();
int chunkSize = getHeaderSize() + payloadBytes.length;
header.putInt(CHUNK_SIZE_OFFSET, chunkSize);
// Combine results
ByteBuffer result = ByteBuffer.allocate(chunkSize).order(ByteOrder.LITTLE_ENDIAN);
result.put(header.array());
result.put(payloadBytes);
return result.array();
}
/**
* Types of chunks that can exist.
*/
public enum Type {
NULL(0x0000),
STRING_POOL(0x0001),
TABLE(0x0002),
XML(0x0003),
XML_START_NAMESPACE(0x0100),
XML_END_NAMESPACE(0x0101),
XML_START_ELEMENT(0x0102),
XML_END_ELEMENT(0x0103),
XML_CDATA(0x0104),
XML_RESOURCE_MAP(0x0180),
TABLE_PACKAGE(0x0200),
TABLE_TYPE(0x0201),
TABLE_TYPE_SPEC(0x0202),
TABLE_LIBRARY(0x0203);
private static final Map<Short, Type> FROM_SHORT;
static {
Builder<Short, Type> builder = ImmutableMap.builder();
for (Type type : values()) {
builder.put(type.code(), type);
}
FROM_SHORT = builder.build();
}
private final short code;
Type(int code) {
this.code = Shorts.checkedCast(code);
}
public static Type fromCode(short code) {
return Preconditions.checkNotNull(FROM_SHORT.get(code), "Unknown chunk type: %s", code);
}
public short code() {
return code;
}
}
}
@@ -0,0 +1,75 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Represents a chunk whose payload is a list of sub-chunks.
*/
public abstract class ChunkWithChunks extends Chunk {
private final Map<Integer, Chunk> chunks = new LinkedHashMap<>();
protected ChunkWithChunks(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
}
@Override
protected void init(ByteBuffer buffer) {
super.init(buffer);
chunks.clear();
int start = this.offset + getHeaderSize();
int offset = start;
int end = this.offset + getOriginalChunkSize();
int position = buffer.position();
buffer.position(start);
while (offset < end) {
Chunk chunk = Chunk.newInstance(buffer, this);
chunks.put(offset, chunk);
offset += chunk.getOriginalChunkSize();
}
buffer.position(position);
}
/**
* Retrieves the @{code chunks} contained in this chunk.
*
* @return map of buffer offset -> chunk contained in this chunk.
*/
public final Map<Integer, Chunk> getChunks() {
return chunks;
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
for (Chunk chunk : getChunks().values()) {
byte[] chunkBytes = chunk.toByteArray(shrink);
output.write(chunkBytes);
writePad(output, chunkBytes.length);
}
}
}
@@ -0,0 +1,153 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Contains a list of package-id to package name mappings for any shared libraries used in this
* {@link ResourceTableChunk}. The package-id's encoded in this resource table may be different
* than the id's assigned at runtime
*/
public final class LibraryChunk extends Chunk {
/**
* The number of resources of this type at creation time.
*/
private final int entryCount;
/**
* The libraries used in this chunk (package id + name).
*/
private final List<Entry> entries = new ArrayList<>();
LibraryChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
entryCount = buffer.getInt();
}
@Override
protected void init(ByteBuffer buffer) {
super.init(buffer);
entries.addAll(enumerateEntries(buffer));
}
private List<Entry> enumerateEntries(ByteBuffer buffer) {
List<Entry> result = new ArrayList<>(entryCount);
int offset = this.offset + getHeaderSize();
int endOffset = offset + Entry.SIZE * entryCount;
while (offset < endOffset) {
result.add(Entry.create(buffer, offset));
offset += Entry.SIZE;
}
return result;
}
@Override
protected Type getType() {
return Type.TABLE_LIBRARY;
}
@Override
protected void writeHeader(ByteBuffer output) {
super.writeHeader(output);
output.putInt(entries.size());
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
for (Entry entry : entries) {
output.write(entry.toByteArray(shrink));
}
}
/**
* A shared library package-id to package name entry.
*/
protected static class Entry implements SerializableResource {
/**
* Library entries only contain a package ID (4 bytes) and a package name.
*/
private static final int SIZE = 4 + PackageUtils.PACKAGE_NAME_SIZE;
private final int packageId;
private final String packageName;
private Entry(int packageId, String packageName) {
this.packageId = packageId;
this.packageName = packageName;
}
static Entry create(ByteBuffer buffer, int offset) {
int packageId = buffer.getInt(offset);
String packageName = PackageUtils.readPackageName(buffer, offset + 4);
return new Entry(packageId, packageName);
}
/**
* The id assigned to the shared library at build time.
*/
public int packageId() {
return packageId;
}
/**
* The package name of the shared library.
*/
public String packageName() {
return packageName;
}
@Override
public byte[] toByteArray() throws IOException {
return toByteArray(false);
}
@Override
public byte[] toByteArray(boolean shrink) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(SIZE).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(packageId());
PackageUtils.writePackageName(buffer, packageName());
return buffer.array();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Entry entry = (Entry) o;
return packageId == entry.packageId &&
Objects.equals(packageName, entry.packageName);
}
@Override
public int hashCode() {
return Objects.hash(packageId, packageName);
}
}
}
@@ -0,0 +1,269 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* A package chunk is a collection of resource data types within a package.
*/
public final class PackageChunk extends ChunkWithChunks {
/**
* Offset in bytes, from the start of the chunk, where {@code typeStringsOffset} can be found.
*/
private static final int TYPE_OFFSET_OFFSET = 268;
/**
* Offset in bytes, from the start of the chunk, where {@code keyStringsOffset} can be found.
*/
private static final int KEY_OFFSET_OFFSET = 276;
/**
* The offset (from {@code offset}) in the original buffer where type strings start.
*/
private final int typeStringsOffset;
/**
* The index into the type string pool of the last public type.
*/
private final int lastPublicType;
/**
* An offset to the string pool that contains the key strings for this package.
*/
private final int keyStringsOffset;
/**
* The index into the key string pool of the last public key.
*/
private final int lastPublicKey;
/**
* An offset to the type ID(s). This is undocumented in the original code.
*/
private final int typeIdOffset;
/**
* Contains a mapping of a type index to its {@link TypeSpecChunk}.
*/
private final Map<Integer, TypeSpecChunk> typeSpecs = new HashMap<>();
/**
* Contains a mapping of a type index to all of the {@link TypeChunk} with that index.
*/
private final Multimap<Integer, TypeChunk> types = ArrayListMultimap.create();
/**
* The package id if this is a base package, or 0 if not a base package.
*/
private int id;
/**
* The name of the package.
*/
private String packageName;
/**
* May contain a library chunk for mapping dynamic references to resolved references.
*/
private Optional<LibraryChunk> libraryChunk = Optional.empty();
PackageChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
id = buffer.getInt();
packageName = PackageUtils.readPackageName(buffer, buffer.position());
typeStringsOffset = buffer.getInt();
lastPublicType = buffer.getInt();
keyStringsOffset = buffer.getInt();
lastPublicKey = buffer.getInt();
typeIdOffset = buffer.getInt();
}
@Override
protected void init(ByteBuffer buffer) {
super.init(buffer);
for (Chunk chunk : getChunks().values()) {
if (chunk instanceof TypeChunk) {
TypeChunk typeChunk = (TypeChunk) chunk;
types.put(typeChunk.getId(), typeChunk);
} else if (chunk instanceof TypeSpecChunk) {
TypeSpecChunk typeSpecChunk = (TypeSpecChunk) chunk;
typeSpecs.put(typeSpecChunk.getId(), typeSpecChunk);
} else if (chunk instanceof LibraryChunk) {
if (libraryChunk.isPresent()) {
throw new IllegalStateException(
"Multiple library chunks present in package chunk.");
}
libraryChunk = Optional.of((LibraryChunk) chunk);
} else if (!(chunk instanceof StringPoolChunk)) {
throw new IllegalStateException(
String.format("PackageChunk contains an unexpected chunk: %s", chunk.getClass()));
}
}
}
/**
* Returns the package id if this is a base package, or 0 if not a base package.
*/
public int getId() {
return id;
}
/**
* Sets the package id
*/
public void setId(int id) {
this.id = id;
}
/**
* Returns the string pool that contains the names of the resources in this package.
*/
public StringPoolChunk getKeyStringPool() {
Chunk chunk = Preconditions.checkNotNull(getChunks().get(keyStringsOffset + offset));
Preconditions.checkState(chunk instanceof StringPoolChunk, "Key string pool not found.");
return (StringPoolChunk) chunk;
}
/**
* Get the type string for a specific id, e.g., (e.g. string, attr, id).
*
* @param id The id to get the type for.
* @return The type string.
*/
public String getTypeString(int id) {
StringPoolChunk typePool = getTypeStringPool();
Preconditions.checkNotNull(typePool, "Package has no type pool.");
Preconditions.checkState(typePool.getStyleCount() >= id, "No type for id: " + id);
return typePool.getString(id - 1); // - 1 here to convert to 0-based index
}
/**
* Returns the string pool that contains the type strings for this package, such as "layout",
* "string", "color".
*/
public StringPoolChunk getTypeStringPool() {
Chunk chunk = Preconditions.checkNotNull(getChunks().get(typeStringsOffset + offset));
Preconditions.checkState(chunk instanceof StringPoolChunk, "Type string pool not found.");
return (StringPoolChunk) chunk;
}
/**
* Returns all {@link TypeChunk} in this package.
*/
public Collection<TypeChunk> getTypeChunks() {
return types.values();
}
/**
* For a given type id, returns the {@link TypeChunk} objects that match that id. The type id is
* the 1-based index of the type in the type string pool (returned by {@link #getTypeStringPool}).
*
* @param id The 1-based type id to return {@link TypeChunk} objects for.
* @return The matching {@link TypeChunk} objects, or an empty collection if there are none.
*/
public Collection<TypeChunk> getTypeChunks(int id) {
return types.get(id);
}
/**
* For a given type, returns the {@link TypeChunk} objects that match that type
* (e.g. "attr", "id", "string", ...).
*
* @param type The type to return {@link TypeChunk} objects for.
* @return The matching {@link TypeChunk} objects, or an empty collection if there are none.
*/
public Collection<TypeChunk> getTypeChunks(String type) {
StringPoolChunk typeStringPool = Preconditions.checkNotNull(getTypeStringPool());
return getTypeChunks(typeStringPool.indexOf(type) + 1); // Convert 0-based index to 1-based
}
/**
* Returns all {@link TypeSpecChunk} in this package.
*/
public Collection<TypeSpecChunk> getTypeSpecChunks() {
return typeSpecs.values();
}
/**
* For a given (1-based) type id, returns the {@link TypeSpecChunk} matching it.
*/
public TypeSpecChunk getTypeSpecChunk(int id) {
return Preconditions.checkNotNull(typeSpecs.get(id));
}
/**
* For a given {@code type}, returns the {@link TypeSpecChunk} that matches it
* (e.g. "attr", "id", "string", ...).
*/
public TypeSpecChunk getTypeSpecChunk(String type) {
StringPoolChunk typeStringPool = Preconditions.checkNotNull(getTypeStringPool());
return getTypeSpecChunk(typeStringPool.indexOf(type) + 1); // Convert 0-based index to 1-based
}
/**
* Returns the name of this package.
*/
public String getPackageName() {
return packageName;
}
/**
* Set the package name
*/
public void setPackageName(String packageName) {
this.packageName = packageName;
}
@Override
protected Type getType() {
return Type.TABLE_PACKAGE;
}
@Override
protected void writeHeader(ByteBuffer output) {
output.putInt(id);
PackageUtils.writePackageName(output, packageName);
output.putInt(0); // typeStringsOffset. This value can't be computed here.
output.putInt(lastPublicType);
output.putInt(0); // keyStringsOffset. This value can't be computed here.
output.putInt(lastPublicKey);
output.putInt(typeIdOffset);
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
int typeOffset = typeStringsOffset;
int keyOffset = keyStringsOffset;
int payloadOffset = 0;
for (Chunk chunk : getChunks().values()) {
if (chunk == getTypeStringPool()) {
typeOffset = payloadOffset + getHeaderSize();
} else if (chunk == getKeyStringPool()) {
keyOffset = payloadOffset + getHeaderSize();
}
byte[] chunkBytes = chunk.toByteArray(shrink);
output.write(chunkBytes);
payloadOffset = writePad(output, chunkBytes.length);
}
header.putInt(TYPE_OFFSET_OFFSET, typeOffset);
header.putInt(KEY_OFFSET_OFFSET, keyOffset);
}
}
@@ -0,0 +1,72 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* Provides utility methods for package names.
*/
public final class PackageUtils {
public static final int PACKAGE_NAME_SIZE = 256;
private PackageUtils() {
} // Prevent instantiation
/**
* Reads the package name from the buffer and repositions the buffer to point directly after
* the package name.
*
* @param buffer The buffer containing the package name.
* @param offset The offset in the buffer to read from.
* @return The package name.
*/
public static String readPackageName(ByteBuffer buffer, int offset) {
byte[] data = buffer.array();
int length = 0;
// Look for the null terminator for the string instead of using the entire buffer.
// It's UTF-16 so check 2 bytes at a time to see if its double 0.
for (int i = offset; i < data.length && i < PACKAGE_NAME_SIZE + offset; i += 2) {
if (data[i] == 0 && data[i + 1] == 0) {
length = i - offset;
break;
}
}
Charset utf16 = StandardCharsets.UTF_16LE;
String str = new String(data, offset, length, utf16);
buffer.position(offset + PACKAGE_NAME_SIZE);
return str;
}
/**
* Writes the provided package name to the buffer in UTF-16.
*
* @param buffer The buffer that will be written to.
* @param packageName The package name that will be written to the buffer.
*/
public static void writePackageName(ByteBuffer buffer, String packageName) {
byte[] nameBytes = packageName.getBytes(StandardCharsets.UTF_16LE);
buffer.put(nameBytes, 0, Math.min(nameBytes.length, PACKAGE_NAME_SIZE));
if (nameBytes.length < PACKAGE_NAME_SIZE) {
// pad out the remaining space with an empty array.
buffer.put(new byte[PACKAGE_NAME_SIZE - nameBytes.length]);
}
}
}
@@ -0,0 +1,301 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import com.google.common.base.Preconditions;
import com.google.devrel.gmscore.tools.apk.arsc.ArscBlamer.ResourceEntry;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
/**
* Calculates extra information about an {@link ResourceEntry}, such as the total
* APK size the entry is responsible for.
* <p>
* This class is not thread-safe.
*/
public class ResourceEntryStatsCollector {
/**
* The size in bytes of an offset in a chunk.
*/
private static final int OFFSET_SIZE = 4;
/**
* The size in bytes of overhead for styles, if present, in {@link StringPoolChunk}.
*/
private static final int STYLE_OVERHEAD = 8;
/**
* The number of bytes, in addition to the header, that the {@link PackageChunk} has in overhead
* excluding the chunks it contains.
*/
private static final int PACKAGE_CHUNK_OVERHEAD = 8;
private final Map<ResourceEntry, ResourceStatistics> stats = new HashMap<>();
private final ArscBlamer blamer;
private final ResourceTableChunk resourceTable;
/**
* Creates a new {@link ResourceEntryStatsCollector}.
*
* @param blamer The blamer that maps resource entries to what they use.
* @param resourceTable The resource table that {@code blamer} is blamed on.
*/
public ResourceEntryStatsCollector(ArscBlamer blamer, ResourceTableChunk resourceTable) {
this.resourceTable = resourceTable;
this.blamer = blamer;
}
public void compute() throws IOException {
Preconditions.checkState(stats.isEmpty(), "Must only call #compute once.");
blamer.blame();
computeStringPoolSizes();
computePackageSizes();
}
/**
* Returns entries for which there are computed stats. Must first call {@link #compute}.
*/
public Map<ResourceEntry, ResourceStatistics> getStats() {
Preconditions.checkState(!stats.isEmpty(), "Must call #compute() first.");
return Collections.unmodifiableMap(stats);
}
/**
* Returns computed stats for a given entry. Must first call {@link #compute}.
*/
public ResourceStatistics getStats(ResourceEntry entry) {
Preconditions.checkState(!stats.isEmpty(), "Must call #compute() first.");
return stats.containsKey(entry) ? stats.get(entry) : ResourceStatistics.EMPTY;
}
private void computeStringPoolSizes() throws IOException {
computePoolSizes(resourceTable.getStringPool(), blamer.getStringToBlamedResources());
}
private void computePackageSizes() throws IOException {
computeTypePoolSizes();
computeKeyPoolSizes();
computeTypeSpecSizes();
computeTypeChunkSizes();
computePackageChunkSizes();
}
private void computeTypePoolSizes() throws IOException {
for (Entry<PackageChunk, List<ResourceEntry>[]> entry
: blamer.getTypeToBlamedResources().entrySet()) {
computePoolSizes(entry.getKey().getTypeStringPool(), entry.getValue());
}
}
private void computeKeyPoolSizes() throws IOException {
for (Entry<PackageChunk, List<ResourceEntry>[]> entry
: blamer.getKeyToBlamedResources().entrySet()) {
computePoolSizes(entry.getKey().getKeyStringPool(), entry.getValue());
}
}
private void computeTypeSpecSizes() {
for (Entry<PackageChunk, List<ResourceEntry>[]> entry
: blamer.getTypeToBlamedResources().entrySet()) {
computeTypeSpecSizes(entry.getKey(), entry.getValue());
}
}
private void computeTypeChunkSizes() {
for (Entry<TypeChunk.Entry, Collection<ResourceEntry>> entry
: blamer.getTypeEntryToBlamedResources().asMap().entrySet()) {
TypeChunk.Entry chunkEntry = entry.getKey();
TypeChunk typeChunk = chunkEntry.parent();
int size = chunkEntry.size() + OFFSET_SIZE;
int count = typeChunk.getEntries().size();
int nullEntries = typeChunk.getTotalEntryCount() - typeChunk.getEntries().size();
int overhead = typeChunk.getHeaderSize() + nullEntries * OFFSET_SIZE;
addSizes(entry.getValue(), overhead, size, count);
}
}
private void computePackageChunkSizes() {
for (Entry<PackageChunk, Collection<ResourceEntry>> entry
: blamer.getPackageToBlamedResources().asMap().entrySet()) {
int overhead = entry.getKey().getHeaderSize() + PACKAGE_CHUNK_OVERHEAD;
addSizes(entry.getValue(), overhead, 0, 1);
}
}
private void computePoolSizes(StringPoolChunk stringPool,
List<ResourceEntry>[] usages) throws IOException {
int overhead = stringPool.getHeaderSize();
if (stringPool.getStyleCount() > 0) {
overhead += STYLE_OVERHEAD;
}
// We have to iterate over the indices of the string pool, because it is possible that there are
// indices which have *no* associated resource entry (i.e. references from XML files without an
// entry in R).
int count = 0;
for (int i = 0; i < usages.length; ++i) {
if (usages[i].isEmpty()) {
overhead += computeStringAndStyleSize(stringPool, i);
} else {
++count;
}
}
// Now that we know the number of actual entries, we can compute the size.
for (int i = 0; i < usages.length; ++i) {
if (usages[i].isEmpty()) {
continue;
}
int size = computeStringAndStyleSize(stringPool, i);
addSizes(usages[i], overhead, size, count);
}
}
private void computeTypeSpecSizes(PackageChunk packageChunk,
List<ResourceEntry>[] usages) {
for (int i = 0; i < usages.length; ++i) {
// The 1 here is to convert back to a 1-based index.
TypeSpecChunk typeSpec = packageChunk.getTypeSpecChunk(i + 1);
// TypeSpecChunk entries share everything equally.
addSizes(usages[i], typeSpec.getOriginalChunkSize(), 0, 1);
}
}
/**
* Given an {@code index} into a {@code stringPool}, return string's total size in bytes plus its
* style, if any.
*
* @param stringPool The string pool containing the {@code index}.
* @param index The (0-based) index of the string and (optional) style.
* @throws IOException Thrown if the style's length could not be computed.
*/
private int computeStringAndStyleSize(StringPoolChunk stringPool, int index)
throws IOException {
return computeStringSize(stringPool, index) + computeStyleSize(stringPool, index);
}
/**
* Given an {@code index} into a {@code stringPool}, return string's total size in bytes.
*/
private int computeStringSize(StringPoolChunk stringPool, int index) {
String string = stringPool.getString(index);
int result = BinaryResourceString.encodeString(string, stringPool.getStringType()).length;
result += OFFSET_SIZE;
return result;
}
/**
* Given an {@code index} into a {@code stringPool}, return style's total size in bytes or 0 if
* there's no style at that index.
*
* @throws IOException Thrown if the style's length could not be computed.
*/
private int computeStyleSize(StringPoolChunk stringPool, int index) throws IOException {
if (index >= stringPool.getStyleCount()) { // No style at index
return 0;
}
return stringPool.getStyle(index).toByteArray().length + OFFSET_SIZE;
}
/**
* Adds to the {@link #stats} of {@code entries} that reference a value in a chunk the bytes it's
* responsible for. This should only be called once per chunk-value pair.
*
* @param entries The resource entries referencing a single value in a chunk.
* @param overhead The number of bytes of overhead of a chunk. Typically the header size.
* @param size The size in bytes of a value in a chunk that {@code entries} reference.
* @param count The total number of values in the chunk.
*/
private void addSizes(Collection<ResourceEntry> entries, int overhead, int size, int count) {
int usageCount = entries.size();
for (ResourceEntry resourceEntry : entries) {
// TODO(acornwall): Replace with Java 8's #getOrDefault when possible.
if (!stats.containsKey(resourceEntry)) {
stats.put(resourceEntry, new ResourceStatistics());
}
ResourceStatistics resourceStats = stats.get(resourceEntry);
if (usageCount == 1) {
resourceStats.addPrivateSize(size);
} else {
resourceStats.addSharedSize(size);
}
// Special case: If the chunk only has one relevant value, removing this entry will remove the
// entire chunk.
if (usageCount == 1 && count == 1) {
resourceStats.addPrivateSize(overhead);
}
resourceStats.addProportionalSize(size, usageCount);
resourceStats.addProportionalSize(overhead, usageCount * count);
}
}
/**
* Stats for an individual {@link ResourceEntry}.
*/
public static class ResourceStatistics {
/**
* The empty, immutable instance of ResourceStatistics which contains 0 for all values.
*/
public static final ResourceStatistics EMPTY = new ResourceStatistics();
private int privateSize = 0;
private int sharedSize = 0;
private double proportionalSize = 0;
private ResourceStatistics() {
}
/**
* The number of bytes that would be freed if this resource was removed.
*/
public int getPrivateSize() {
return privateSize;
}
/**
* The number of bytes taken up by this resource that are also shared with other resources.
*/
public int getSharedSize() {
return sharedSize;
}
/**
* The total size this resource is responsible for.
*/
public double getProportionalSize() {
return proportionalSize;
}
private void addPrivateSize(int privateSize) {
this.privateSize += privateSize;
}
private void addSharedSize(int sharedSize) {
this.sharedSize += sharedSize;
}
private void addProportionalSize(int numerator, int denominator) {
this.proportionalSize += 1.0 * numerator / denominator;
}
}
}
@@ -0,0 +1,101 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import com.google.common.base.Preconditions;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Represents a resource table structure. Its sub-chunks contain:
*
* <ul>
* <li>A {@link StringPoolChunk} containing all string values in the entire resource table. It does
* not, however, contain the names of entries or type identifiers.
* <li>One or more {@link PackageChunk}.
* </ul>
*/
public final class ResourceTableChunk extends ChunkWithChunks {
/**
* The packages contained in this resource table.
*/
private final Map<String, PackageChunk> packages = new HashMap<>();
/**
* A string pool containing all string resource values in the entire resource table.
*/
private StringPoolChunk stringPool;
ResourceTableChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
// packageCount. We ignore this, because we already know how many chunks we have.
Preconditions.checkState(buffer.getInt() >= 1, "ResourceTableChunk package count was < 1.");
}
@Override
protected void init(ByteBuffer buffer) {
super.init(buffer);
packages.clear();
for (Chunk chunk : getChunks().values()) {
if (chunk instanceof PackageChunk) {
PackageChunk packageChunk = (PackageChunk) chunk;
packages.put(packageChunk.getPackageName(), packageChunk);
} else if (chunk instanceof StringPoolChunk) {
stringPool = (StringPoolChunk) chunk;
}
}
Preconditions.checkNotNull(stringPool, "ResourceTableChunk must have a string pool.");
}
/**
* Returns the string pool containing all string resource values in the resource table.
*/
public StringPoolChunk getStringPool() {
return stringPool;
}
/**
* Returns the package with the given {@code packageName}. Else, returns null.
*/
@Nullable
public PackageChunk getPackage(String packageName) {
return packages.get(packageName);
}
/**
* Returns the packages contained in this resource table.
*/
public Collection<PackageChunk> getPackages() {
return Collections.unmodifiableCollection(packages.values());
}
@Override
protected Type getType() {
return Type.TABLE;
}
@Override
protected void writeHeader(ByteBuffer output) {
super.writeHeader(output);
output.putInt(packages.size());
}
}
@@ -0,0 +1,43 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import java.io.IOException;
/**
* A resource, typically a @{link Chunk}, that can be converted to an array of bytes.
*/
public interface SerializableResource {
/**
* Converts this resource into an array of bytes representation.
*
* @return An array of bytes representing this resource.
* @throws IOException
*/
byte[] toByteArray() throws IOException;
/**
* Converts this resource into an array of bytes representation.
*
* @param shrink True if, when converting to a byte array, this resource can modify the returned
* bytes in an effort to reduce the size.
* @return An array of bytes representing this resource.
* @throws IOException
*/
byte[] toByteArray(boolean shrink) throws IOException;
}
@@ -0,0 +1,443 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.io.LittleEndianDataOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
/**
* Represents a string pool structure.
*/
public final class StringPoolChunk extends Chunk {
// These are the defined flags for the "flags" field of ResourceStringPoolHeader
private static final int SORTED_FLAG = 1 << 0;
private static final int UTF8_FLAG = 1 << 8;
/**
* The offset from the start of the header that the stylesStart field is at.
*/
private static final int STYLE_START_OFFSET = 24;
/**
* Flags.
*/
private final int flags;
/**
* Index from header of the string data.
*/
private final int stringsStart;
/**
* Index from header of the style data.
*/
private final int stylesStart;
/**
* Number of strings in the original buffer. This is not necessarily the number of strings in
* {@code strings}.
*/
private final int stringCount;
/**
* Number of styles in the original buffer. This is not necessarily the number of styles in
* {@code styles}.
*/
private final int styleCount;
/**
* The strings ordered as they appear in the arsc file. e.g. strings.get(1234) gets the 1235th
* string in the arsc file.
*/
private final List<String> strings = new ArrayList<>();
/**
* These styles have a 1:1 relationship with the strings. For example, styles.get(3) refers to
* the string at location strings.get(3). There are never more styles than strings (though there
* may be less). Inside of that are all of the styles referenced by that string.
*/
private final List<StringPoolStyle> styles = new ArrayList<>();
/**
* True if the original {@link StringPoolChunk} shows signs of being deduped. Specifically, this
* is set to true if there exists a string whose offset is <= the previous offset. This is used to
* preserve the deduping of strings for pools that have been deduped.
*/
private boolean isOriginalDeduped = false;
StringPoolChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
stringCount = buffer.getInt();
styleCount = buffer.getInt();
flags = buffer.getInt();
stringsStart = buffer.getInt();
stylesStart = buffer.getInt();
}
@Override
protected void init(ByteBuffer buffer) {
super.init(buffer);
strings.addAll(readStrings(buffer, offset + stringsStart, stringCount));
styles.addAll(readStyles(buffer, offset + stylesStart, styleCount));
}
/**
* Returns the 0-based index of the first occurrence of the given string, or -1 if the string is
* not in the pool. This runs in O(n) time.
*
* @param string The string to check the pool for.
* @return Index of the string, or -1 if not found.
*/
public int indexOf(String string) {
return strings.indexOf(string);
}
/**
* Returns a string at the given (0-based) index.
*
* @param index The (0-based) index of the string to return.
* @throws IndexOutOfBoundsException If the index is out of range (index < 0 || index >= size()).
*/
public String getString(int index) {
return strings.get(index);
}
public void updateString(int index, String value) {
strings.set(index, value);
}
/**
* Returns the number of strings in this pool.
*/
public int getStringCount() {
return strings.size();
}
/**
* Returns a style at the given (0-based) index.
*
* @param index The (0-based) index of the style to return.
* @throws IndexOutOfBoundsException If the index is out of range (index < 0 || index >= size()).
*/
public StringPoolStyle getStyle(int index) {
return styles.get(index);
}
/**
* Returns the number of styles in this pool.
*/
public int getStyleCount() {
return styles.size();
}
/**
* Returns the type of strings in this pool.
*/
public BinaryResourceString.Type getStringType() {
return isUTF8() ? BinaryResourceString.Type.UTF8 : BinaryResourceString.Type.UTF16;
}
@Override
protected Type getType() {
return Type.STRING_POOL;
}
/**
* Returns the number of bytes needed for offsets based on {@code strings} and {@code styles}.
*/
private int getOffsetSize() {
return (strings.size() + styles.size()) * 4;
}
/**
* True if this string pool contains strings in UTF-8 format. Otherwise, strings are in UTF-16.
*
* @return true if @{code strings} are in UTF-8; false if they're in UTF-16.
*/
public boolean isUTF8() {
return (flags & UTF8_FLAG) != 0;
}
/**
* True if this string pool contains already-sorted strings.
*
* @return true if @{code strings} are sorted.
*/
public boolean isSorted() {
return (flags & SORTED_FLAG) != 0;
}
private List<String> readStrings(ByteBuffer buffer, int offset, int count) {
List<String> result = new ArrayList<>();
int previousOffset = -1;
// After the header, we now have an array of offsets for the strings in this pool.
for (int i = 0; i < count; ++i) {
int stringOffset = offset + buffer.getInt();
result.add(BinaryResourceString.decodeString(buffer, stringOffset, getStringType()));
if (stringOffset <= previousOffset) {
isOriginalDeduped = true;
}
previousOffset = stringOffset;
}
return result;
}
private List<StringPoolStyle> readStyles(ByteBuffer buffer, int offset, int count) {
List<StringPoolStyle> result = new ArrayList<>();
// After the array of offsets for the strings in the pool, we have an offset for the styles
// in this pool.
for (int i = 0; i < count; ++i) {
int styleOffset = offset + buffer.getInt();
result.add(StringPoolStyle.create(buffer, styleOffset, this));
}
return result;
}
private int writeStrings(DataOutput payload, ByteBuffer offsets, boolean shrink)
throws IOException {
int stringOffset = 0;
Map<String, Integer> used = new HashMap<>(); // Keeps track of strings already written
for (String string : strings) {
// Dedupe everything except stylized strings, unless shrink is true (then dedupe everything)
if (used.containsKey(string) && (shrink || isOriginalDeduped)) {
Integer offset = used.get(string);
offsets.putInt(offset == null ? 0 : offset);
} else {
byte[] encodedString = BinaryResourceString.encodeString(string, getStringType());
payload.write(encodedString);
used.put(string, stringOffset);
offsets.putInt(stringOffset);
stringOffset += encodedString.length;
}
}
// ARSC files pad to a 4-byte boundary. We should do so too.
stringOffset = writePad(payload, stringOffset);
return stringOffset;
}
private int writeStyles(DataOutput payload, ByteBuffer offsets, boolean shrink)
throws IOException {
int styleOffset = 0;
if (!styles.isEmpty()) {
Map<StringPoolStyle, Integer> used = new HashMap<>(); // Keeps track of bytes already written
for (StringPoolStyle style : styles) {
if (!used.containsKey(style) || !shrink) {
byte[] encodedStyle = style.toByteArray(shrink);
payload.write(encodedStyle);
used.put(style, styleOffset);
offsets.putInt(styleOffset);
styleOffset += encodedStyle.length;
} else { // contains key and shrink is true
Integer offset = used.get(style);
offsets.putInt(offset == null ? 0 : offset);
}
}
// The end of the spans are terminated with another sentinel value
payload.writeInt(StringPoolStyle.RES_STRING_POOL_SPAN_END);
styleOffset += 4;
// TODO(acornwall): There appears to be an extra SPAN_END here... why?
payload.writeInt(StringPoolStyle.RES_STRING_POOL_SPAN_END);
styleOffset += 4;
styleOffset = writePad(payload, styleOffset);
}
return styleOffset;
}
@Override
protected void writeHeader(ByteBuffer output) {
int stringsStart = getHeaderSize() + getOffsetSize();
output.putInt(strings.size());
output.putInt(styles.size());
output.putInt(flags);
output.putInt(strings.isEmpty() ? 0 : stringsStart);
output.putInt(0); // Placeholder. The styles starting offset cannot be computed at this point.
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int stringOffset = 0;
ByteBuffer offsets = ByteBuffer.allocate(getOffsetSize());
offsets.order(ByteOrder.LITTLE_ENDIAN);
// Write to a temporary payload so we can rearrange this and put the offsets first
try (LittleEndianDataOutputStream payload = new LittleEndianDataOutputStream(baos)) {
stringOffset = writeStrings(payload, offsets, shrink);
writeStyles(payload, offsets, shrink);
}
output.write(offsets.array());
output.write(baos.toByteArray());
if (!styles.isEmpty()) {
header.putInt(STYLE_START_OFFSET, getHeaderSize() + getOffsetSize() + stringOffset);
}
}
/**
* Represents all of the styles for a particular string. The string is determined by its index
* in {@link StringPoolChunk}.
*/
public static class StringPoolStyle implements SerializableResource {
// Styles are a list of integers with 0xFFFFFFFF serving as a sentinel value.
static final int RES_STRING_POOL_SPAN_END = 0xFFFFFFFF;
private final List<StringPoolSpan> spans;
private StringPoolStyle(List<StringPoolSpan> spans) {
this.spans = spans;
}
static StringPoolStyle create(ByteBuffer buffer, int offset, StringPoolChunk parent) {
Builder<StringPoolSpan> spans = ImmutableList.builder();
int nameIndex = buffer.getInt(offset);
while (nameIndex != RES_STRING_POOL_SPAN_END) {
spans.add(StringPoolSpan.create(buffer, offset, parent));
offset += StringPoolSpan.SPAN_LENGTH;
nameIndex = buffer.getInt(offset);
}
return new StringPoolStyle(spans.build());
}
@Override
public byte[] toByteArray() throws IOException {
return toByteArray(false);
}
@Override
public byte[] toByteArray(boolean shrink) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (LittleEndianDataOutputStream payload = new LittleEndianDataOutputStream(baos)) {
for (StringPoolSpan span : spans) {
byte[] encodedSpan = span.toByteArray(shrink);
if (encodedSpan.length != StringPoolSpan.SPAN_LENGTH) {
throw new IllegalStateException("Encountered a span of invalid length.");
}
payload.write(encodedSpan);
}
payload.writeInt(RES_STRING_POOL_SPAN_END);
}
return baos.toByteArray();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StringPoolStyle that = (StringPoolStyle) o;
return Objects.equals(spans, that.spans);
}
@Override
public int hashCode() {
return Objects.hash(spans);
}
/**
* Returns a brief description of the contents of this style. The representation of this
* information is subject to change, but below is a typical example:
*
* <pre>"StringPoolStyle{spans=[StringPoolSpan{foo, start=0, stop=5}, ...]}"</pre>
*/
@Override
public String toString() {
return String.format("StringPoolStyle{spans=%s}", spans);
}
}
/**
* Represents a styled span associated with a specific string.
*/
private static class StringPoolSpan implements SerializableResource {
static final int SPAN_LENGTH = 12;
private final int nameIndex;
private final int start;
private final int stop;
private final StringPoolChunk parent;
private StringPoolSpan(int nameIndex, int start, int stop, StringPoolChunk parent) {
this.nameIndex = nameIndex;
this.start = start;
this.stop = stop;
this.parent = parent;
}
static StringPoolSpan create(ByteBuffer buffer, int offset, StringPoolChunk parent) {
int nameIndex = buffer.getInt(offset);
int start = buffer.getInt(offset + 4);
int stop = buffer.getInt(offset + 8);
return new StringPoolSpan(nameIndex, start, stop, parent);
}
@Override
public final byte[] toByteArray() {
return toByteArray(false);
}
@Override
public final byte[] toByteArray(boolean shrink) {
ByteBuffer buffer = ByteBuffer.allocate(SPAN_LENGTH).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(nameIndex);
buffer.putInt(start);
buffer.putInt(stop);
return buffer.array();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StringPoolSpan that = (StringPoolSpan) o;
return nameIndex == that.nameIndex &&
start == that.start &&
stop == that.stop &&
Objects.equals(parent, that.parent);
}
@Override
public int hashCode() {
return Objects.hash(nameIndex, start, stop, parent);
}
/**
* Returns a brief description of this span. The representation of this information is subject
* to change, but below is a typical example:
*
* <pre>"StringPoolSpan{foo, start=0, stop=5}"</pre>
*/
@Override
public String toString() {
return String.format("StringPoolSpan{%s, start=%d, stop=%d}",
parent.getString(nameIndex), start, stop);
}
}
}
@@ -0,0 +1,520 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import com.google.common.base.Preconditions;
import com.google.common.io.LittleEndianDataOutputStream;
import com.google.common.primitives.UnsignedBytes;
import java.io.ByteArrayOutputStream;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
/**
* Represents a type chunk, which contains the resource values for a specific resource type and
* configuration in a {@link PackageChunk}. The resource values in this chunk correspond to
* the array of type strings in the enclosing {@link PackageChunk}.
*
* <p>A {@link PackageChunk} can have multiple of these chunks for different
* (configuration, resource type) combinations.
*/
public final class TypeChunk extends Chunk {
/**
* The type identifier of the resource type this chunk is holding.
*/
private final int id;
/**
* The number of resources of this type at creation time.
*/
private final int entryCount;
/**
* The offset (from {@code offset}) in the original buffer where {@code entries} start.
*/
private final int entriesStart;
/**
* A sparse list of resource entries defined by this chunk.
*/
private final Map<Integer, Entry> entries = new TreeMap<>();
/**
* The resource configuration that these resource entries correspond to.
*/
private BinaryResourceConfiguration configuration;
TypeChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
id = UnsignedBytes.toInt(buffer.get());
buffer.position(buffer.position() + 3); // Skip 3 bytes for packing
entryCount = buffer.getInt();
entriesStart = buffer.getInt();
configuration = BinaryResourceConfiguration.create(buffer);
}
@Override
protected void init(ByteBuffer buffer) {
int offset = this.offset + entriesStart;
for (int i = 0; i < entryCount; ++i) {
Entry entry = Entry.create(buffer, offset, this);
if (entry != null) {
entries.put(i, entry);
}
}
}
/**
* Returns the (1-based) type id of the resource types that this {@link TypeChunk} is holding.
*/
public int getId() {
return id;
}
/**
* Returns the name of the type this chunk represents (e.g. string, attr, id).
*/
public String getTypeName() {
PackageChunk packageChunk = getPackageChunk();
Preconditions.checkNotNull(packageChunk, "%s has no parent package.", getClass());
StringPoolChunk typePool = packageChunk.getTypeStringPool();
Preconditions.checkNotNull(typePool, "%s's parent package has no type pool.", getClass());
return typePool.getString(getId() - 1); // - 1 here to convert to 0-based index
}
/**
* Returns the resource configuration that these resource entries correspond to.
*/
public BinaryResourceConfiguration getConfiguration() {
return configuration;
}
/**
* Sets the resource configuration that this chunk's entries correspond to.
*
* @param configuration The new configuration.
*/
public void setConfiguration(BinaryResourceConfiguration configuration) {
this.configuration = configuration;
}
/**
* Returns the total number of entries for this type + configuration, including null entries.
*/
public int getTotalEntryCount() {
return entryCount;
}
/**
* Returns a sparse list of 0-based indices to resource entries defined by this chunk.
*/
public Map<Integer, Entry> getEntries() {
return Collections.unmodifiableMap(entries);
}
/**
* Returns true if this chunk contains an entry for {@code resourceId}.
*/
public boolean containsResource(BinaryResourceIdentifier resourceId) {
PackageChunk packageChunk = Preconditions.checkNotNull(getPackageChunk());
int packageId = packageChunk.getId();
int typeId = getId();
return resourceId.packageId() == packageId
&& resourceId.typeId() == typeId
&& entries.containsKey(resourceId.entryId());
}
/**
* Overrides the entries in this chunk at the given index:entry pairs in {@code entries}.
* For example, if the current list of entries is {0: foo, 1: bar, 2: baz}, and {@code entries}
* is {1: qux, 3: quux}, then the entries will be changed to {0: foo, 1: qux, 2: baz}. If an entry
* has an index that does not exist in the dense entry list, then it is considered a no-op for
* that single entry.
*
* @param entries A sparse list containing index:entry pairs to override.
*/
public void overrideEntries(Map<Integer, Entry> entries) {
for (Map.Entry<Integer, Entry> entry : entries.entrySet()) {
int index = entry.getKey() != null ? entry.getKey() : -1;
overrideEntry(index, entry.getValue());
}
}
/**
* Overrides an entry at the given index. Passing null for the {@code entry} will remove that
* entry from {@code entries}. Indices < 0 or >= {@link #getTotalEntryCount()} are a no-op.
*
* @param index The 0-based index for the entry to override.
* @param entry The entry to override, or null if the entry should be removed at this location.
*/
public void overrideEntry(int index, @Nullable Entry entry) {
if (index >= 0 && index < entryCount) {
if (entry != null) {
entries.put(index, entry);
} else {
entries.remove(index);
}
}
}
private String getString(int index) {
ResourceTableChunk resourceTable = getResourceTableChunk();
Preconditions.checkNotNull(resourceTable, "%s has no resource table.", getClass());
return resourceTable.getStringPool().getString(index);
}
private String getKeyName(int index) {
PackageChunk packageChunk = getPackageChunk();
Preconditions.checkNotNull(packageChunk, "%s has no parent package.", getClass());
StringPoolChunk keyPool = packageChunk.getKeyStringPool();
Preconditions.checkNotNull(keyPool, "%s's parent package has no key pool.", getClass());
return keyPool.getString(index);
}
private void updateKey(int index, String value) {
PackageChunk packageChunk = getPackageChunk();
Preconditions.checkNotNull(packageChunk, "%s has no parent package.", getClass());
StringPoolChunk keyPool = packageChunk.getKeyStringPool();
Preconditions.checkNotNull(keyPool, "%s's parent package has no key pool.", getClass());
keyPool.updateString(index, value);
}
@Nullable
private ResourceTableChunk getResourceTableChunk() {
Chunk chunk = getParent();
while (chunk != null && !(chunk instanceof ResourceTableChunk)) {
chunk = chunk.getParent();
}
return chunk != null ? (ResourceTableChunk) chunk : null;
}
/**
* Returns the package enclosing this chunk, if any. Else, returns null.
*/
@Nullable
public PackageChunk getPackageChunk() {
Chunk chunk = getParent();
while (chunk != null && !(chunk instanceof PackageChunk)) {
chunk = chunk.getParent();
}
return chunk != null ? (PackageChunk) chunk : null;
}
@Override
protected Type getType() {
return Type.TABLE_TYPE;
}
/**
* Returns the number of bytes needed for offsets based on {@code entries}.
*/
private int getOffsetSize() {
return entryCount * 4;
}
private int writeEntries(DataOutput payload, ByteBuffer offsets, boolean shrink)
throws IOException {
int entryOffset = 0;
for (int i = 0; i < entryCount; ++i) {
Entry entry = entries.get(i);
if (entry == null) {
offsets.putInt(Entry.NO_ENTRY);
} else {
byte[] encodedEntry = entry.toByteArray(shrink);
payload.write(encodedEntry);
offsets.putInt(entryOffset);
entryOffset += encodedEntry.length;
}
}
entryOffset = writePad(payload, entryOffset);
return entryOffset;
}
@Override
protected void writeHeader(ByteBuffer output) {
int entriesStart = getHeaderSize() + getOffsetSize();
output.putInt(id); // Write an unsigned byte with 3 bytes padding
output.putInt(entryCount);
output.putInt(entriesStart);
output.put(configuration.toByteArray(false));
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteBuffer offsets = ByteBuffer.allocate(getOffsetSize()).order(ByteOrder.LITTLE_ENDIAN);
try (LittleEndianDataOutputStream payload = new LittleEndianDataOutputStream(baos)) {
writeEntries(payload, offsets, shrink);
}
output.write(offsets.array());
output.write(baos.toByteArray());
}
/**
* An {@link Entry} in a {@link TypeChunk}. Contains one or more {@link BinaryResourceValue}.
*/
public static class Entry implements SerializableResource {
/**
* An entry offset that indicates that a given resource is not present.
*/
public static final int NO_ENTRY = 0xFFFFFFFF;
/**
* Set if this is a complex resource. Otherwise, it's a simple resource.
*/
private static final int FLAG_COMPLEX = 0x0001;
/**
* Size of a single resource id + value mapping entry.
*/
private static final int MAPPING_SIZE = 4 + BinaryResourceValue.SIZE;
private final int headerSize;
private final int flags;
private final int keyIndex;
private final int parentEntry;
private final TypeChunk parent;
private BinaryResourceValue value;
private final Map<Integer, BinaryResourceValue> values;
private Entry(int headerSize,
int flags,
int keyIndex,
BinaryResourceValue value,
Map<Integer, BinaryResourceValue> values,
int parentEntry,
TypeChunk parent) {
this.headerSize = headerSize;
this.flags = flags;
this.keyIndex = keyIndex;
this.value = value;
this.values = values;
this.parentEntry = parentEntry;
this.parent = parent;
}
/**
* Creates a new {@link Entry} whose contents start at the 0-based position in
* {@code buffer} given by a 4-byte value read from {@code buffer} and then added to
* {@code baseOffset}. If the value read from {@code buffer} is equal to {@link #NO_ENTRY}, then
* null is returned as there is no resource at that position.
*
* <p>Otherwise, this position is parsed and returned as an {@link Entry}.
*
* @param buffer A buffer positioned at an offset to an {@link Entry}.
* @param baseOffset Offset that must be added to the value at {@code buffer}'s position.
* @param parent The {@link TypeChunk} that this resource entry belongs to.
* @return New {@link Entry} or null if there is no resource at this location.
*/
@Nullable
public static Entry create(ByteBuffer buffer, int baseOffset, TypeChunk parent) {
int offset = buffer.getInt();
if (offset == NO_ENTRY) {
return null;
}
int position = buffer.position();
buffer.position(baseOffset + offset); // Set buffer position to resource entry start
Entry result = newInstance(buffer, parent);
buffer.position(position); // Restore buffer position
return result;
}
@Nullable
private static Entry newInstance(ByteBuffer buffer, TypeChunk parent) {
int headerSize = buffer.getShort() & 0xFFFF;
int flags = buffer.getShort() & 0xFFFF;
int keyIndex = buffer.getInt();
BinaryResourceValue value = null;
Map<Integer, BinaryResourceValue> values = new LinkedHashMap<>();
int parentEntry = 0;
if ((flags & FLAG_COMPLEX) != 0) {
parentEntry = buffer.getInt();
int valueCount = buffer.getInt();
for (int i = 0; i < valueCount; ++i) {
values.put(buffer.getInt(), BinaryResourceValue.create(buffer));
}
} else {
value = BinaryResourceValue.create(buffer);
}
return new Entry(headerSize, flags, keyIndex, value, values, parentEntry, parent);
}
/**
* Number of bytes in the header of the {@link Entry}.
*/
public int headerSize() {
return headerSize;
}
/**
* Resource entry flags.
*/
public int flags() {
return flags;
}
/**
* Index into {@link PackageChunk#getKeyStringPool} identifying this entry.
*/
public int keyIndex() {
return keyIndex;
}
/**
* The value of this resource entry, if this is not a complex entry. Else, null.
*/
@Nullable
public BinaryResourceValue value() {
return value;
}
/**
* Update the value of this resource entry
*
* @param value
*/
public void updateValue(@Nullable BinaryResourceValue value) {
this.value = value;
}
/**
* The extra values in this resource entry if this {@link #isComplex}.
*/
public Map<Integer, BinaryResourceValue> values() {
return values;
}
/**
* Update the value in this resource entry if this {@link #isComplex}.
*/
public void updateValue(int index, BinaryResourceValue value) {
if (index >= 0) {
if (value != null) {
values.put(index, value);
} else {
values.remove(index);
}
}
}
/**
* Entry into {@link PackageChunk} that is the parent {@link Entry} to this entry.
* This value only makes sense when this is complex ({@link #isComplex} returns true).
*/
public int parentEntry() {
return parentEntry;
}
/**
* The {@link TypeChunk} that this resource entry belongs to.
*/
public TypeChunk parent() {
return parent;
}
/**
* Returns the name of the type this chunk represents (e.g. string, attr, id).
*/
public final String typeName() {
return parent().getTypeName();
}
/**
* The total number of bytes that this {@link Entry} takes up.
*/
public final int size() {
return headerSize() + (isComplex() ? values().size() * MAPPING_SIZE : BinaryResourceValue.SIZE);
}
/**
* Returns the key name identifying this resource entry.
*/
public final String key() {
return parent().getKeyName(keyIndex());
}
/**
* Update the key name in this resource entry.
*/
public final void updateKey(int keyIndex, String value) {
parent().updateKey(keyIndex, value);
}
/**
* Returns true if this is a complex resource.
*/
public final boolean isComplex() {
return (flags() & FLAG_COMPLEX) != 0;
}
@Override
public final byte[] toByteArray() {
return toByteArray(false);
}
@Override
public final byte[] toByteArray(boolean shrink) {
ByteBuffer buffer = ByteBuffer.allocate(size());
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putShort((short) headerSize());
buffer.putShort((short) flags());
buffer.putInt(keyIndex());
if (isComplex()) {
buffer.putInt(parentEntry());
buffer.putInt(values().size());
for (Map.Entry<Integer, BinaryResourceValue> entry : values().entrySet()) {
buffer.putInt(entry.getKey());
buffer.put(entry.getValue().toByteArray(shrink));
}
} else {
BinaryResourceValue value = value();
Preconditions.checkNotNull(value, "A non-complex TypeChunk entry must have a value.");
buffer.put(value.toByteArray());
}
return buffer.array();
}
@Override
public final String toString() {
return String.format("Entry{key=%s}", key());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Entry entry = (Entry) o;
return headerSize == entry.headerSize &&
flags == entry.flags &&
keyIndex == entry.keyIndex &&
parentEntry == entry.parentEntry &&
Objects.equals(value, entry.value) &&
Objects.equals(values, entry.values) &&
Objects.equals(parent, entry.parent);
}
@Override
public int hashCode() {
return Objects.hash(headerSize, flags, keyIndex, value, values, parentEntry, parent);
}
}
}
@@ -0,0 +1,113 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import com.google.common.base.Preconditions;
import com.google.common.primitives.UnsignedBytes;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* A chunk that contains a collection of resource entries for a particular resource data type.
*/
public final class TypeSpecChunk extends Chunk {
/**
* The id of the resource type that this type spec refers to.
*/
private final int id;
/**
* Resource configuration masks.
*/
private final int[] resources;
TypeSpecChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
id = UnsignedBytes.toInt(buffer.get());
buffer.position(buffer.position() + 3); // Skip 3 bytes for packing
int resourceCount = buffer.getInt();
resources = new int[resourceCount];
for (int i = 0; i < resourceCount; ++i) {
resources[i] = buffer.getInt();
}
}
/**
* Returns the (1-based) type id of the resources that this {@link TypeSpecChunk} has
* configuration masks for.
*/
public int getId() {
return id;
}
/**
* Returns the number of resource entries that this chunk has configuration masks for.
*/
public int getResourceCount() {
return resources.length;
}
@Override
protected Type getType() {
return Type.TABLE_TYPE_SPEC;
}
/**
* Returns the name of the type this chunk represents (e.g. string, attr, id).
*/
public String getTypeName() {
PackageChunk packageChunk = getPackageChunk();
Preconditions.checkNotNull(packageChunk, "%s has no parent package.", getClass());
StringPoolChunk typePool = packageChunk.getTypeStringPool();
Preconditions.checkNotNull(typePool, "%s's parent package has no type pool.", getClass());
return typePool.getString(getId() - 1); // - 1 here to convert to 0-based index
}
/**
* Returns the package enclosing this chunk, if any. Else, returns null.
*/
@Nullable
private PackageChunk getPackageChunk() {
Chunk chunk = getParent();
while (chunk != null && !(chunk instanceof PackageChunk)) {
chunk = chunk.getParent();
}
return chunk != null ? (PackageChunk) chunk : null;
}
@Override
protected void writeHeader(ByteBuffer output) {
super.writeHeader(output);
// id is an unsigned byte in the range [0-255]. It is guaranteed to be non-negative.
// Because our output is in little-endian, we are making use of the 4 byte packing here
output.putInt(id);
output.putInt(resources.length);
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
for (int resource : resources) {
output.writeInt(resource);
}
}
}
@@ -0,0 +1,62 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* A chunk whose contents are unknown. This is a placeholder until we add a proper chunk for the
* unknown type.
*/
public final class UnknownChunk extends Chunk {
private final Type type;
private final byte[] header;
private final byte[] payload;
UnknownChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
type = Type.fromCode(buffer.getShort(offset));
header = new byte[headerSize - Chunk.METADATA_SIZE];
payload = new byte[chunkSize - headerSize];
buffer.get(header);
buffer.get(payload);
}
@Override
protected void writeHeader(ByteBuffer output) {
output.put(header);
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
output.write(payload);
}
@Override
protected Type getType() {
return type;
}
}
@@ -0,0 +1,168 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Objects;
/**
* Represents an XML attribute and value.
*/
public class XmlAttribute implements SerializableResource {
/**
* The serialized size in bytes of an {@link XmlAttribute}.
*/
public static final int SIZE = 12 + BinaryResourceValue.SIZE;
private final int namespaceIndex;
private final int nameIndex;
private final int rawValueIndex;
private final BinaryResourceValue typedValue;
private final XmlNodeChunk parent;
private XmlAttribute(int namespaceIndex,
int nameIndex,
int rawValueIndex,
BinaryResourceValue typedValue,
XmlNodeChunk parent) {
this.namespaceIndex = namespaceIndex;
this.nameIndex = nameIndex;
this.rawValueIndex = rawValueIndex;
this.typedValue = typedValue;
this.parent = parent;
}
/**
* Creates a new {@link XmlAttribute} based on the bytes at the current {@code buffer} position.
*
* @param buffer A buffer whose position is at the start of a {@link XmlAttribute}.
* @param parent The parent chunk that contains this attribute; used for string lookups.
*/
public static XmlAttribute create(ByteBuffer buffer, XmlNodeChunk parent) {
int namespace = buffer.getInt();
int name = buffer.getInt();
int rawValue = buffer.getInt();
BinaryResourceValue typedValue = BinaryResourceValue.create(buffer);
return new XmlAttribute(namespace, name, rawValue, typedValue, parent);
}
/**
* A string reference to the namespace URI, or -1 if not present.
*/
public int namespaceIndex() {
return namespaceIndex;
}
/**
* A string reference to the attribute name.
*/
public int nameIndex() {
return nameIndex;
}
/**
* A string reference to a string containing the character value.
*/
public int rawValueIndex() {
return rawValueIndex;
}
/**
* A {@link BinaryResourceValue} instance containing the parsed value.
*/
public BinaryResourceValue typedValue() {
return typedValue;
}
/**
* The parent of this XML attribute; used for dereferencing the namespace and name.
*/
public XmlNodeChunk parent() {
return parent;
}
/**
* The namespace URI, or the empty string if not present.
*/
public final String namespace() {
return getString(namespaceIndex());
}
/**
* The attribute name, or the empty string if not present.
*/
public final String name() {
return getString(nameIndex());
}
/**
* The raw character value.
*/
public final String rawValue() {
return getString(rawValueIndex());
}
private String getString(int index) {
return parent().getString(index);
}
@Override
public byte[] toByteArray() {
return toByteArray(false);
}
@Override
public byte[] toByteArray(boolean shrink) {
ByteBuffer buffer = ByteBuffer.allocate(SIZE).order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(namespaceIndex());
buffer.putInt(nameIndex());
buffer.putInt(rawValueIndex());
buffer.put(typedValue().toByteArray(shrink));
return buffer.array();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
XmlAttribute that = (XmlAttribute) o;
return namespaceIndex == that.namespaceIndex &&
nameIndex == that.nameIndex &&
rawValueIndex == that.rawValueIndex &&
Objects.equals(typedValue, that.typedValue) &&
Objects.equals(parent, that.parent);
}
@Override
public int hashCode() {
return Objects.hash(namespaceIndex, nameIndex, rawValueIndex, typedValue, parent);
}
/**
* Returns a brief description of this XML attribute. The representation of this information is
* subject to change, but below is a typical example:
*
* <pre>"XmlAttribute{namespace=foo, name=bar, value=1234}"</pre>
*/
@Override
public String toString() {
return String.format("XmlAttribute{namespace=%s, name=%s, value=%s}",
namespace(), name(), rawValue());
}
}
@@ -0,0 +1,84 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Represents an XML cdata node.
*/
public final class XmlCdataChunk extends XmlNodeChunk {
/**
* A string reference to a string containing the raw character data.
*/
private final int rawValue;
/**
* A {@link BinaryResourceValue} instance containing the parsed value.
*/
private final BinaryResourceValue binaryResourceValue;
XmlCdataChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
rawValue = buffer.getInt();
binaryResourceValue = BinaryResourceValue.create(buffer);
}
/**
* Returns a string containing the raw character data of this chunk.
*/
public String getRawValue() {
return getString(rawValue);
}
/**
* Returns a {@link BinaryResourceValue} instance containing the parsed cdata value.
*/
public BinaryResourceValue getResourceValue() {
return binaryResourceValue;
}
@Override
protected Type getType() {
return Type.XML_CDATA;
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
super.writePayload(output, header, shrink);
output.writeInt(rawValue);
output.write(binaryResourceValue.toByteArray());
}
/**
* Returns a brief description of this XML node. The representation of this information is
* subject to change, but below is a typical example:
*
* <pre>"XmlCdataChunk{line=1234, comment=My awesome comment., value=1234}"</pre>
*/
@Override
public String toString() {
return String.format("XmlCdataChunk{line=%d, comment=%s, value=%s}",
getLineNumber(), getComment(), getRawValue());
}
}
@@ -0,0 +1,51 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.nio.ByteBuffer;
/**
* Represents an XML chunk structure.
*
* <p>An XML chunk can contain many nodes as well as a string pool which contains all of the strings
* referenced by the nodes.
*/
public final class XmlChunk extends ChunkWithChunks {
XmlChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
}
@Override
protected Type getType() {
return Type.XML;
}
/**
* Returns a string at the provided (0-based) index if the index exists in the string pool.
*/
public String getString(int index) {
for (Chunk chunk : getChunks().values()) {
if (chunk instanceof StringPoolChunk) {
return ((StringPoolChunk) chunk).getString(index);
}
}
throw new IllegalStateException("XmlChunk did not contain a string pool.");
}
}
@@ -0,0 +1,86 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Represents the end of an XML node.
*/
public final class XmlEndElementChunk extends XmlNodeChunk {
/**
* A string reference to the namespace URI, or -1 if not present.
*/
private final int namespace;
/**
* A string reference to the attribute name.
*/
private final int name;
XmlEndElementChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
namespace = buffer.getInt();
name = buffer.getInt();
}
/**
* Returns the namespace URI, or the empty string if no namespace is present.
*/
public String getNamespace() {
return getString(namespace);
}
/**
* Returns the attribute name.
*/
public String getName() {
return getString(name);
}
@Override
protected Type getType() {
return Type.XML_END_ELEMENT;
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
super.writePayload(output, header, shrink);
output.writeInt(namespace);
output.writeInt(name);
}
/**
* Returns a brief description of this XML node. The representation of this information is
* subject to change, but below is a typical example:
*
* <pre>
* "XmlEndElementChunk{line=1234, comment=My awesome comment., namespace=foo, name=bar}"
* </pre>
*/
@Override
public String toString() {
return String.format("XmlEndElementChunk{line=%d, comment=%s, namespace=%s, name=%s}",
getLineNumber(), getComment(), getNamespace(), getName());
}
}
@@ -0,0 +1,81 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Represents the start/end of a namespace in an XML document.
*/
public abstract class XmlNamespaceChunk extends XmlNodeChunk {
/**
* A string reference to the namespace prefix.
*/
private final int prefix;
/**
* A string reference to the namespace URI.
*/
private final int uri;
protected XmlNamespaceChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
prefix = buffer.getInt();
uri = buffer.getInt();
}
/**
* Returns the namespace prefix.
*/
public String getPrefix() {
return getString(prefix);
}
/**
* Returns the namespace URI.
*/
public String getUri() {
return getString(uri);
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
super.writePayload(output, header, shrink);
output.writeInt(prefix);
output.writeInt(uri);
}
/**
* Returns a brief description of this namespace chunk. The representation of this information is
* subject to change, but below is a typical example:
*
* <pre>
* "XmlNamespaceChunk{line=1234, comment=My awesome comment., prefix=foo, uri=com.google.foo}"
* </pre>
*/
@Override
public String toString() {
return String.format("XmlNamespaceChunk{line=%d, comment=%s, prefix=%s, uri=%s}",
getLineNumber(), getComment(), getPrefix(), getUri());
}
}
@@ -0,0 +1,36 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.nio.ByteBuffer;
/**
* Represents the ending tag of a namespace in an XML document.
*/
public final class XmlNamespaceEndChunk extends XmlNamespaceChunk {
XmlNamespaceEndChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
}
@Override
protected Type getType() {
return Type.XML_END_NAMESPACE;
}
}
@@ -0,0 +1,36 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.nio.ByteBuffer;
/**
* Represents the starting tag of a namespace in an XML document.
*/
public final class XmlNamespaceStartChunk extends XmlNamespaceChunk {
XmlNamespaceStartChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
}
@Override
protected Type getType() {
return Type.XML_START_NAMESPACE;
}
}
@@ -0,0 +1,109 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.nio.ByteBuffer;
/**
* The common superclass for the various types of XML nodes.
*/
public abstract class XmlNodeChunk extends Chunk {
/**
* The line number in the original source at which this node appeared.
*/
private final int lineNumber;
/**
* A string reference of this node's comment. If this is -1, then there is no comment.
*/
private final int comment;
protected XmlNodeChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
lineNumber = buffer.getInt();
comment = buffer.getInt();
}
/**
* Returns true if this XML node contains a comment. Else, returns false.
*/
public boolean hasComment() {
return comment != -1;
}
/**
* Returns the line number in the original source at which this node appeared.
*/
public int getLineNumber() {
return lineNumber;
}
/**
* Returns the comment associated with this node, if any. Else, returns the empty string.
*/
public String getComment() {
return getString(comment);
}
/**
* An {@link XmlNodeChunk} does not know by itself what strings its indices reference. In order
* to get the actual string, the first {@link XmlChunk} ancestor is found. The
* {@link XmlChunk} ancestor should have a string pool which {@code index} references.
*
* @param index The index of the string.
* @return String that the given {@code index} references, or empty string if {@code index} is -1.
*/
protected String getString(int index) {
if (index == -1) { // Special case. Packed XML files use -1 for "no string entry"
return "";
}
Chunk parent = getParent();
while (parent != null) {
if (parent instanceof XmlChunk) {
return ((XmlChunk) parent).getString(index);
}
parent = parent.getParent();
}
throw new IllegalStateException("XmlNodeChunk did not have an XmlChunk parent.");
}
/**
* An {@link XmlNodeChunk} and anything that is itself an {@link XmlNodeChunk} has a header size
* of 16. Anything else is, interestingly, considered to be a payload. For that reason, this
* method is final.
*/
@Override
protected final void writeHeader(ByteBuffer output) {
super.writeHeader(output);
output.putInt(lineNumber);
output.putInt(comment);
}
/**
* Returns a brief description of this XML node. The representation of this information is
* subject to change, but below is a typical example:
*
* <pre>"XmlNodeChunk{line=1234, comment=My awesome comment.}"</pre>
*/
@Override
public String toString() {
return String.format("XmlNodeChunk{line=%d, comment=%s}", getLineNumber(), getComment());
}
}
@@ -0,0 +1,91 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Represents an XML resource map chunk.
*
* <p>This chunk maps attribute ids to the resource ids of the attribute resource that defines the
* attribute (e.g. type, enum values, etc.).
*/
public class XmlResourceMapChunk extends Chunk {
/**
* The size of a resource reference for {@code resources} in bytes.
*/
private static final int RESOURCE_SIZE = 4;
/**
* Contains a mapping of attributeID to resourceID. For example, the attributeID 2 refers to the
* resourceID returned by {@code resources.get(2)}.
*/
private final List<Integer> resources = new ArrayList<>();
protected XmlResourceMapChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
}
@Override
protected void init(ByteBuffer buffer) {
super.init(buffer);
resources.addAll(enumerateResources(buffer));
}
private List<Integer> enumerateResources(ByteBuffer buffer) {
int resourceCount = (getOriginalChunkSize() - getHeaderSize()) / RESOURCE_SIZE;
List<Integer> result = new ArrayList<>(resourceCount);
int offset = this.offset + getHeaderSize();
buffer.mark();
buffer.position(offset);
for (int i = 0; i < resourceCount; ++i) {
result.add(buffer.getInt());
}
buffer.reset();
return result;
}
/**
* Returns the resource ID that this {@code attributeId} maps to.
*/
public BinaryResourceIdentifier getResourceId(int attributeId) {
return BinaryResourceIdentifier.create(resources.get(attributeId));
}
@Override
protected Type getType() {
return Type.XML_RESOURCE_MAP;
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
super.writePayload(output, header, shrink);
for (Integer resource : resources) {
output.writeInt(resource);
}
}
}
@@ -0,0 +1,169 @@
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.devrel.gmscore.tools.apk.arsc;
import androidx.annotation.Nullable;
import com.google.common.base.Preconditions;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Represents the beginning of an XML node.
*/
public final class XmlStartElementChunk extends XmlNodeChunk {
/**
* A string reference to the namespace URI, or -1 if not present.
*/
private final int namespace;
/**
* A string reference to the element name that this chunk represents.
*/
private final int name;
/**
* The offset to the start of the attributes payload.
*/
private final int attributeStart;
/**
* The number of attributes in the original buffer.
*/
private final int attributeCount;
/**
* The (0-based) index of the id attribute, or -1 if not present.
*/
private final int idIndex;
/**
* The (0-based) index of the class attribute, or -1 if not present.
*/
private final int classIndex;
/**
* The (0-based) index of the style attribute, or -1 if not present.
*/
private final int styleIndex;
/**
* The XML attributes associated with this element.
*/
private final List<XmlAttribute> attributes = new ArrayList<>();
XmlStartElementChunk(ByteBuffer buffer, @Nullable Chunk parent) {
super(buffer, parent);
namespace = buffer.getInt();
name = buffer.getInt();
attributeStart = (buffer.getShort() & 0xFFFF);
int attributeSize = (buffer.getShort() & 0xFFFF);
Preconditions.checkState(attributeSize == XmlAttribute.SIZE,
"attributeSize is wrong size. Got %s, want %s", attributeSize, XmlAttribute.SIZE);
attributeCount = (buffer.getShort() & 0xFFFF);
// The following indices are 1-based and need to be adjusted.
idIndex = (buffer.getShort() & 0xFFFF) - 1;
classIndex = (buffer.getShort() & 0xFFFF) - 1;
styleIndex = (buffer.getShort() & 0xFFFF) - 1;
}
@Override
protected void init(ByteBuffer buffer) {
super.init(buffer);
attributes.addAll(enumerateAttributes(buffer));
}
private List<XmlAttribute> enumerateAttributes(ByteBuffer buffer) {
List<XmlAttribute> result = new ArrayList<>(attributeCount);
int offset = this.offset + getHeaderSize() + attributeStart;
int endOffset = offset + XmlAttribute.SIZE * attributeCount;
buffer.mark();
buffer.position(offset);
while (offset < endOffset) {
result.add(XmlAttribute.create(buffer, this));
offset += XmlAttribute.SIZE;
}
buffer.reset();
return result;
}
/**
* Returns the namespace URI, or the empty string if not present.
*/
public String getNamespace() {
return getString(namespace);
}
/**
* Returns the element name that this chunk represents.
*/
public String getName() {
return getString(name);
}
/**
* Returns an unmodifiable list of this XML element's attributes.
*/
public List<XmlAttribute> getAttributes() {
return Collections.unmodifiableList(attributes);
}
@Override
protected Type getType() {
return Type.XML_START_ELEMENT;
}
@Override
protected void writePayload(DataOutput output, ByteBuffer header, boolean shrink)
throws IOException {
super.writePayload(output, header, shrink);
output.writeInt(namespace);
output.writeInt(name);
output.writeShort((short) XmlAttribute.SIZE); // attribute start
output.writeShort((short) XmlAttribute.SIZE);
output.writeShort((short) attributes.size());
output.writeShort((short) (idIndex + 1));
output.writeShort((short) (classIndex + 1));
output.writeShort((short) (styleIndex + 1));
for (XmlAttribute attribute : attributes) {
output.write(attribute.toByteArray(shrink));
}
}
/**
* Returns a brief description of this XML node. The representation of this information is
* subject to change, but below is a typical example:
*
* <pre>
* "XmlStartElementChunk{line=1234, comment=My awesome comment., namespace=foo, name=bar, ...}"
* </pre>
*/
@Override
public String toString() {
return String.format(
"XmlStartElementChunk{line=%d, comment=%s, namespace=%s, name=%s, attributes=%s}",
getLineNumber(), getComment(), getNamespace(), getName(), attributes.toString());
}
}
@@ -0,0 +1,77 @@
package com.vk.api.audio;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.vk.api.base.ApiRequest;
import com.vk.dto.music.MusicTrack;
import com.vk.log.L;
import org.json.JSONObject;
import ru.vtosters.hooks.other.Preferences;
import ru.vtosters.lite.music.Genius;
import ru.vtosters.lite.utils.AndroidUtils;
import java.util.ArrayList;
public class AudioGetLyrics extends ApiRequest<AudioGetLyrics.a> {
private final MusicTrack musicTrack;
public AudioGetLyrics(int lyrics_id, String audio_id, MusicTrack mt) {
super("audio.getLyrics");
c("audio_id", audio_id);
musicTrack = mt;
}
/* renamed from: a */
public a a(@NonNull JSONObject jSONObject) {
var aVar = new a();
if (Preferences.getBoolValue("useGenius", false) && !Preferences.serverFeaturesDisable()) {
aVar.a = Genius.getTextMusic(musicTrack);
return aVar;
}
try {
var lines = new ArrayList<>();
var lyrics = jSONObject.getJSONObject("response").getJSONObject("lyrics");
if (lyrics.has("timestamps")) {
var timestamps = lyrics.getJSONArray("timestamps");
for (int i = 0; i < timestamps.length(); i++) {
var timestamp = timestamps.getJSONObject(i);
if (timestamp.has("line")) {
lines.add(timestamp.getString("line"));
}
if (timestamp.optString("interlude").length() > 0) {
lines.add("♪");
}
}
aVar.a = TextUtils.join("\n", lines);
} else if (lyrics.has("text")) {
var text = lyrics.getJSONArray("text");
for (int i = 0; i < text.length(); i++) {
lines.add(text.getString(i));
}
aVar.a = TextUtils.join("\n", lines);
} else {
L.e("vk", "No text found");
aVar.a = "No text found";
}
return aVar;
} catch (Exception e) {
L.e("vk", e);
aVar.a = AndroidUtils.getString("failed_to_get_text") + "\n\n" + AndroidUtils.getString("error") + ": \n" + e.getLocalizedMessage();
return aVar;
}
}
public static class a {
public String a;
}
}
@@ -1,24 +1,12 @@
package com.vk.api.gifts;
import android.content.Context;
import com.vk.api.base.ApiRequest;
import com.vk.dto.gift.CatalogedGift;
import org.json.JSONException;
import org.json.JSONObject;
public class GiftGetByStickerId extends ApiRequest<GiftGetByStickerId.a> {
public static class a {
public final int a;
public final CatalogedGift b;
public a(int i, CatalogedGift catalogedGift) {
this.a = i;
this.b = catalogedGift;
}
}
public GiftGetByStickerId(Context context, int i) {
super("execute.getGiftByStickerId");
b("sticker_id", i);
@@ -29,7 +17,17 @@ public class GiftGetByStickerId extends ApiRequest<GiftGetByStickerId.a> {
@Override // com.vk.api.sdk.o.VKRequest
public GiftGetByStickerId.a a(JSONObject jSONObject) throws JSONException {
JSONObject jSONObject2 = jSONObject.getJSONObject("response");
return new a(jSONObject2.optInt("balance"),
return new a(jSONObject2.optInt("balance"),
new CatalogedGift(jSONObject2.getJSONObject("gift")));
}
public static class a {
public final int a;
public final CatalogedGift b;
public a(int i, CatalogedGift catalogedGift) {
this.a = i;
this.b = catalogedGift;
}
}
}
@@ -0,0 +1,200 @@
package com.vk.contacts;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.vk.core.dialogs.alert.VkAlertDialog;
import com.vk.core.ui.themes.VKThemeHelper;
import com.vk.core.util.ContextExtKt;
import com.vk.navigation.NavigatorKeys;
import com.vk.permission.PermissionHelper;
import com.vtosters.lite.R;
import com.vtosters.lite.VKActivity;
import com.vtosters.lite.activities.LogoutReceiver;
import java.util.List;
import kotlin.Unit;
import kotlin.jvm.b.Functions;
import kotlin.jvm.b.Functions2;
public class ContactsSyncAcitvity extends VKActivity implements View.OnClickListener {
private boolean I;
private View J;
private RadioButton K;
private RadioButton L;
private RadioButton M;
@Nullable
private String G = null;
private int H = 2;
private LogoutReceiver N = null;
public static void a(Context context) {
b(context, ContactsSyncUtils.b());
}
public static void b(Context context, int i) {
a(context, i, null);
}
private void f(int i) {
this.H = i;
this.K.setChecked(i == 0);
this.L.setChecked(i == 1);
this.M.setChecked(i == 2);
CheckBox checkBox = this.J.findViewById(R.id.sync_big_pictures);
checkBox.setEnabled(i != 2);
if (i == 2) {
checkBox.setChecked(false);
}
}
private void onDismiss() {
ContactsSyncReporter.a.a(ContactsSyncUtils.b(), this.G);
finish();
}
private void x1() {
this.H = getIntent().getIntExtra("force_select_sync_contacts", ContactsSyncUtils.b());
this.I = ContactsSyncUtils.d();
this.K = this.J.findViewById(R.id.welcome_sync_opt1);
this.L = this.J.findViewById(R.id.welcome_sync_opt2);
this.M = this.J.findViewById(R.id.welcome_sync_opt3);
this.K.setChecked(this.H == 0);
this.L.setChecked(this.H == 1);
this.M.setChecked(this.H == 2);
this.J.findViewById(R.id.welcome_sync1).setOnClickListener(this);
this.J.findViewById(R.id.welcome_sync2).setOnClickListener(this);
this.J.findViewById(R.id.welcome_sync3).setOnClickListener(this);
CheckBox checkBox = this.J.findViewById(R.id.sync_big_pictures);
checkBox.setChecked(this.I);
checkBox.setEnabled(this.H != 2);
checkBox.setOnCheckedChangeListener(ContactsSyncAcitvity.this::a);
VkAlertDialog.Builder builder = new VkAlertDialog.Builder(this);
builder.setTitle(R.string.sett_sync);
builder.setView(this.J);
builder.setCancelable(false);
builder.setPositiveButton(R.string.save, ContactsSyncAcitvity.this::a);
builder.setNegativeButton(R.string.cancel, ContactsSyncAcitvity.this::b);
builder.show();
}
public Unit c(List list) {
ContactsSyncReporter.a.a(this.G);
finish();
return Unit.a;
}
@SuppressLint("NonConstantResourceId")
@Override // android.view.View.OnClickListener
public void onClick(View view) {
switch (view.getId()) {
case R.id.welcome_sync1 /* 2131365835 */:
f(0);
return;
case R.id.welcome_sync2 /* 2131365836 */:
f(1);
return;
case R.id.welcome_sync3 /* 2131365837 */:
f(2);
return;
default:
}
}
@Override // com.vtosters.lite.VKActivity, com.vk.core.ui.themes.ThemableActivity, androidx.appcompat.app.AppCompatActivity, androidx.fragment.app.FragmentActivity, androidx.core.app.ComponentActivity, android.app.Activity
public void onCreate(Bundle bundle) {
setTheme(VKThemeHelper.n());
super.onCreate(bundle);
this.G = getIntent().getStringExtra(NavigatorKeys.l0);
this.N = LogoutReceiver.a(this);
overridePendingTransition(0, 0);
getWindow().setBackgroundDrawableResource(R.drawable.transparent);
setContentView(new View(this));
this.J = View.inflate(new ContextThemeWrapper(this, VKThemeHelper.n()), R.layout.welcome, null);
VKThemeHelper.d(this);
PermissionHelper permissionHelper = PermissionHelper.r;
permissionHelper.a(this, permissionHelper.e(), R.string.permissions_contacts_sync, R.string.permissions_contacts_sync_settings, new Functions() { // from class: com.vk.contacts.c
@Override // kotlin.jvm.b.Functions
public Object invoke() {
return ContactsSyncAcitvity.this.w1();
}
}, new Functions2() { // from class: com.vk.contacts.a
@Override // kotlin.jvm.b.Functions2
public Object invoke(Object obj) {
return ContactsSyncAcitvity.this.c((List) obj);
}
});
}
@Override // com.vtosters.lite.VKActivity, androidx.appcompat.app.AppCompatActivity, androidx.fragment.app.FragmentActivity, android.app.Activity
public void onDestroy() {
this.N.a();
super.onDestroy();
}
@Override // android.app.Activity
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
this.H = bundle.getInt("state_option", 2);
this.I = bundle.getBoolean("state_sync_hq_photo", false);
f(this.H);
}
@Override // androidx.appcompat.app.AppCompatActivity, androidx.fragment.app.FragmentActivity, androidx.core.app.ComponentActivity, android.app.Activity
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putInt("state_option", this.H);
bundle.putBoolean("state_sync_hq_photo", this.I);
}
public Unit w1() {
x1();
return Unit.a;
}
public static void a(Context context, int i, @Nullable String str) {
Intent intent = new Intent(context, ContactsSyncAcitvity.class);
intent.setAction("syncsettings");
intent.putExtra("force_select_sync_contacts", i);
intent.putExtra(NavigatorKeys.l0, str);
if (ContextExtKt.e(context) == null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
}
public void b(DialogInterface dialogInterface, int i) {
onDismiss();
}
public void a(CompoundButton compoundButton, boolean z) {
this.I = z;
}
public void a(DialogInterface dialogInterface, int i) {
ContactsSyncUtils.b(this.H);
ContactsSyncUtils.a(this.I);
Intent intent = new Intent();
intent.putExtra("option", this.H);
setResult(-1, intent);
onDismiss();
}
public void a(DialogInterface dialogInterface) {
onDismiss();
}
}
@@ -0,0 +1,45 @@
package com.vk.contacts;
import com.vk.metrics.eventtracking.Event;
import com.vk.metrics.eventtracking.VkTracker;
import com.vk.navigation.NavigatorKeys;
public final class ContactsSyncReporter {
public static final ContactsSyncReporter a = new ContactsSyncReporter();
private static final String EVENT_NAME = "LoggingTracker";
private static final String ENABLE_CONTACTS_SYNC = "enable_contacts_sync";
private static final String HAS_CONTACTS_PERMISSION = "has_contacts_permission";
private static final String SELECTED_SYNC_OPTION = "selected_sync_option";
private static final String NAVIGATOR_KEYS_L0 = NavigatorKeys.l0;
private ContactsSyncReporter() {
}
private static Event createEvent(boolean z, int i, String str) {
Event.a a2 = Event.b.a();
a2.a(EVENT_NAME);
a2.a(ENABLE_CONTACTS_SYNC);
a2.a(HAS_CONTACTS_PERMISSION, z);
a2.a(SELECTED_SYNC_OPTION, i != 0 ? (i != 1 ? "disabled" : "contacts") : "all");
if (str == null) {
str = "";
}
a2.a(NAVIGATOR_KEYS_L0, str);
return a2.a();
}
public void a(String str) {
a(false, 2, str);
}
public void a(int i, String str) {
a(true, i, str);
}
private void a(boolean z, int i, String str) {
VkTracker vkTracker = VkTracker.k;
Event event = createEvent(z, i, str);
vkTracker.a(event);
}
}
@@ -0,0 +1,112 @@
package com.vk.contacts;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import com.vk.auth.VKAuthUtils;
import com.vk.core.concurrent.VkExecutors;
import com.vk.core.preference.Preference;
import com.vk.core.util.AppContextHolder;
import com.vk.metrics.eventtracking.VkTracker;
import com.vtosters.lite.auth.VKAccountManager;
public final class ContactsSyncUtils {
private static final SharedPreferences prefs;
static {
prefs = Preference.b();
}
public static void a(boolean z) { // setSyncHqPhotos
try {
prefs.edit().putBoolean("sync_hq_photos", z).apply();
Log.d("Contacts", "setSyncHqPhotos");
} catch (Exception e) {
VkTracker.k.b(e);
e.fillInStackTrace();
}
}
public static void b(int i) { // setSyncOption
try {
prefs.edit().putInt("key_sync_option", i).apply();
syncAccount(i);
Log.d("Contacts", "setSyncOption");
} catch (Exception e) {
VkTracker.k.b(e);
e.fillInStackTrace();
}
}
public static boolean d() { // getSyncHqPhotos
return prefs.getBoolean("sync_hq_photos", false);
}
public static void e() { // syncAccount
syncAccount(b());
Log.d("Contacts", "syncAccount");
}
public static int b() { // getSyncOption
Account[] accounts;
try {
AccountManager accountManager = AccountManager.get(AppContextHolder.a);
accounts = accountManager.getAccountsByType("com.vkontakte.account");
if (accounts.length == 0) {
Account account = new Account(VKAccountManager.d().Z(), "com.vkontakte.account");
try {
accountManager.addAccountExplicitly(account, null, null);
} catch (Exception e) {
VkTracker.k.a(e);
e.fillInStackTrace();
}
accounts = new Account[]{account};
}
if (ContentResolver.getSyncAutomatically(accounts[0], "com.android.contacts")) {
if (prefs.contains("key_sync_option")) {
return prefs.getInt("key_sync_option", 2);
}
if (prefs.contains("sync_all")) {
return prefs.getBoolean("sync_all", false) ? 0 : 1;
}
return 2;
}
return 2;
} catch (Exception e2) {
VkTracker.k.b(e2);
e2.fillInStackTrace();
return 2;
}
}
private static void syncAccount(int i) {
Log.d("Contacts", String.valueOf(i));
if (!VKAccountManager.d().b1()) {
syncAllAccounts();
Log.d("Contacts", "VKAccountManager.d().b1() is not false");
return;
}
Account account = VKAuthUtils.a.a(VKAccountManager.d().Z());
if (i != 2 && account != null) {
syncSingleAccount(account);
Log.d("Contacts", "sync single account, account is " + account);
} else {
syncAllAccounts();
Log.d("Contacts", "sync all accounts, account is " + account);
}
}
private static void syncSingleAccount(Account account) {
Bundle bundle = new Bundle();
bundle.putBoolean("com.vtosters.lite.EXTRA_FORCE_KEY", true);
ContentResolver.requestSync(account, "com.android.contacts", bundle);
VkExecutors.x.l().submit(() -> ContactsSyncAdapterService.a(AppContextHolder.a, account, new Bundle()));
}
private static void syncAllAccounts() {
VkExecutors.x.l().submit(() -> ContactsSyncAdapterService.a(AppContextHolder.a.getContentResolver()));
}
}
@@ -27,6 +27,15 @@ public class RecoloredDrawable extends Drawable implements Drawable.Callback {
onStateChange(new int[0]);
}
public RecoloredDrawable(Drawable drawable, int i) {
this(drawable, new ColorStateList(new int[][]{new int[0]}, new int[]{i}));
}
public RecoloredDrawable() {
this.c = 255;
this.d = 255;
}
public void a(int i) {
a(new ColorStateList(new int[][]{new int[0]}, new int[]{i}));
}
@@ -120,13 +129,4 @@ public class RecoloredDrawable extends Drawable implements Drawable.Callback {
public Drawable a() {
return this.drawable;
}
public RecoloredDrawable(Drawable drawable, int i) {
this(drawable, new ColorStateList(new int[][]{new int[0]}, new int[]{i}));
}
public RecoloredDrawable() {
this.c = 255;
this.d = 255;
}
}
@@ -0,0 +1,128 @@
package com.vk.core.extensions;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.AttrRes;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import b.h.v.InitialValueObservable;
import b.h.v.TextViewTextChangeEvent;
import b.h.v.TextViewTextChangeEventObservable;
import com.vk.core.util.ContextExtKt;
import ru.vtosters.hooks.other.ThemesUtils;
public final class TextViewExt {
public static void a(TextView textView, Drawable drawable) {
a(textView, null, drawable);
}
public static boolean b(TextView textView) {
return textView == null || TextUtils.isEmpty(textView.getEditableText());
}
public static InitialValueObservable<TextViewTextChangeEvent> c(TextView textView) {
return new TextViewTextChangeEventObservable(textView);
}
public static void d(TextView textView, @DrawableRes int i, @AttrRes int i2) {
b(textView, ThemesUtils.recolorDrawable(ContextExtKt.a(textView.getContext(), i, ContextExtKt.h(textView.getContext(), i2))));
}
public static void a(TextView textView, Drawable drawable, ColorStateList colorStateList) {
a(textView, null, a(drawable, colorStateList));
}
public static void b(TextView textView, Drawable drawable) {
a(textView, drawable, (Drawable) null);
}
public static void c(TextView textView, @DrawableRes int i, @ColorRes int i2) {
if (i == 0) {
b(textView, null);
} else if (i2 == 0) {
b(textView, ContextCompat.getDrawable(textView.getContext(), i));
} else {
b(textView, ContextCompat.getDrawable(textView.getContext(), i), ContextCompat.getColorStateList(textView.getContext(), i2));
}
}
public static void d(TextView textView, int i) {
textView.setTextSize(0, i);
}
public static void a(TextView textView, @DrawableRes int i) {
a(textView, i, 0);
}
public static void b(TextView textView, Drawable drawable, ColorStateList colorStateList) {
a(textView, a(drawable, colorStateList), (Drawable) null);
}
public static void a(TextView textView, @DrawableRes int i, @ColorRes int i2) {
if (i == 0) {
a(textView, (Drawable) null);
} else if (i2 == 0) {
a(textView, ContextCompat.getDrawable(textView.getContext(), i));
} else {
a(textView, ContextCompat.getDrawable(textView.getContext(), i), ContextCompat.getColorStateList(textView.getContext(), i2));
}
}
public static void b(TextView textView, @DrawableRes int i) {
c(textView, i, 0);
}
public static void b(TextView textView, @DrawableRes int i, @AttrRes int i2) {
if (i == 0) {
a(textView, (Drawable) null);
} else if (i2 == 0) {
a(textView, ContextCompat.getDrawable(textView.getContext(), i));
} else {
Drawable drawable = ContextCompat.getDrawable(textView.getContext(), i);
a(textView, drawable, ColorStateList.valueOf(ContextExtKt.h(textView.getContext(), i2)));
}
}
public static void c(TextView textView, @ColorRes int i) {
textView.setTextColor(ContextExtKt.a(textView.getContext(), i));
}
private static void a(TextView textView, Drawable drawable, Drawable drawable2) {
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, drawable2, null);
}
public static void a(TextView textView) {
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null);
}
public static Drawable a(Drawable drawable, ColorStateList colorStateList) {
if (colorStateList == null) return drawable;
if (drawable != null) {
Drawable wrap = DrawableCompat.wrap(drawable.mutate());
DrawableCompat.setTintList(wrap, colorStateList);
return wrap;
}
return null;
}
public static void a(TextView textView, CharSequence charSequence) {
if (TextUtils.isEmpty(charSequence)) {
textView.setVisibility(View.GONE);
return;
}
textView.setVisibility(View.VISIBLE);
textView.setText(charSequence);
}
public static void a(TextView textView, float f) {
textView.setTextSize(0, f);
}
}
@@ -11,13 +11,15 @@ import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import b.h.g.m.CameraUtils;
import b.h.g.m.FileUtils;
import com.facebook.common.i.MediaUtils;
import com.facebook.x.g.EncodedImage;
import com.vk.imageloader.VKImageLoader;
import com.vk.log.L;
import com.vk.metrics.eventtracking.VkTracker;
import com.vtosters.lite.R;
import ru.vtosters.lite.concurrent.VTExecutors;
import java.io.File;
import java.io.FileOutputStream;
@@ -26,10 +28,6 @@ import java.io.InputStream;
import java.net.URI;
import java.util.HashSet;
import b.h.g.m.CameraUtils;
import b.h.g.m.FileUtils;
import ru.vtosters.lite.concurrent.VTExecutors;
public class DownloadUtils {
public static final HashSet<Long> a = new HashSet<>();
@@ -49,7 +47,7 @@ public class DownloadUtils {
ToastUtils.a(context.getString(R.string.error) + " [" + e2.getMessage() + "]");
}
}
private static void b(final Context context, String str, String uri, boolean z) {
if (TextUtils.isEmpty(uri)) {
return;
@@ -191,7 +189,7 @@ public class DownloadUtils {
if (!file.exists()) {
return false;
}
Intent intent = new Intent("android.intent.action.VIEW");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
var mimeType = FileUtils.f(file);
var uri = FileUtils.uriFromFile(file);
@@ -222,7 +220,7 @@ public class DownloadUtils {
var mimeType = FileUtils.f(file);
var uri = FileUtils.uriFromFile(file);
Intent intent = new Intent("android.intent.action.VIEW");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, mimeType);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.d("DownloadUtils", "openFile: " + file.getAbsolutePath() + "| mimetype " + mimeType + "| uri " + uri);
@@ -0,0 +1,268 @@
package com.vk.core.utils;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import b.h.z.e;
import com.vk.core.drawable.RecoloredDrawable;
import com.vk.core.extensions.TextViewExt;
import com.vk.core.ui.themes.MilkshakeHelper;
import com.vk.core.ui.themes.VKThemeHelper;
import com.vk.dto.common.VerifyInfo;
import com.vk.extensions.ViewExtKt;
import com.vtosters.lite.R;
import ru.vtosters.hooks.other.ThemesUtils;
public final class VerifyInfoHelper {
public static final VerifyInfoHelper h;
public static int devIcon = R.drawable.ic_favorite_16;
static {
h = new VerifyInfoHelper();
}
private VerifyInfoHelper() {
}
public static Integer enumSwitchMapping(VerifyInfoHelper.ColorTheme color) {
return switch (color) {
case normal -> 1;
case light -> 2;
case ultraLight -> 3;
case white -> 4;
};
}
public static Drawable b(VerifyInfoHelper verifyInfoHelper, boolean z, boolean z2, boolean dev, Context context, ColorTheme colorTheme, int i, Object obj) {
if ((i & 8) != 0) {
colorTheme = ColorTheme.normal;
}
return verifyInfoHelper.b(z, z2, dev, context, colorTheme);
}
public static Drawable b(VerifyInfoHelper verifyInfoHelper, VerifyInfo verifyInfo, Context context, ColorTheme colorTheme, int i, Object obj) {
return b(verifyInfoHelper, verifyInfo.u1(), verifyInfo.t1(), verifyInfo.dev(), context, colorTheme, i, obj);
}
public static Drawable b(VerifyInfoHelper verifyInfoHelper, boolean z, boolean z2, Context context, ColorTheme colorTheme, int i, Object obj) {
return b(verifyInfoHelper, z, z2, false, context, colorTheme, i, obj);
}
public static Drawable a(VerifyInfoHelper verifyInfoHelper, VerifyInfo verifyInfo, Context context, ColorTheme colorTheme, int i, Object obj) {
if ((i & 4) != 0) {
colorTheme = ColorTheme.normal;
}
return verifyInfoHelper.b(verifyInfo, context, colorTheme);
}
public static Drawable a(VerifyInfoHelper verifyInfoHelper, boolean z, boolean z2, boolean dev, Context context, ColorTheme colorTheme, int i, Object obj) {
if ((i & 8) != 0) {
colorTheme = ColorTheme.normal;
}
return verifyInfoHelper.a(z, z2, dev, context, colorTheme);
}
public static Drawable a(VerifyInfoHelper verifyInfoHelper, boolean z, boolean z2, Context context, ColorTheme colorTheme, int i, Object obj) {
return a(verifyInfoHelper, z, z2, false, context, colorTheme, i, obj);
}
public static void a(VerifyInfoHelper verifyInfoHelper, TextView textView, VerifyInfo verifyInfo, boolean z, ColorTheme colorTheme, int i, Object obj) {
if ((i & 4) != 0) {
z = false;
}
if ((i & 8) != 0) {
colorTheme = ColorTheme.normal;
}
verifyInfoHelper.a(textView, verifyInfo, z, colorTheme);
}
private int a() {
return ThemesUtils.getAccentColor();
}
private int b() {
return ThemesUtils.getAccentColor();
}
private int c() {
return ThemesUtils.getColor(R.color.fire_orange);
}
private int d() {
return ThemesUtils.getColor(R.color.light_blue);
}
private int e() {
return ThemesUtils.getColor(R.color.white_alpha60);
}
private int f() {
return ThemesUtils.getColor(R.color.white);
}
public int a(ColorTheme colorTheme) {
return switch (enumSwitchMapping(colorTheme)) {
case 1, 2 -> c();
case 3 -> e();
case 4 -> d();
default -> 0;
};
}
public Drawable a(VerifyInfo verifyInfo, Context context) {
return a(this, verifyInfo, context, null, 4, null);
}
public Drawable a(boolean z, boolean z2, boolean dev, Context context) {
return b(this, z, z2, dev, context, null, 8, null);
}
public Drawable a(boolean z, boolean z2, Context context) {
return b(this, z, z2, false, context, null, 8, null);
}
public int b(ColorTheme colorTheme) {
return a(colorTheme);
}
public int c(ColorTheme colorTheme) {
return switch (enumSwitchMapping(colorTheme)) {
case 1 -> MilkshakeHelper.e() ? b() : a();
case 2 -> d();
case 3 -> e();
case 4 -> f();
default -> 0;
};
}
public Drawable b(Context context, VerifyInfo verifyInfo) {
if (verifyInfo.dev()) {
return new RecoloredDrawable(ContextCompat.getDrawable(context, devIcon), c(ColorTheme.normal));
} else if (verifyInfo.t1() && verifyInfo.u1()) {
return ContextCompat.getDrawable(context, e.ic_fire_verified_border_composite_20_xml);
} else if (verifyInfo.t1()) {
return ContextCompat.getDrawable(context, e.ic_fire_border_composite_20_xml);
} else if (verifyInfo.u1()) {
return new RecoloredDrawable(ContextCompat.getDrawable(context, e.verified_16), c(ColorTheme.normal));
}
return null;
}
public Drawable b(VerifyInfo verifyInfo, Context context, ColorTheme colorTheme) {
return b(verifyInfo.u1(), verifyInfo.t1(), verifyInfo.dev(), context, colorTheme);
}
public Drawable a(Context context, VerifyInfo verifyInfo) {
if (verifyInfo.dev()) {
return new RecoloredDrawable(ContextCompat.getDrawable(context, devIcon), c(ColorTheme.normal));
} else if (verifyInfo.t1() && verifyInfo.u1()) {
return ContextCompat.getDrawable(context, e.ic_fire_verified_border_composite_20_xml);
} else if (verifyInfo.t1()) {
return ContextCompat.getDrawable(context, e.ic_fire_border_composite_20_xml);
} else if (verifyInfo.u1() && VKThemeHelper.s()) {
return ContextCompat.getDrawable(context, e.verified_badge_light_24);
} else if (verifyInfo.u1() && VKThemeHelper.r()) {
return ContextCompat.getDrawable(context, e.verified_badge_dark_24);
}
return null;
}
public Drawable b(boolean z, boolean z2, Context context, ColorTheme colorTheme) {
return b(z, z2, false, context, colorTheme);
}
public Drawable b(boolean z, boolean z2, boolean dev, Context context, ColorTheme colorTheme) {
int i = 0;
int c2 = 0;
if (dev) {
i = devIcon;
c2 = c(colorTheme);
} else if (z2 && z) {
i = e.ic_fire_verified_16;
c2 = b(colorTheme);
} else if (z2) {
i = e.ic_fire_16;
c2 = a(colorTheme);
} else if (z) {
i = e.verified_16;
c2 = c(colorTheme);
} else {
Log.d("VerifyInfoHelper", "Use VerifyInfo.has()");
}
return new RecoloredDrawable(ContextCompat.getDrawable(context, i), c2);
}
public Drawable a(VerifyInfo verifyInfo, Context context, ColorTheme colorTheme) {
return a(verifyInfo.u1(), verifyInfo.t1(), verifyInfo.dev(), context, colorTheme);
}
public Drawable a(boolean z, boolean z2, Context context, ColorTheme colorTheme) {
return a(z, z2, false, context, colorTheme);
}
public Drawable a(boolean z, boolean z2, boolean dev, Context context, ColorTheme colorTheme) {
int i = 0;
int c2 = 0;
if (dev) {
i = devIcon;
c2 = c(colorTheme);
} else if (z2 && z) {
i = e.ic_fire_verified_12;
c2 = b(colorTheme);
} else if (z2) {
i = e.ic_fire_12;
c2 = a(colorTheme);
} else if (z) {
i = e.verified_12;
c2 = c(colorTheme);
} else {
Log.d("VerifyInfoHelper", "Use VerifyInfo.has()");
}
return new RecoloredDrawable(ContextCompat.getDrawable(context, i), c2);
}
public void a(TextView textView, VerifyInfo verifyInfo, boolean z, ColorTheme colorTheme) {
Drawable drawable;
Context context = textView.getContext();
if (verifyInfo == null || !verifyInfo.v1() || context == null) {
drawable = null;
} else {
drawable = z ? a(verifyInfo, context, colorTheme) : b(verifyInfo, context, colorTheme);
}
TextViewExt.a(textView, drawable);
}
public void a(ImageView imageView, boolean z, VerifyInfo verifyInfo) {
Drawable b2;
if (verifyInfo != null && verifyInfo.v1()) {
if (z) {
Context context = imageView.getContext();
b2 = a(context, verifyInfo);
} else {
Context context2 = imageView.getContext();
b2 = b(context2, verifyInfo);
}
imageView.setImageDrawable(b2);
ViewExtKt.r(imageView);
return;
}
ViewExtKt.p(imageView);
}
public enum ColorTheme {
white,
normal,
light,
ultraLight
}
}
@@ -0,0 +1,11 @@
package com.vk.extensions;
import android.widget.TextView;
import androidx.annotation.AttrRes;
import com.vk.core.ui.themes.VKThemeHelper;
public final class TextViewExt {
public static void a(TextView textView, @AttrRes int i) {
VKThemeHelper.a(textView, i);
}
}
@@ -0,0 +1,238 @@
package com.vk.im.engine.commands.dialogs;
import androidx.collection.ArraySet;
import b.h.g.p.Transliteration;
import com.vk.auth.y.a.BuildConfig;
import com.vk.im.engine.ImEnvironment;
import com.vk.im.engine.commands.etc.ProfilesGetCmd;
import com.vk.im.engine.commands.etc.ProfilesInfoGetArgs;
import com.vk.im.engine.i.BaseImEngineCmd;
import com.vk.im.engine.internal.storage.utils.StringMatchStrategy;
import com.vk.im.engine.models.*;
import com.vk.im.engine.models.dialogs.DialogMember;
import com.vk.im.engine.utils.ImDialogsUtils;
import kotlin.NoWhenBranchMatchedException;
import kotlin.collections.l;
import kotlin.jvm.b.Functions2;
import kotlin.jvm.internal.Intrinsics;
import kotlin.sequences.m;
import kotlin.text.Regex;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
public final class DialogGetMentionSuggestionCmd extends BaseImEngineCmd<Suggestion> {
private final int f2365b;
private final String c;
private final Source d;
private final boolean e;
private final Object f;
public DialogGetMentionSuggestionCmd(int i, String str, Source source, boolean z, Object obj) {
this.f2365b = i;
this.c = str;
this.d = source;
this.e = z;
this.f = obj;
}
private ProfilesInfo a(ImEnvironment imEnvironment, Collection<Member> collection, Source source, boolean z, Object obj) {
ProfilesInfoGetArgs.a aVar = new ProfilesInfoGetArgs.a();
aVar.a(collection);
aVar.a(source);
aVar.a(z);
aVar.a(obj);
Object a2 = null;
try {
a2 = imEnvironment.a(this, new ProfilesGetCmd(aVar.a()));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
Intrinsics.a(a2, "env.submitCommandDirect(this, cmd)");
return (ProfilesInfo) a2;
}
private String a(String str) {
String a2 = new Regex("\\W*").a(str, BuildConfig.g);
int length = a2.length() - 1;
int i = 0;
boolean z = false;
while (i <= length) {
boolean z2 = a2.charAt(!z ? i : length) <= ' ';
if (z) {
if (!z2) {
break;
}
length--;
} else if (z2) {
i++;
} else {
z = true;
}
}
return a2.subSequence(i, length + 1).toString();
}
private Collection<Member> a(ImEnvironment imEnvironment, int i) {
var d = imEnvironment.a0().f().b().d(i);
var arrayList = new ArrayList(l.a(d, 10));
for (DialogMember dialogMember : d) {
arrayList.add(dialogMember.Z());
}
// changed
var fakeMember = new Member();
fakeMember.b(MemberType.CUSTOM_BOT);
arrayList.add(fakeMember);
return arrayList;
}
private Collection<Member> a(ImEnvironment imEnvironment, int i, String str) {
if (a(str).length() == 0) {
return l.a();
}
List<String> c = l.c(Transliteration.a.a(str), Transliteration.a.b(str));
ArraySet arraySet = new ArraySet();
for (String str2 : c) {
arraySet.addAll(imEnvironment.a0().m().a(i, str2, StringMatchStrategy.STARTING_WITH));
}
// changed
var fakeMember = new Member();
fakeMember.b(MemberType.CUSTOM_BOT);
arraySet.add(fakeMember);
return arraySet;
}
private Comparator<Member> a(List<Member> list) {
return new a(list);
}
private void a(ImEnvironment imEnvironment, int i, Source source, boolean z, Object obj) {
try {
imEnvironment.a(this, new DialogGetMembersCmd(i, source, z, obj));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private List<Member> b(ImEnvironment imEnvironment, int i) {
return imEnvironment.a0().j().a(i, Weight.d.c(), Direction.BEFORE, 100);
}
@Override // com.vk.im.engine.i.ImEngineCmd
public Suggestion a(ImEnvironment imEnvironment) {
Collection<Member> a2;
Source source;
if (ImDialogsUtils.d(this.f2365b) != PeerType.CHAT) {
return new Suggestion(null, null);
}
Member Z = imEnvironment.Z();
int d = imEnvironment.a0().n().d();
Integer e = imEnvironment.a0().f().b().e(this.f2365b);
boolean z = false;
boolean z2 = e == null;
boolean z3 = e == null || e.intValue() != d;
boolean z4 = z2 || z3;
Source source2 = this.d;
boolean z5 = source2 == Source.NETWORK || (z4 && source2 == Source.ACTUAL);
if (z5) {
a(imEnvironment, this.f2365b, this.d, this.e, this.f);
z3 = false;
z2 = false;
}
List<Member> b2 = b(imEnvironment, this.f2365b);
if (this.c.length() == 0) {
z = true;
}
if (z) {
a2 = a(imEnvironment, this.f2365b);
} else if (z) {
throw new NoWhenBranchMatchedException();
} else {
a2 = a(imEnvironment, this.f2365b, this.c);
}
var sequense = l.d(a2);
var l = m.l(m.a(m.b(sequense, new Functions2<Member, Boolean>() {
@Override
public Boolean invoke(Member member) {
return member.e(Z) && (member.a(MemberType.USER) || member.a(MemberType.GROUP));
}
}), a(b2)));
EntityValue entityValue = new EntityValue(z2 ? null : l, z3);
switch (this.d) {
case CACHE:
source = Source.CACHE;
break;
case ACTUAL:
source = Source.ACTUAL;
break;
case NETWORK:
source = Source.NETWORK;
break;
default:
throw new NoWhenBranchMatchedException();
}
return new Suggestion(entityValue, a(imEnvironment, l, source, this.e, this.f));
}
public boolean equals(Object obj) {
if (this != obj) {
if (obj instanceof DialogGetMentionSuggestionCmd) {
DialogGetMentionSuggestionCmd dialogGetMentionSuggestionCmd = (DialogGetMentionSuggestionCmd) obj;
return this.f2365b == dialogGetMentionSuggestionCmd.f2365b && this.e == dialogGetMentionSuggestionCmd.e;
}
return false;
}
return true;
}
public int hashCode() {
int i = this.f2365b;
String str = this.c;
int i2 = 0;
int hashCode = str != null ? str.hashCode() : 0;
Source source = this.d;
int hashCode2 = source != null ? source.hashCode() : 0;
boolean z = this.e;
int i3 = z ? 1 : 0;
if (z) {
i3 = 1;
}
Object obj = this.f;
if (obj != null) {
i2 = obj.hashCode();
}
return (((((((i * 31) + hashCode) * 31) + hashCode2) * 31) + i3) * 31) + i2;
}
public String toString() {
return "DialogGetMentionSuggestionCmd(dialogId=" + this.f2365b + ", query=" + this.c + ", source=" + this.d + ", isAwaitNetwork=" + this.e + ", changerTag=" + this.f + ")";
}
public static final class a<T> implements Comparator<Member> {
List a;
a(List list) {
this.a = list;
}
@Override // java.util.Comparator
/* renamed from: a */
public int compare(Member member, Member member2) {
int indexOf = this.a.indexOf(member);
int indexOf2 = this.a.indexOf(member2);
int i = indexOf;
if (indexOf < 0) {
i = Integer.MAX_VALUE;
}
int i2 = indexOf2;
if (indexOf2 < 0) {
i2 = Integer.MAX_VALUE;
}
return Intrinsics.a(i, i2);
}
}
}
@@ -0,0 +1,38 @@
package com.vk.im.engine.models;
public enum MemberType {
UNKNOWN(0),
USER(1),
GROUP(2),
EMAIL(3),
CONTACT(4),
CUSTOM_BOT(5);
private final int mTypeAsInt;
MemberType(int i) {
this.mTypeAsInt = i;
}
public static MemberType a(int i) {
switch (i) {
case 0:
return UNKNOWN;
case 1:
return USER;
case 2:
return GROUP;
case 3:
return EMAIL;
case 4:
return CONTACT;
case 5:
return CUSTOM_BOT;
}
throw new IllegalArgumentException("Unknown member type value: " + i);
}
public int a() {
return this.mTypeAsInt;
}
}
@@ -36,5 +36,6 @@ public enum DialogAction {
unpinmsg,
ENCRYPT_SETT,
ENCRYPT,
DOWNLOAD
DOWNLOAD,
STAT
}
@@ -11,16 +11,15 @@ import com.vk.im.engine.models.dialogs.Dialog;
import com.vk.im.engine.models.groups.Group;
import com.vk.im.engine.utils.DialogPermissionHelper;
import com.vk.im.ui.p.ImBridge7;
import ru.vtosters.hooks.DialogMenuInjectors;
import java.util.ArrayList;
import java.util.List;
import ru.vtosters.lite.dnr.DNRInjector;
public final class DialogActionsHelper {
public static final DialogActionsHelper a = new DialogActionsHelper();
public final List<DialogAction> a(ImConfig imConfig, Dialog dialog, ProfilesSimpleInfo profilesSimpleInfo) {
public List<DialogAction> a(ImConfig imConfig, Dialog dialog, ProfilesSimpleInfo profilesSimpleInfo) {
if (dialog != null && profilesSimpleInfo != null) {
long b2 = TimeProvider.f.b();
ChatSettings z1 = dialog.z1();
@@ -28,7 +27,7 @@ public final class DialogActionsHelper {
boolean I1 = z1 != null && z1.I1();
ArrayList<DialogAction> arrayList = new ArrayList<>();
DNRInjector.inject(dialog, arrayList);
DialogMenuInjectors.inject(dialog, arrayList);
arrayList.add(DialogAction.SEARCH);
@@ -85,7 +84,7 @@ public final class DialogActionsHelper {
return new ArrayList<>();
}
public final List<DialogAction> a(Dialog dialog, ProfilesSimpleInfo profilesSimpleInfo) {
public List<DialogAction> a(Dialog dialog, ProfilesSimpleInfo profilesSimpleInfo) {
long b2 = TimeProvider.f.b();
Profile profile = profilesSimpleInfo.get(dialog.getId());
@@ -97,7 +96,7 @@ public final class DialogActionsHelper {
ChatSettings z1 = dialog.z1();
ArrayList<DialogAction> arrayList = new ArrayList<>();
DNRInjector.inject(dialog, arrayList);
DialogMenuInjectors.inject(dialog, arrayList);
// if (dialog.hasUnread()) {
arrayList.add(DialogAction.MARK_AS_READ);
@@ -139,7 +138,7 @@ public final class DialogActionsHelper {
return arrayList;
}
public final boolean a(Dialog dialog) {
public boolean a(Dialog dialog) {
if (dialog.V1() || !dialog.y1()) {
return false;
}
@@ -11,5 +11,6 @@ public enum MsgAction {
PIN,
UNPIN,
TRANSLATE,
READTO
READTO,
KICK
}
@@ -3,9 +3,11 @@ package com.vk.im.ui.components.common;
import com.vk.core.extensions.CollectionExt;
import com.vk.im.engine.ImConfig;
import com.vk.im.engine.ImEngine;
import com.vk.im.engine.models.Member;
import com.vk.im.engine.models.dialogs.Dialog;
import com.vk.im.engine.models.messages.Msg;
import com.vk.im.engine.utils.MsgPermissionHelper;
import ru.vtosters.lite.utils.AccountManagerUtils;
import java.util.ArrayList;
import java.util.Collection;
@@ -14,11 +16,11 @@ import java.util.List;
public final class MsgActionHelper {
public static final MsgActionHelper a = new MsgActionHelper();
public final List<MsgAction> a(ImEngine imEngine, Dialog dialog, Collection<? extends Msg> collection) {
public List<MsgAction> a(ImEngine imEngine, Dialog dialog, Collection<? extends Msg> collection) {
return a(imEngine != null ? imEngine.g() : null, dialog, collection);
}
public final List<MsgAction> a(ImConfig imConfig, Dialog dialog, Collection<? extends Msg> collection) {
public List<MsgAction> a(ImConfig imConfig, Dialog dialog, Collection<? extends Msg> collection) {
if (imConfig != null && dialog != null && collection != null) {
MsgPermissionHelper.a aVar = new MsgPermissionHelper.a(imConfig, dialog, collection);
ArrayList<MsgAction> arrayList = new ArrayList<>();
@@ -35,6 +37,24 @@ public final class MsgActionHelper {
CollectionExt.a(arrayList, MsgAction.TRANSLATE, true);
CollectionExt.a(arrayList, MsgAction.READTO, true);
boolean isAdmin = false;
try {
if (aVar.a().z1().L0().t1() == AccountManagerUtils.getUserId()) { // is owner
isAdmin = true;
} else if (!aVar.a().z1().K1()) { // is you not kicked
for (Member admins : aVar.a().z1().t1()) { // admin list
if (admins.t1() == AccountManagerUtils.getUserId()) {
isAdmin = true;
break;
}
}
}
} catch (Exception ignored) {
}
CollectionExt.a(arrayList, MsgAction.KICK, isAdmin);
return arrayList;
}
@@ -0,0 +1,73 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.vk.im.ui.components.viewcontrollers.msg_list.adapter;
import android.util.SparseIntArray;
import androidx.annotation.ColorInt;
import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import com.vk.im.engine.j.StickersAnimationLoader;
import com.vk.im.engine.models.ImExperimentsProvider;
import com.vk.im.engine.models.Member;
import com.vk.im.engine.models.ProfilesSimpleInfo;
import com.vk.im.engine.models.attaches.Attach;
import com.vk.im.engine.models.messages.Msg;
import com.vk.im.engine.models.messages.NestedMsg;
import com.vk.im.ui.media.audio.AudioTrack;
import com.vk.im.ui.q.h.VideoAutoPlayer;
import com.vk.im.ui.views.span.OnSpanClickListener;
import com.vk.im.ui.views.span.OnSpanLongPressListener;
import com.vk.im.ui.views.sticker.StickerAnimationState;
import java.util.List;
@MainThread
public class MsgPartHolderBindArgs {
public SparseIntArray A;
public AudioTrack B;
public AudioMsgInfo C;
public StickerAnimationState D;
public StickersAnimationLoader E;
@Nullable
public OnSpanClickListener F;
@Nullable
public OnSpanLongPressListener G;
@Nullable
public MsgListAdapterCallback H;
@Nullable
public VideoAutoPlayer I;
public Msg a;
public NestedMsg b;
public CharSequence c;
public Attach d;
public List<Attach> e;
public boolean f;
public int g;
public int h;
public int i;
public int j;
public int k;
@ColorInt
public int l;
public Member m;
public ProfilesSimpleInfo n;
public ImExperimentsProvider o;
public int p;
public int q;
public int r;
public boolean s;
public boolean t;
public boolean u;
public boolean v;
public boolean w;
public boolean x;
public boolean y;
public boolean isSelected;
public SparseIntArray z;
public MsgPartHolderBindArgs() {
}
}
@@ -0,0 +1,435 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.vk.im.ui.components.viewcontrollers.msg_list.adapter;
import android.util.SparseIntArray;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.vk.core.network.TimeProvider;
import com.vk.im.engine.j.StickersAnimationLoader;
import com.vk.im.engine.models.ImBgSyncState;
import com.vk.im.engine.models.ImExperimentsProvider;
import com.vk.im.engine.models.Member;
import com.vk.im.engine.models.ProfilesSimpleInfo;
import com.vk.im.engine.models.attaches.AttachAudioMsg;
import com.vk.im.engine.models.dialogs.Dialog;
import com.vk.im.engine.models.dialogs.DialogTheme;
import com.vk.im.engine.models.messages.*;
import com.vk.im.engine.utils.collection.IntSet;
import com.vk.im.ui.components.viewcontrollers.msg_list.entry.AdapterEntry;
import com.vk.im.ui.media.audio.AudioTrack;
import com.vk.im.ui.q.h.VideoAutoPlayer;
import com.vk.im.ui.views.span.OnSpanClickListener;
import com.vk.im.ui.views.span.OnSpanLongPressListener;
import com.vk.im.ui.views.sticker.StickerAnimationState;
public class VhBindArgs {
public MsgListAdapterCallback A;
@Nullable
public VideoAutoPlayer B = null;
@Nullable
public MsgIdType C = null;
public int D = -1;
public AdapterEntry a;
public AdapterEntry b;
public AdapterEntry c;
public int d;
@Nullable
public Dialog e;
@NonNull
public DialogTheme f;
public Member g;
public ProfilesSimpleInfo h;
public int i;
public boolean j;
public boolean k;
public boolean l;
public long m;
public ImExperimentsProvider n;
public ImBgSyncState o;
public int p;
public boolean q;
public IntSet r;
public SparseIntArray s;
public SparseIntArray t;
public AudioTrack u;
public AudioMsgInfo v;
public StickerAnimationState w;
public StickersAnimationLoader x;
@Nullable
public OnSpanClickListener y;
@Nullable
public OnSpanLongPressListener z;
public VhBindArgs() {
}
private long K() {
Msg var1 = this.b.c;
return var1 == null ? Long.MAX_VALUE : TimeProvider.f.b() - var1.getTime();
}
private boolean L() {
boolean var1;
var1 = this.K() > this.m || TimeProvider.f.c();
return var1;
}
public boolean A() {
AdapterEntry var1 = this.a;
boolean var2 = false;
boolean var3 = var2;
if (var1 != null) {
if (var1.d()) {
var3 = var2;
} else {
Msg var4 = this.a.c;
Msg var5 = this.b.c;
var3 = var2;
if (var4.W() == var5.W()) {
var3 = var2;
if (var4.e0() == var5.e0()) {
var3 = true;
}
}
}
}
return var3;
}
public boolean B() {
AdapterEntry var1 = this.a;
boolean var2;
var2 = var1 != null && var1.c();
return var2;
}
public boolean C() {
AdapterEntry var1 = this.a;
boolean var2;
var2 = var1 != null && var1.c() && this.a.c.getLocalId() == this.b.c.getLocalId();
return var2;
}
public boolean D() {
AdapterEntry var1 = this.a;
boolean var2;
var2 = var1 != null && var1.a == 83;
return var2;
}
public boolean E() {
Msg var1 = this.b.c;
boolean var2;
var2 = var1 instanceof MsgFromUser && ((MsgFromUser) var1).i2();
return var2;
}
public boolean F() {
Msg var1 = this.b.c;
boolean var2;
var2 = var1 instanceof MsgFromUser && ((MsgFromUser) var1).F0();
return var2;
}
public boolean G() {
AdapterEntry var1 = this.b;
boolean var2;
var2 = var1 != null && var1.a == 51;
return var2;
}
public int H() {
return this.b.i;
}
public boolean I() {
long var1 = this.K();
long var3 = this.m;
boolean var5;
var5 = var1 > var3 && var1 < var3 * 2L;
return var5;
}
public boolean J() {
Msg var1 = this.b.c;
boolean var2 = false;
if (var1 == null) {
return false;
} else if (!(var1 instanceof MsgFromUser)) {
return false;
} else {
MsgFromUser var7 = (MsgFromUser) var1;
Msg var3 = this.a.c;
boolean var4;
var4 = var3 != null && var3.d() == MsgSyncState.DONE;
boolean var5;
var5 = this.o == ImBgSyncState.CONNECTED;
boolean var6 = var2;
if (!var7.H0()) {
var6 = var2;
if (var5) {
var6 = var2;
if (!this.L()) {
var6 = var2;
if (var4) {
var6 = true;
}
}
}
}
return var6;
}
}
public int a() {
boolean var1 = this.h();
byte var2 = 0;
int var3 = var2;
if (var1) {
AttachAudioMsg var4 = ((MsgFromUser) this.b.c).c(AttachAudioMsg.class, false);
var3 = var2;
if (var4 != null) {
var3 = var4.f();
}
}
return var3;
}
public int b() {
Msg var1 = this.b.c;
int var2;
if (var1 != null) {
var2 = var1.B1();
} else {
var2 = 0;
}
return var2;
}
public boolean c() {
Msg var1 = this.b.c;
boolean var2;
var2 = var1 instanceof MsgFromUser && ((MsgFromUser) var1).I0();
return var2;
}
public boolean d() {
Msg var1 = this.b.c;
boolean var2;
var2 = var1 instanceof WithUserContent && ((WithUserContent) var1).D0() != null;
return var2;
}
public boolean e() {
boolean var1;
var1 = this.b.i > 0;
return var1;
}
public boolean f() {
AdapterEntry var1 = this.b;
boolean var2;
if (var1 != null) {
Msg var3 = var1.c;
if (var3 != null && var3.P1()) {
var2 = true;
return var2;
}
}
var2 = false;
return var2;
}
public boolean g() {
Msg var1 = this.b.c;
boolean var2;
var2 = var1 instanceof MsgFromUser && ((MsgFromUser) var1).G0();
return var2;
}
public boolean h() {
Msg var1 = this.b.c;
boolean var2;
var2 = var1 instanceof MsgFromUser && ((MsgFromUser) var1).Z1();
return var2;
}
public boolean i() {
boolean var1;
var1 = this.j && !this.u() && !this.l();
return var1;
}
public boolean j() {
boolean var1;
var1 = this.j && !this.u() && (!this.B() || !this.A() || this.a.c.H1());
return var1;
}
public boolean k() {
Dialog var1 = this.e;
boolean var2;
var2 = var1 != null && var1.U1();
return var2;
}
public boolean l() {
Dialog var1 = this.e;
boolean var2;
var2 = var1 != null && var1.V1();
return var2;
}
public boolean m() {
Dialog var1 = this.e;
boolean var2;
var2 = var1 != null && var1.W1();
return var2;
}
public boolean n() {
int var1 = this.b.a;
return var1 == 52 || var1 == 53 || var1 == 56 || var1 == 57 || var1 == 70 || var1 == 77 || var1 == 85 || var1 == 94 || var1 == 95;
}
public boolean o() {
AdapterEntry var1 = this.b;
boolean var2;
var2 = var1 != null && var1.a == 101;
return var2;
}
public boolean p() {
Msg var1 = this.b.c;
boolean var2;
var2 = var1 != null && var1.G1();
return var2;
}
public boolean q() {
AdapterEntry var1 = this.b;
boolean var3;
if (var1 != null) {
int var2 = var1.a;
if (var2 == 59 || var2 == 58 || var2 == 61 || var2 == 60) {
var3 = true;
return var3;
}
}
var3 = false;
return var3;
}
public boolean r() {
Msg var1 = this.b.c;
boolean var2;
var2 = var1 instanceof MsgFromUser && ((MsgFromUser) var1).e2();
return var2;
}
public boolean s() {
if (this.C != null)
return switch (this.C) {
case LOCAL_ID -> this.D == this.b.c.getLocalId();
case VK_ID -> this.D == this.b.c.C1();
};
return false;
}
public boolean t() {
AdapterEntry var1 = this.b;
boolean var2;
if (var1 != null) {
Msg var3 = var1.c;
if (var3 != null && !var3.b(this.g)) {
var2 = true;
return var2;
}
}
var2 = false;
return var2;
}
public boolean u() {
Msg var1 = this.b.c;
if (var1 != null) {
return var1.b(this.g);
} else {
throw new RuntimeException();
}
}
public boolean v() {
IntSet var1 = this.r;
boolean var2;
var2 = var1 != null && var1.a(this.b.c.getLocalId());
return var2;
}
public boolean w() {
return !this.z();
}
public boolean x() {
AdapterEntry var1 = this.c;
boolean var2;
var2 = var1 != null && var1.a == 100;
return var2;
}
public boolean y() {
AdapterEntry var1 = this.c;
boolean var2;
var2 = var1 != null && var1.a == 96;
return var2;
}
public boolean z() {
AdapterEntry var1 = this.c;
boolean var2;
var2 = var1 != null && var1.c() && this.c.c.getLocalId() == this.b.c.getLocalId();
return var2;
}
public boolean isSelected() {
return this.b != null && this.b.c != null && this.r.a(this.b.c.getLocalId());
}
}
@@ -0,0 +1,176 @@
package com.vk.im.ui.components.viewcontrollers.msg_list.adapter.msgparts;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.vk.core.util.DurationFormatter;
import com.vk.im.engine.models.CallState;
import com.vk.im.engine.models.Member;
import com.vk.im.engine.models.attaches.Attach;
import com.vk.im.engine.models.attaches.AttachCall;
import com.vk.im.engine.models.dialogs.BubbleColors;
import com.vk.im.engine.models.messages.Msg;
import com.vk.im.ui.components.viewcontrollers.msg_list.adapter.MsgPartHolderBase;
import com.vk.im.ui.components.viewcontrollers.msg_list.adapter.MsgPartHolderBindArgs;
import com.vk.im.ui.components.viewcontrollers.msg_list.adapter.utils.MsgTimeFormatter;
import com.vk.im.ui.j;
import com.vk.im.ui.m;
import com.vk.im.ui.n;
import com.vk.im.ui.views.msg.MsgPartIconTwoRowView;
import com.vtosters.lite.R;
import kotlin.TypeCastException;
import kotlin.jvm.internal.Intrinsics;
import ru.vtosters.hooks.CallsHook;
public final class MsgPartCallHolder extends MsgPartHolderBase<AttachCall> {
public static final a I = new a();
private final Context C;
private final DurationFormatter D;
private final StringBuilder E;
private final MsgTimeFormatter F;
private final StringBuilder G;
private final MsgPartIconTwoRowView H;
private boolean incoming;
public MsgPartCallHolder(MsgPartIconTwoRowView var1) {
this.H = var1;
this.C = this.H.getContext();
Context var2 = this.H.getContext();
Intrinsics.a(var2, "view.context");
this.D = new DurationFormatter(var2);
this.E = new StringBuilder();
this.F = MsgTimeFormatter.f;
this.G = new StringBuilder();
}
private void a(Msg var1) {
this.G.setLength(0);
MsgTimeFormatter var2 = this.F;
Context var3 = this.C;
Intrinsics.a(var3, "context");
var2.a(var1, var3, this.G);
this.H.setTimeText(this.G);
}
private void a(boolean var1) {
MsgPartIconTwoRowView var2 = this.H;
int var3;
if (var1) {
var3 = R.drawable.vkim_ic_attach_video_call;
} else {
var3 = R.drawable.vkim_ic_attach_call;
}
var2.setIcon(var3);
}
private void a(boolean var1, AttachCall var2) {
boolean var3 = !var1;
if (var2.h() == CallState.ERROR) {
this.H.setSubtitleText(m.vkim_msg_list_call_error);
this.H.setSubtitleTextAppearance(n.VkIm_MsgPart_Call_Failure);
} else if (var2.h() == CallState.DONE) {
this.E.setLength(0);
this.D.a(var2.a(), this.E);
this.H.setSubtitleText(this.E);
this.H.setSubtitleTextAppearance(n.VkIm_MsgPart_Call_Duration);
} else if (var1) {
this.H.setSubtitleText(m.vkim_msg_list_call_missed);
this.H.setSubtitleTextAppearance(n.VkIm_MsgPart_Call_Failure);
} else if (var2.h() == CallState.CANCELLED) {
this.H.setSubtitleText(m.vkim_msg_list_call_cancelled);
this.H.setSubtitleTextAppearance(n.VkIm_MsgPart_Call_Failure);
} else if (var2.h() == CallState.DECLINED) {
this.H.setSubtitleText(m.vkim_msg_list_call_declined);
this.H.setSubtitleTextAppearance(n.VkIm_MsgPart_Call_Failure);
}
}
private void b(boolean var1) {
incoming = var1;
if (incoming) {
this.H.setTitleText(m.vkim_msg_list_call_incoming);
} else {
this.H.setTitleText(m.vkim_msg_list_call_outgoing);
}
}
private void c() {
this.H.setTimeText(null);
}
private void c(MsgPartHolderBindArgs var1) {
super.f = var1.H;
super.g = var1.a;
super.h = var1.b;
Attach var2 = var1.d;
if (var2 != null) {
super.B = (AttachCall) var2;
} else {
throw new TypeCastException("null cannot be cast to non-null type com.vk.im.engine.models.attaches.AttachCall");
}
}
protected View b(LayoutInflater var1, ViewGroup var2) {
this.H.setOnClickListener(var11 -> {
if (incoming) {
CallsHook.forwardToVkOffApps(C, super.B.f().getId());
} else {
CallsHook.forwardToVkOffApps(C, super.B.g().getId());
}
});
return this.H;
}
protected void b(BubbleColors var1) {
this.a(this.H, var1);
}
protected void b(MsgPartHolderBindArgs var1) {
Msg var2 = var1.a;
if (var2 != null) {
Attach var3 = var1.d;
if (var3 != null) {
AttachCall var4 = (AttachCall) var3;
Member var5 = var4.f();
Member var8 = var1.m;
Intrinsics.a(var8, "bindArgs.currentMember");
boolean var6 = var5.e(var8);
boolean var7 = var4.i();
this.c(var1);
this.b(var6);
this.a(var6, var4);
this.a(var7);
if (var1.f) {
this.a(var2);
} else {
this.c();
}
} else {
throw new TypeCastException("null cannot be cast to non-null type com.vk.im.engine.models.attaches.AttachCall");
}
} else {
Intrinsics.a();
throw null;
}
}
public static final class a {
private a() {
}
public MsgPartCallHolder a(LayoutInflater var1, ViewGroup var2) {
View var3 = var1.inflate(j.vkim_msg_part_call, var2, false);
if (var3 != null) {
return new MsgPartCallHolder((MsgPartIconTwoRowView) var3);
} else {
throw new TypeCastException("null cannot be cast to non-null type com.vk.im.ui.views.msg.MsgPartIconTwoRowView");
}
}
}
}
@@ -0,0 +1,48 @@
package com.vk.im.ui.components.viewcontrollers.msg_list.adapter.msgparts;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.vk.im.engine.models.attaches.Attach;
import com.vk.im.engine.models.dialogs.BubbleColors;
import com.vk.im.ui.components.viewcontrollers.msg_list.adapter.MsgPartHolderBase;
import com.vk.im.ui.components.viewcontrollers.msg_list.adapter.MsgPartHolderBindArgs;
import com.vk.im.ui.views.msg.MsgPartTextView;
import com.vk.im.ui.views.msg.WithTime;
import com.vtosters.lite.R;
public class MsgPartTextHolder extends MsgPartHolderBase<Attach> {
private FrameLayout mContainer;
private MsgPartTextView mTextPart;
@Override
protected View b(LayoutInflater inflater, ViewGroup parent) {
mTextPart = (MsgPartTextView) inflater.inflate(R.layout.vkim_msg_part_text, parent, false);
mTextPart.setOnClickListener(view -> {
MsgPartTextHolder.this.f.a(MsgPartTextHolder.this.g.getLocalId());
});
mTextPart.setOnLongClickListener(view -> {
if (!mTextPart.isTextSelectable()) MsgPartTextHolder.this.f.b(MsgPartTextHolder.this.g.getLocalId());
return false;
});
return mTextPart;
}
@Override
protected void b(BubbleColors colors) {
mTextPart.setTimeTextColor(colors.h);
mTextPart.setLinkTextColor(colors.d);
mTextPart.setTextColor(colors.f);
}
@Override
protected void b(MsgPartHolderBindArgs bindArgs) {
mTextPart.setOnSpanClickListener(bindArgs.F);
mTextPart.setOnSpanLongPressListener(bindArgs.G);
mTextPart.setText(bindArgs.c);
mTextPart.setTextIsSelectable(bindArgs.isSelected);
a(bindArgs, (WithTime) mTextPart);
}
}
@@ -0,0 +1,164 @@
package com.vk.im.ui.q.h.e;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.vk.core.ui.VkBottomSheetBehavior;
import com.vk.core.util.ContextExtKt;
import com.vk.core.util.Screen;
import com.vk.extensions.ViewExtKt;
import com.vk.im.engine.ImEngine;
import com.vk.im.engine.models.Member;
import com.vk.im.engine.models.ProfilesInfo;
import com.vk.im.engine.models.Suggestion;
import com.vk.im.ui.components.dialog_mention.DialogMentionComponent;
import com.vk.im.ui.components.dialog_mention.DialogMentionComponentCallback;
import com.vk.im.ui.formatters.MentionNameFormatter;
import com.vk.im.ui.utils.j.MentionSuggestionsSupplier;
import com.vk.im.ui.utils.j.MentionsManager;
import com.vk.im.ui.views.RichEditText;
import com.vtosters.lite.R;
public final class MentionsController {
private final RichEditText a;
private final ImEngine mImEngine;
private final View j;
private final b k;
private boolean state;
private CoordinatorLayout mCoordinatorLayout;
private VkBottomSheetBehavior<RecyclerView> mBottomSheetBehavior;
private boolean e;
private final DialogMentionComponent mDialogMentionComponent;
private final MentionsManager mMentionsManager;
private final int i;
public MentionsController(ImEngine imEngine, int i, View view, b bVar) {
this.mImEngine = imEngine;
this.i = i;
this.j = view;
this.k = bVar;
this.a = this.j.findViewById(R.id.writebar_edit);
this.mMentionsManager = new MentionsManager(this.a, new MentionSuggestionsSupplier() {
@Override
public boolean a() {
if (MentionsController.this.state)
return ViewExtKt.i(MentionsController.this.mCoordinatorLayout);
return false;
}
@Override
public boolean a(String str) {
if (MentionsController.this.c().c())
return false;
MentionsController.this.mDialogMentionComponent.a(MentionsController.this.d(), str);
MentionsController.this.e = true;
MentionsController.this.j();
return true;
}
@Override
public void b() {
MentionsController.this.mDialogMentionComponent.a(0, null);
MentionsController.this.g();
}
});
this.mDialogMentionComponent = new DialogMentionComponent(this.mImEngine);
this.mDialogMentionComponent.a(new DialogMentionComponentCallback() {
@Override
public void a(Member member, ProfilesInfo profilesInfo) {
MentionsController.this.mMentionsManager.a(member, MentionNameFormatter.a.a(member, profilesInfo));
}
@Override
public void a(Suggestion suggestion) {
if (suggestion.b().b() == null || suggestion.b().b().isEmpty())
MentionsController.this.g();
else
MentionsController.this.i();
}
});
}
public void g() {
this.e = false;
j();
}
private void h() {
if (this.state) {
return;
}
View inflate = ((ViewStub) this.j.findViewById(R.id.mentions_container_stub)).inflate();
ViewGroup viewGroup = inflate.findViewById(R.id.mentions_container);
viewGroup.addView(this.mDialogMentionComponent.a(viewGroup, null));
this.mCoordinatorLayout = inflate.findViewById(R.id.mentions_cl);
this.mBottomSheetBehavior = (VkBottomSheetBehavior<RecyclerView>) ((CoordinatorLayout.LayoutParams) viewGroup.getLayoutParams()).getBehavior();
this.mBottomSheetBehavior.a(new VkBottomSheetBehavior.b() {
@Override
public void a(View view, int i) {
if (i == 5) {
MentionsController.this.g();
}
}
});
this.mBottomSheetBehavior.b(true);
this.mBottomSheetBehavior.g(4);
this.mBottomSheetBehavior.e(Screen.a(160));
this.state = true;
}
public void i() {
this.e = true;
j();
}
public void j() {
if (this.k.d()) {
Context context = this.j.getContext();
Activity f = ContextExtKt.f(context);
boolean z = this.e && (Screen.k(f) || Screen.l(f));
if (z || this.state) {
if (!this.state) h();
this.mCoordinatorLayout.setVisibility(z ? View.VISIBLE : View.GONE);
if (z) return;
this.mCoordinatorLayout.postDelayed(() -> this.mBottomSheetBehavior.b(4), 300L);
}
}
}
public void a() {
this.mDialogMentionComponent.g();
}
public void b() {
this.mDialogMentionComponent.h();
}
public b c() {
return this.k;
}
public int d() {
return this.i;
}
public void e() {
this.mDialogMentionComponent.q();
}
public void f() {
this.mDialogMentionComponent.r();
}
public interface b {
boolean c();
boolean d();
}
}
@@ -2,13 +2,13 @@ package com.vk.im.ui.views;
import androidx.annotation.NonNull;
public class Corners{
public class Corners {
private int topLeft;
private int topRight;
private int bottomLeft;
private int bottomRight;
public Corners(int i, int i2, int i3, int i4){
public Corners(int i, int i2, int i3, int i4) {
this.topLeft = i;
this.topRight = i2;
this.bottomLeft = i3;
@@ -23,7 +23,7 @@ public class Corners{
this(0, 0, 0, 0, 15);
}
public static Corners a(Corners corners, int i, int i2, int i3, int i4, int i5, Object obj){
public static Corners a(Corners corners, int i, int i2, int i3, int i4, int i5, Object obj) {
if ((i5 & 1) != 0) {
i = corners.topLeft;
}
@@ -40,30 +40,30 @@ public class Corners{
return corners;
}
public int a(){
public int a() {
return this.bottomLeft;
}
public int b(){
public int b() {
return this.bottomRight;
}
public int c(){
public int c() {
return this.topLeft;
}
public int d(){
public int d() {
return this.topRight;
}
public boolean e(){
public boolean e() {
int i;
int i2 = this.topLeft;
int i3 = this.topRight;
return i2 == i3 && i3 == (i = this.bottomRight) && this.bottomLeft == i;
}
public boolean equals(Object obj){
public boolean equals(Object obj) {
if (this != obj) {
if (!(obj instanceof Corners)) {
return false;
@@ -74,24 +74,24 @@ public class Corners{
return true;
}
public boolean f(){
public boolean f() {
return this.topLeft == 0 && e();
}
public void g(){
public void g() {
a(0, 0);
}
public int hashCode(){
public int hashCode() {
return (((((this.topLeft * 31) + this.topRight) * 31) + this.bottomLeft) * 31) + this.bottomRight;
}
@NonNull
public String toString(){
public String toString() {
return "Corners(topLeft=" + this.topLeft + ", topRight=" + this.topRight + ", bottomLeft=" + this.bottomLeft + ", bottomRight=" + this.bottomRight + ")";
}
public Corners a(int i, int i2){
public Corners a(int i, int i2) {
if ((i2 & 1) > 0) {
this.topLeft = i;
}
@@ -113,7 +113,7 @@ public class Corners{
return this;
}
public Corners a(int i, int i2, int i3, int i4){
public Corners a(int i, int i2, int i3, int i4) {
this.topLeft = i;
this.topRight = i2;
this.bottomLeft = i3;
@@ -121,7 +121,7 @@ public class Corners{
return this;
}
public Corners a(Corners corners){
public Corners a(Corners corners) {
this.topLeft = corners.topLeft;
this.topRight = corners.topRight;
this.bottomLeft = corners.bottomLeft;
@@ -9,19 +9,18 @@ import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.vk.im.ui.o;
public class StoryBorderView extends View {
private boolean B;
private final Paint a;
private final int g;
private final int h;
private boolean B;
private LinearGradient f15747b;
private int f15748c;
private int f15749d;
private int f15750e;
private int f15751f;
private final int g;
private final int h;
public StoryBorderView(Context context) {
this(context, null, 0, 6);
@@ -35,10 +34,32 @@ public class StoryBorderView extends View {
this(context, (i2 & 2) != 0 ? null : attributeSet, (i2 & 4) != 0 ? 0 : i);
}
public StoryBorderView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
this.a = paint;
TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, o.StoryBorderView);
setBorderColor(obtainStyledAttributes.getInt(o.StoryBorderView_vkim_borderColor, 0));
this.g = obtainStyledAttributes.getInt(o.StoryBorderView_vkim_borderGradientStartColor, 0);
this.h = obtainStyledAttributes.getInt(o.StoryBorderView_vkim_borderGradientEndColor, 0);
setBorderWidth(obtainStyledAttributes.getDimensionPixelSize(o.StoryBorderView_vkim_borderWidth, 0));
obtainStyledAttributes.recycle();
}
public int getBorderColor() {
return this.f15749d;
}
public void setBorderColor(int i) {
if (this.f15749d != i) {
this.f15749d = i;
this.a.setColor(i);
invalidate();
}
}
public int getBorderGradientEndColor() {
return this.h;
}
@@ -51,14 +72,33 @@ public class StoryBorderView extends View {
return this.f15750e;
}
public void setBorderWidth(int i) {
if (this.f15750e != i) {
this.f15750e = i;
this.a.setStrokeWidth(i);
invalidate();
}
}
public int getPadding() {
return this.f15751f;
}
public void setPadding(int i) {
if (this.f15751f != i) {
this.f15751f = i;
setPadding(i, i, i, i);
}
}
public int getViewSize() {
return this.f15748c;
}
public void setViewSize(int i) {
this.f15748c = i;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawOval(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(), getHeight() - getPaddingBottom(), this.a);
@@ -70,22 +110,6 @@ public class StoryBorderView extends View {
setMeasuredDimension(i3, i3);
}
public void setBorderColor(int i) {
if (this.f15749d != i) {
this.f15749d = i;
this.a.setColor(i);
invalidate();
}
}
public void setBorderWidth(int i) {
if (this.f15750e != i) {
this.f15750e = i;
this.a.setStrokeWidth(i);
invalidate();
}
}
@Override
public void setLayoutParams(ViewGroup.LayoutParams layoutParams) {
super.setLayoutParams(layoutParams);
@@ -109,29 +133,4 @@ public class StoryBorderView extends View {
invalidate();
}
}
public void setPadding(int i) {
if (this.f15751f != i) {
this.f15751f = i;
setPadding(i, i, i, i);
}
}
public void setViewSize(int i) {
this.f15748c = i;
}
public StoryBorderView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
this.a = paint;
TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, o.StoryBorderView);
setBorderColor(obtainStyledAttributes.getInt(o.StoryBorderView_vkim_borderColor, 0));
this.g = obtainStyledAttributes.getInt(o.StoryBorderView_vkim_borderGradientStartColor, 0);
this.h = obtainStyledAttributes.getInt(o.StoryBorderView_vkim_borderGradientEndColor, 0);
setBorderWidth(obtainStyledAttributes.getDimensionPixelSize(o.StoryBorderView_vkim_borderWidth, 0));
obtainStyledAttributes.recycle();
}
}
@@ -1,8 +1,5 @@
package com.vk.im.ui.views.dialogs;
import static com.vk.im.ui.d.vkim_administration_title;
import static ru.vtosters.lite.utils.ThemesUtils.getAccentColor;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
@@ -17,10 +14,9 @@ import android.view.ViewGroup;
import android.view.ViewPropertyAnimator;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.appcompat.widget.AppCompatImageView;
import b.h.g.r.MathExt;
import com.vk.core.extensions.AnimationExtKt;
import com.vk.core.util.ContextExtKt;
import com.vk.core.util.Screen;
@@ -42,9 +38,10 @@ import com.vk.im.ui.views.FixTextView;
import com.vk.im.ui.views.avatars.AvatarView;
import com.vk.im.ui.views.avatars.StoryBorderView;
import b.h.g.r.MathExt;
import static com.vk.im.ui.d.vkim_administration_title;
import static ru.vtosters.hooks.other.ThemesUtils.getAccentColor;
public class DialogItemView extends ViewGroup{
public class DialogItemView extends ViewGroup {
private final int B;
private final int C;
private final int D;
@@ -80,15 +77,15 @@ public class DialogItemView extends ViewGroup{
private boolean g0;
private boolean h0;
public DialogItemView(Context context){
public DialogItemView(Context context) {
this(context, null, 0, 6);
}
public DialogItemView(Context context, AttributeSet attributeSet){
public DialogItemView(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0, 4);
}
public DialogItemView(Context context, AttributeSet attributeSet, int i){
public DialogItemView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
Resources resources = getResources();
this.a = resources.getDisplayMetrics();
@@ -255,11 +252,11 @@ public class DialogItemView extends ViewGroup{
addView(this.f0);
}
public DialogItemView(Context context, AttributeSet attributeSet, int i, int i2){
public DialogItemView(Context context, AttributeSet attributeSet, int i, int i2) {
this(context, (i2 & 2) != 0 ? null : attributeSet, (i2 & 4) != 0 ? 0 : i);
}
public static ViewPropertyAnimator b(View view, float f, long j, long j2, Runnable runnable, int i, Object obj){
public static ViewPropertyAnimator b(View view, float f, long j, long j2, Runnable runnable, int i, Object obj) {
if ((i & 1) != 0) {
f = 0.0f;
}
@@ -279,7 +276,7 @@ public class DialogItemView extends ViewGroup{
return AnimationExtKt.b(view, f, j, j2, runnable);
}
public static void a(View view, float f, float f2, int i, Object obj){
public static void a(View view, float f, float f2, int i, Object obj) {
if ((i & 1) != 0) {
f = 1.0f;
}
@@ -291,7 +288,7 @@ public class DialogItemView extends ViewGroup{
AnimationExtKt.a(view, f, f2);
}
public static ViewPropertyAnimator a(View view, float f, long j, long j2, Runnable runnable, int i, Object obj){
public static ViewPropertyAnimator a(View view, float f, long j, long j2, Runnable runnable, int i, Object obj) {
if ((i & 1) != 0) {
f = 1.0f;
}
@@ -311,14 +308,14 @@ public class DialogItemView extends ViewGroup{
return AnimationExtKt.a(view, f, j, j2, runnable);
}
static void a(DialogItemView dialogItemView, int i, int i2, int i3, int i4, Object obj){
static void a(DialogItemView dialogItemView, int i, int i2, int i3, int i4, Object obj) {
if ((i4 & 4) != 0) {
i3 = 0;
}
dialogItemView.a(i, i2, i3);
}
static ViewGroup.MarginLayoutParams a(DialogItemView dialogItemView, int i, int i2, int i3, int i4, int i5, int i6, int i7, Object obj){
static ViewGroup.MarginLayoutParams a(DialogItemView dialogItemView, int i, int i2, int i3, int i4, int i5, int i6, int i7, Object obj) {
if ((i7 & 1) != 0) {
i = -2;
}
@@ -340,19 +337,19 @@ public class DialogItemView extends ViewGroup{
return dialogItemView.a(i, i2, i3, i4, i5, i6);
}
private Drawable getDrOnlineMobile(){
private Drawable getDrOnlineMobile() {
return ContextExtKt.c(getContext(), f.ic_online_mobile_vkapp_composite_16);
}
private Drawable getDrOnlineVkMe(){
private Drawable getDrOnlineVkMe() {
return ContextExtKt.c(getContext(), f.ic_online_mobile_vkme_composite_16);
}
private Drawable getDrOnlineWeb(){
private Drawable getDrOnlineWeb() {
return ContextExtKt.c(getContext(), f.ic_online_web_composite_16);
}
private int getTimeMargin(){
private int getTimeMargin() {
Layout layout = this.T.getLayout();
if (layout == null) {
@@ -374,11 +371,11 @@ public class DialogItemView extends ViewGroup{
return 0;
}
private int getTitleColorHighlight(){
private int getTitleColorHighlight() {
return ContextExtKt.a(getContext(), vkim_administration_title);
}
private void h(int i, int i2, int i3, int i4){
private void h(int i, int i2, int i3, int i4) {
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int measuredWidth = getMeasuredWidth() - getPaddingRight();
@@ -412,51 +409,51 @@ public class DialogItemView extends ViewGroup{
j(measuredWidth - r, max6, measuredWidth, q + max6);
}
private int i(){
private int i() {
return g(this.K);
}
private int j(){
private int j() {
return f(this.T) + Math.max(f(this.V), f(this.U));
}
private int k(){
private int k() {
return Math.max(g(this.T), g(this.V) + g(this.U));
}
private int l(){
private int l() {
return Math.max(Math.max(f(this.N), f(this.R)), Math.max(f(this.O), f(this.P)));
}
private int m(){
private int m() {
return View.MeasureSpec.makeMeasureSpec(0, 0);
}
private boolean n(){
private boolean n() {
return e(this.S);
}
private int o(){
private int o() {
return f(this.S);
}
private int p(){
private int p() {
return g(this.S);
}
private int q(){
private int q() {
return MathExt.a(f(this.b0), f(this.c0), f(this.d0), f(this.e0), f(this.f0));
}
private int r(){
private int r() {
return g(this.b0) + MathExt.a(g(this.c0), g(this.d0), g(this.e0), g(this.f0));
}
private int s(){
private int s() {
return Math.max(f(this.a0), f(this.W));
}
private void setAttach(CharSequence charSequence){
private void setAttach(CharSequence charSequence) {
int i = VISIBLE;
if (charSequence == null || charSequence.length() == 0) {
@@ -467,57 +464,57 @@ public class DialogItemView extends ViewGroup{
this.U.setText(charSequence);
}
private void setBodyLinesCount(int i){
private void setBodyLinesCount(int i) {
boolean z = i == 1;
this.T.setSingleLine(z);
this.T.setMaxLines(i);
}
private int t(){
private int t() {
return g(this.a0) + g(this.W);
}
private void u(){
private void u() {
ViewExtKt.b(this.b0, this.g0 | this.h0);
}
public void a(Dialog dialog, ProfilesSimpleInfo profilesSimpleInfo){
public void a(Dialog dialog, ProfilesSimpleInfo profilesSimpleInfo) {
this.K.a(dialog, profilesSimpleInfo);
}
public void b(){
public void b() {
a(null, (ComposingType) null);
}
public void c(){
public void c() {
a(getDrOnlineMobile());
}
public void d(){
public void d() {
a(getDrOnlineVkMe());
}
public void e(){
public void e() {
a(getDrOnlineWeb());
}
public void f(){
public void f() {
this.S.setVisibility(GONE);
this.S.e();
}
public void g(){
public void g() {
b(this.L, 0.0f, 0L, 0L, null, 15, null);
}
@Override // android.view.ViewGroup, android.view.View
protected void onDetachedFromWindow(){
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
a(this.L, 0.0f, 0.0f, 3, null);
}
@Override // android.view.ViewGroup, android.view.View
protected void onLayout(boolean z, int i, int i2, int i3, int i4){
protected void onLayout(boolean z, int i, int i2, int i3, int i4) {
if (this.E) {
g(i, i2, i3, i4);
} else {
@@ -526,7 +523,7 @@ public class DialogItemView extends ViewGroup{
}
@Override // android.view.View
protected void onMeasure(int i, int i2){
protected void onMeasure(int i, int i2) {
if (this.E) {
c(i);
} else {
@@ -534,11 +531,11 @@ public class DialogItemView extends ViewGroup{
}
}
public void setAvatar(Profile profile){
public void setAvatar(Profile profile) {
this.K.a(profile);
}
public void setBombVisible(boolean z){
public void setBombVisible(boolean z) {
if (z) {
this.b0.setImageResource(f.ic_bomb_composite_24);
}
@@ -548,23 +545,23 @@ public class DialogItemView extends ViewGroup{
u();
}
public void setCasperIconColor(@ColorInt int i){
public void setCasperIconColor(@ColorInt int i) {
ViewExtKt.a(this.Q, i);
}
public void setCasperIconVisible(boolean z){
public void setCasperIconVisible(boolean z) {
this.Q.setVisibility(z ? VISIBLE : GONE);
}
public void setErrorVisible(boolean z){
public void setErrorVisible(boolean z) {
this.f0.setVisibility(z ? VISIBLE : GONE);
}
public void setGiftVisible(boolean z){
public void setGiftVisible(boolean z) {
this.V.setVisibility(z ? VISIBLE : GONE);
}
public void setHasStories(boolean z){
public void setHasStories(boolean z) {
if (this.I == z) {
return;
}
@@ -590,7 +587,7 @@ public class DialogItemView extends ViewGroup{
setClipToPadding(!z);
}
public void setMentionVisible(boolean z){
public void setMentionVisible(boolean z) {
if (z) {
this.b0.setImageResource(f.ic_mention_composite_24);
}
@@ -600,15 +597,15 @@ public class DialogItemView extends ViewGroup{
u();
}
public void setMutedVisible(boolean z){
public void setMutedVisible(boolean z) {
this.P.setVisibility(z ? VISIBLE : GONE);
}
public void setOnStoryClickListener(View.OnClickListener onClickListener){
public void setOnStoryClickListener(View.OnClickListener onClickListener) {
ViewExtKt.b(this.M, onClickListener);
}
public void setSender(Profile profile){
public void setSender(Profile profile) {
if (profile == null) {
f();
return;
@@ -617,29 +614,29 @@ public class DialogItemView extends ViewGroup{
this.S.a(profile);
}
public void setSendingVisible(boolean z){
public void setSendingVisible(boolean z) {
this.e0.setVisibility(z ? VISIBLE : GONE);
}
public void setTime(CharSequence charSequence){
public void setTime(CharSequence charSequence) {
this.R.setText(charSequence);
}
public void setUnreadOutVisible(boolean z){
public void setUnreadOutVisible(boolean z) {
this.d0.setVisibility(z ? VISIBLE : GONE);
}
public void setVerifiedVisible(boolean z){
public void setVerifiedVisible(boolean z) {
this.O.setVisibility(z ? VISIBLE : GONE);
}
private void a(Drawable drawable){
private void a(Drawable drawable) {
ViewExtKt.c(this.L, a(16), a(20));
this.L.setImageDrawable(drawable);
a(this.L, 0.0f, 0L, 0L, null, 15, null);
}
private void c(int i){
private void c(int i) {
int size = (View.MeasureSpec.getSize(i) - getPaddingLeft()) - getPaddingRight();
d(b(size - this.K.getViewSize()), m());
int r = r();
@@ -655,7 +652,7 @@ public class DialogItemView extends ViewGroup{
setMeasuredDimension(View.MeasureSpec.getSize(i), getPaddingTop() + getPaddingBottom() + Math.max(f(this.K), l() + Math.max(Math.max(o(), j()), Math.max(s(), q()))));
}
private void d(int i){
private void d(int i) {
int size = (View.MeasureSpec.getSize(i) - getPaddingLeft()) - getPaddingRight();
d(b(size - this.K.getViewSize()), m());
int r = r();
@@ -672,7 +669,7 @@ public class DialogItemView extends ViewGroup{
setMeasuredDimension(View.MeasureSpec.getSize(i), getPaddingTop() + getPaddingBottom() + Math.max(f(this.K), l() + Math.max(Math.max(o(), j()), Math.max(s(), q()))));
}
private void e(int i, int i2, int i3, int i4){
private void e(int i, int i2, int i3, int i4) {
if (e(this.T) && e(this.U)) {
c(i, i2, i3, i4);
} else if (e(this.T)) {
@@ -683,7 +680,7 @@ public class DialogItemView extends ViewGroup{
}
}
private void g(int i, int i2, int i3, int i4){
private void g(int i, int i2, int i3, int i4) {
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int measuredWidth = getMeasuredWidth() - getPaddingRight();
@@ -706,12 +703,12 @@ public class DialogItemView extends ViewGroup{
j(measuredWidth - r, i8, measuredWidth, q + i8);
}
private void i(int i, int i2, int i3, int i4){
private void i(int i, int i2, int i3, int i4) {
AvatarView avatarView = this.S;
b(avatarView, i + b(avatarView), ((i2 + ((i4 - i2) / 2)) - (this.S.getMeasuredHeight() / 2)) + d(this.S));
}
private void j(int i, int i2, int i3, int i4){
private void j(int i, int i2, int i3, int i4) {
int i5 = i2 + ((i4 - i2) / 2);
AppCompatImageView appCompatImageView = this.b0;
b(appCompatImageView, b(appCompatImageView) + i, (i5 - (this.b0.getMeasuredHeight() / 2)) + d(this.b0));
@@ -728,7 +725,7 @@ public class DialogItemView extends ViewGroup{
b(appCompatImageView4, i + b(appCompatImageView4), (i5 - (this.f0.getMeasuredHeight() / 2)) + d(this.f0));
}
private void k(int i, int i2, int i3, int i4){
private void k(int i, int i2, int i3, int i4) {
int i5 = i2 + ((i4 - i2) / 2);
TextView textView = this.W;
b(textView, b(textView) + i, (i5 - (this.W.getMeasuredHeight() / 2)) + d(this.W));
@@ -741,7 +738,7 @@ public class DialogItemView extends ViewGroup{
b(appCompatImageView, i + b(appCompatImageView), (i5 - (this.a0.getMeasuredHeight() / 2)) + d(this.a0));
}
public void b(CharSequence charSequence, boolean z){
public void b(CharSequence charSequence, boolean z) {
int i = VISIBLE;
if (charSequence == null || charSequence.length() == 0) {
@@ -755,7 +752,7 @@ public class DialogItemView extends ViewGroup{
this.g.a(z ? this.B : this.h);
}
private void f(int i, int i2, int i3, int i4){
private void f(int i, int i2, int i3, int i4) {
TextView textView = this.N;
b(textView, i + b(textView), d(this.N) + i2);
int right = this.N.getRight() + c(this.N);
@@ -783,7 +780,7 @@ public class DialogItemView extends ViewGroup{
}
}
private void l(int i, int i2, int i3, int i4){
private void l(int i, int i2, int i3, int i4) {
TextView textView = this.W;
b(textView, i + b(textView), i2);
int right = this.W.getRight() + c(this.W);
@@ -791,33 +788,33 @@ public class DialogItemView extends ViewGroup{
b(appCompatImageView, right + b(appCompatImageView), (((this.W.getBottom() + this.W.getTop()) / 2) - (this.a0.getMeasuredHeight() / 2)) + d(this.a0));
}
private void e(int i, int i2){
private void e(int i, int i2) {
b(this.a0, i, 0, i2, 0);
b(this.W, i, g(this.a0), i2, 0);
}
public void a(CharSequence charSequence, boolean z){
public void a(CharSequence charSequence, boolean z) {
this.N.setText(charSequence);
this.N.setTextColor(z ? getTitleColorHighlight() : this.f15761e);
}
private void b(int i, int i2){
private void b(int i, int i2) {
b(this.O, i, 0, i2, 0);
b(this.Q, i, 0, i2, 0);
b(this.P, i, 0, i2, 0);
b(this.R, i, 0, i2, 0);
}
public void a(){
public void a() {
a(null, 1);
setAttach(null);
}
private boolean e(View view){
private boolean e(View view) {
return view.getVisibility() == VISIBLE;
}
public void a(CharSequence charSequence, int i, CharSequence charSequence2){
public void a(CharSequence charSequence, int i, CharSequence charSequence2) {
boolean z = false;
if (!(charSequence == null || charSequence.length() == 0)) {
@@ -840,11 +837,11 @@ public class DialogItemView extends ViewGroup{
}
}
private void b(int i, int i2, int i3){
private void b(int i, int i2, int i3) {
a(this.N, i, i3, i2, 0);
}
private void b(int i, int i2, int i3, int i4){
private void b(int i, int i2, int i3, int i4) {
int g = e(this.V) ? g(this.V) + i : i;
TextView textView = this.U;
a(textView, g + b(textView), i2 + d(this.U));
@@ -852,7 +849,7 @@ public class DialogItemView extends ViewGroup{
b(appCompatImageView, i + b(appCompatImageView), (this.U.getTop() + (this.U.getMeasuredHeight() / 2)) - (this.V.getMeasuredHeight() / 2));
}
private void a(CharSequence charSequence, int i){
private void a(CharSequence charSequence, int i) {
int i2 = VISIBLE;
if (charSequence == null || charSequence.length() == 0) {
@@ -864,13 +861,13 @@ public class DialogItemView extends ViewGroup{
setBodyLinesCount(i);
}
private void b(View view, int i, int i2, int i3, int i4){
private void b(View view, int i, int i2, int i3, int i4) {
if (view.getVisibility() != GONE) {
a(view, i, i2, i3, i4);
}
}
public void a(CharSequence charSequence, ComposingType composingType){
public void a(CharSequence charSequence, ComposingType composingType) {
Drawable drawable = composingType == ComposingType.AUDIO ? this.H : this.G;
boolean z = false;
drawable.setVisible(!(charSequence == null || charSequence.length() == 0), false);
@@ -885,13 +882,13 @@ public class DialogItemView extends ViewGroup{
this.W.setText(charSequence);
}
private void b(View view, int i, int i2){
private void b(View view, int i, int i2) {
if (view.getVisibility() == VISIBLE) {
a(view, i, i2);
}
}
private int b(View view){
private int b(View view) {
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
if (marginLayoutParams != null) {
@@ -901,11 +898,11 @@ public class DialogItemView extends ViewGroup{
return 0;
}
private int b(int i){
private int b(int i) {
return View.MeasureSpec.makeMeasureSpec(i, MeasureSpec.AT_MOST);
}
private int g(View view){
private int g(View view) {
if (view.getVisibility() == GONE) {
return 0;
}
@@ -915,13 +912,13 @@ public class DialogItemView extends ViewGroup{
return marginLayoutParams != null ? measuredWidth + marginLayoutParams.leftMargin + marginLayoutParams.rightMargin : measuredWidth;
}
private void a(int i, int i2){
private void a(int i, int i2) {
a(this.K, i, 0, i2, 0);
b(this.M, i, 0, i2, 0);
b(this.L, i, 0, i2, 0);
}
private int f(View view){
private int f(View view) {
if (view.getVisibility() == GONE) {
return 0;
}
@@ -934,32 +931,32 @@ public class DialogItemView extends ViewGroup{
return measuredHeight;
}
private void a(int i, int i2, int i3, int i4){
private void a(int i, int i2, int i3, int i4) {
AvatarView avatarView = this.K;
a(avatarView, i + b(avatarView), i2 + d(this.K));
a(this.M, this.K.getLeft() - this.K.getPaddingLeft(), this.K.getTop() - this.K.getPaddingTop());
b(this.L, this.K.getRight() - this.L.getMeasuredWidth(), this.K.getBottom() - this.L.getMeasuredHeight());
}
private void c(int i, int i2){
private void c(int i, int i2) {
b(this.S, i, 0, i2, 0);
}
private void c(int i, int i2, int i3, int i4){
private void c(int i, int i2, int i3, int i4) {
d(i, i2, i3, f(this.T) + i2);
b(i, i2 + f(this.T), i3, i4);
}
private int h(){
private int h() {
return f(this.K);
}
private void d(int i, int i2, int i3, int i4){
private void d(int i, int i2, int i3, int i4) {
TextView textView = this.T;
a(textView, i + b(textView), i2 + d(this.T));
}
private int c(View view){
private int c(View view) {
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
if (marginLayoutParams != null) {
@@ -969,7 +966,7 @@ public class DialogItemView extends ViewGroup{
return 0;
}
private void d(int i, int i2){
private void d(int i, int i2) {
b(this.b0, i, 0, i2, 0);
b(this.c0, i, 0, i2, 0);
b(this.d0, i, 0, i2, 0);
@@ -977,13 +974,13 @@ public class DialogItemView extends ViewGroup{
b(this.f0, i, 0, i2, 0);
}
private void a(int i, int i2, int i3){
private void a(int i, int i2, int i3) {
b(this.T, i, i3, i2, 0);
b(this.V, i, i3, i2, 0);
b(this.U, i, i3 + g(this.V), i2, 0);
}
private int d(View view){
private int d(View view) {
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
if (marginLayoutParams != null) {
@@ -993,7 +990,7 @@ public class DialogItemView extends ViewGroup{
return 0;
}
private ViewGroup.MarginLayoutParams a(int i, int i2, int i3, int i4, int i5, int i6){
private ViewGroup.MarginLayoutParams a(int i, int i2, int i3, int i4, int i5, int i6) {
ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(i, i2);
marginLayoutParams.leftMargin = i3;
marginLayoutParams.topMargin = i4;
@@ -1002,23 +999,23 @@ public class DialogItemView extends ViewGroup{
return marginLayoutParams;
}
public int a(int i){
public int a(int i) {
return (int) (i * (this.a.densityDpi / 160.0f));
}
public int a(float f2){
public int a(float f2) {
return (int) (f2 * (this.a.densityDpi / 160.0f));
}
private void a(View view, int i, int i2, int i3, int i4){
private void a(View view, int i, int i2, int i3, int i4) {
view.measure(ViewGroup.getChildMeasureSpec(i, i2 + b(view) + c(view), view.getLayoutParams().width), ViewGroup.getChildMeasureSpec(i3, i4 + d(view) + a(view), view.getLayoutParams().height));
}
private void a(View view, int i, int i2){
private void a(View view, int i, int i2) {
view.layout(i, i2, view.getMeasuredWidth() + i, view.getMeasuredHeight() + i2);
}
private int a(View view){
private int a(View view) {
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
if (marginLayoutParams != null) {
@@ -0,0 +1,93 @@
package com.vk.medianative;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Build;
import android.util.Log;
import ru.vtosters.hooks.other.Preferences;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MediaImageEncoder {
private static boolean compressBitmap(Bitmap bitmap, File file, CompressFormat format, int quality) {
try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
return bitmap.compress(format, quality, fileOutputStream);
} catch (IOException e) {
Log.e(MediaImageEncoder.class.getSimpleName(), "Bitmap compression error: " + e);
return false;
}
}
private static boolean compressBitmapJpeg(Bitmap bitmap, File file, int quality) {
return compressBitmap(bitmap, file, CompressFormat.JPEG, quality);
}
private static boolean compressBitmapLossless(Bitmap bitmap, File file) {
return compressBitmap(bitmap, file, CompressFormat.PNG, 100);
}
private static boolean compressBitmapNative(Bitmap bitmap, File file, int quality) {
if (MediaNative.isX86() || MediaNative.isAsus() || Build.VERSION.SDK_INT < 24) {
Log.e(MediaImageEncoder.class.getSimpleName(), "JPEG turbo not supported on this device!");
return compressBitmapJpeg(bitmap, file, quality);
}
byte[] jpegData = MediaNative.compressBitmapJpeg(bitmap, quality);
if (jpegData == null) {
return false;
}
try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
fileOutputStream.write(jpegData);
return true;
} catch (IOException e) {
Log.e(MediaImageEncoder.class.getSimpleName(), "JPEG compression error: " + e);
return false;
}
}
public static boolean encodePicture(Bitmap bitmap, File file, int quality) {
if (bitmap != null && !bitmap.isRecycled() && bitmap.getWidth() * bitmap.getHeight() != 0) {
switch (Preferences.getPreferences().getString("compression", "jpeg")) {
case "skip" -> {
return compressBitmapLossless(bitmap, file);
}
case "jpeg" -> {
return compressBitmapJpeg(bitmap, file, quality);
}
case "native" -> {
return compressBitmapNative(bitmap, file, quality);
}
}
}
return false;
}
public static boolean needToSkipCompression() {
return Preferences.getPreferences().getString("compression", "jpeg").equals("skip");
}
public static boolean needToCompress() {
return !needToSkipCompression();
}
public static boolean encodeJpeg(Bitmap bitmap, File file) {
return encodePicture(bitmap, file, 90);
}
public static boolean encodeJpegWithoutCompression(Bitmap bitmap, File file) {
return encodePicture(bitmap, file, 95);
}
public static boolean encodeJpeg(Bitmap bitmap, File file, int quality) {
if (bitmap != null && !bitmap.isRecycled() && bitmap.getWidth() * bitmap.getHeight() != 0) {
return needToCompress() ? compressBitmapNative(bitmap, file, quality) : compressBitmapJpeg(bitmap, file, quality);
} else {
return false;
}
}
}
@@ -0,0 +1,504 @@
package com.vk.medianative;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Process;
import android.os.*;
import android.util.Log;
import androidx.annotation.Keep;
import androidx.annotation.Nullable;
import com.facebook.soloader.SoLoader;
import ru.vtosters.sponsorpost.internal.Native;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.util.Scanner;
public final class MediaNative {
private static final String a = NativeMediaEncoder.class.getSimpleName();
private static final Object f17443d = new Object();
@SuppressLint("StaticFieldLeak")
@Keep
public static volatile Context context;
private static boolean isMediaLoaded = false;
private static boolean isMediaMasksLoaded = false;
public static int HSLToIntRGB(float f2, float f3, float f4) {
int[] iArr = new int[3];
waitForContext();
nativeHSLToRGB(f2, f3, f4, iArr);
return Color.argb(255, iArr[0], iArr[1], iArr[2]);
}
public static void HSLToRGB(float f2, float f3, float f4, int[] iArr) {
waitForContext();
nativeHSLToRGB(f2, f3, f4, iArr);
}
public static int HSVToIntRGB(float f2, float f3, float f4) {
int[] iArr = new int[3];
waitForContext();
nativeHSVToRGB(f2, f3, f4, iArr);
return Color.argb(255, iArr[0], iArr[1], iArr[2]);
}
public static void HSVToRGB(float f2, float f3, float f4, int[] iArr) {
waitForContext();
nativeHSVToRGB(f2, f3, f4, iArr);
}
public static int LabToIntRGB(float f2, float f3, float f4) {
int[] iArr = new int[3];
waitForContext();
nativeLabToRGB(f2, f3, f4, iArr);
return Color.argb(255, iArr[0], iArr[1], iArr[2]);
}
public static void LabToRGB(float f2, float f3, float f4, int[] iArr) {
waitForContext();
nativeLabToRGB(f2, f3, f4, iArr);
}
public static void RGBToHSL(int i, int i2, int i3, float[] fArr) {
waitForContext();
nativeRGBToHSL(i, i2, i3, fArr);
}
public static void RGBToHSV(int i, int i2, int i3, float[] fArr) {
waitForContext();
nativeRGBToHSV(i, i2, i3, fArr);
}
public static void RGBToLab(int i, int i2, int i3, float[] fArr) {
waitForContext();
nativeRGBToLab(i, i2, i3, fArr);
}
public static long animationPlayerCreate(String str, int i, int i2, boolean z) {
waitForContext();
return nativeAnimationPlayerCreate(str, i, i2, z);
}
public static int animationPlayerDecode(long j, Bitmap bitmap) {
waitForContext();
return nativeAnimationPlayerDecode(j, bitmap);
}
public static int animationPlayerGetSize(long j) {
waitForContext();
return nativeAnimationPlayerGetSize(j);
}
public static void animationPlayerRelease(long j) {
waitForContext();
nativeAnimationPlayerRelease(j);
}
public static boolean animationPlayerSeek(long j, int i) {
waitForContext();
return nativeAnimationPlayerSeek(j, i);
}
public static void applyCurveAndSaturationBitmap(Bitmap bitmap, int[] iArr, float f2) {
waitForContext();
nativeCurveSaturation(bitmap, iArr, f2, Runtime.getRuntime().availableProcessors());
}
public static long audioGetTotalPcmDuration() {
waitForContext();
return nativeAudioGetTotalPcmDuration();
}
public static byte[] audioGetWaveform(short[] sArr, int i) {
waitForContext();
return nativeAudioGetWaveform(sArr, i);
}
public static int audioIsOpusFile(String str) {
waitForContext();
return nativeAudioIsOpusFile(str);
}
public static void audioReadOpusFile(ByteBuffer byteBuffer, int i, int[] iArr) {
waitForContext();
nativeAudioReadOpusFile(byteBuffer, i, iArr);
}
public static int audioSeekOpusFile(float f2) {
waitForContext();
return nativeAudioSeekOpusFile(f2);
}
public static int audioStartRecord(String str) { // need to hack
waitForContext();
return nativeAudioStartRecord(str);
}
public static void audioStopRecord() { // need to hack
waitForContext();
nativeAudioStopRecord();
}
public static int audioWriteFrame(ByteBuffer byteBuffer, int i) { // need to hack
waitForContext();
return nativeAudioWriteFrame(byteBuffer, i);
}
private static void waitForContext() {
synchronized (f17443d) {
if (context == null) {
try {
f17443d.wait();
} catch (InterruptedException e2) {
Log.e(a, "Interrupted while waiting for context", e2);
}
}
}
}
public static void blurBitmap(Bitmap bitmap, int i) {
waitForContext();
nativeBlur(bitmap, i);
}
private static String c() {
return getProcMaps(String.valueOf(Process.myPid()));
}
public static void cameraProcessorCreate() {
waitForContext();
nativeProcessorCreate();
}
public static boolean cameraProcessorDo(byte[] bArr, long[] jArr) {
waitForContext();
return nativeProcessorDo(bArr, jArr);
}
public static int cameraProcessorGetVersion() {
waitForContext();
return nativeProcessorGetVersion();
}
public static boolean cameraProcessorInit(String str, int i, int i2) {
waitForContext();
return nativeProcessorInit(str, i, i2);
}
public static boolean cameraProcessorLoad(String str, boolean z) {
waitForContext();
return nativeProcessorLoad(str, z);
}
public static void cameraProcessorMouseTap(int i, float f2, float f3) {
waitForContext();
nativeProcessorMouseTap(i, f2, f3);
}
public static void cameraProcessorRelease() {
waitForContext();
nativeProcessorRelease();
}
public static void colorCorrectionBitmap(Bitmap bitmap, Bitmap bitmap2, float[] fArr) {
waitForContext();
nativeColorCorrection(bitmap, bitmap2, fArr, fArr.length, Runtime.getRuntime().availableProcessors());
}
public static byte[] compressBitmapJpeg(Bitmap bitmap, int i) {
waitForContext();
return nativeJpegTurboCompress(bitmap, i);
}
public static String createAllInOneShader() {
waitForContext();
return nativeAllInOneShader();
}
public static void createCurve(int[] iArr, int[] iArr2, int[] iArr3, int[] iArr4, int[] iArr5, float f2, float f3, float f4, float f5, float f6) {
waitForContext();
nativeCreateCurve(iArr, iArr2, iArr3, iArr4, iArr5, f2, f3, f4, f5, f6);
}
public static String createOneInAllShader() {
waitForContext();
return nativeOneInAllShader();
}
private static String d() {
return getProcMaps("self");
}
public static String dump() {
return "LD_LIBRARY_PATH:\n" + SoLoader.makeLdLibraryPath() + "\nSELF_MAPS:\n" + d() + "\nPID_MAPS:\n" + c() + "\n";
}
private static void e() {
isMediaMasksLoaded = NativeLibLoader.loadLibrary("vkmediamasks");
}
public static void enhanceBitmap(Bitmap bitmap, float f2) {
waitForContext();
nativeEnhance(bitmap, f2, Runtime.getRuntime().availableProcessors());
}
private static void loadVKMediaLibs() {
if (isMediaLoaded) {
return;
}
NativeLibLoader.loadLibrary("ffmpeg");
isMediaLoaded = NativeLibLoader.loadLibrary("vkmedia");
isMediaLoaded = NativeLibLoader.loadLibrary("vkmediaencoder");
}
public static void flipHorizontallyBitmap(Bitmap bitmap) {
waitForContext();
nativeFlipHorizontally(bitmap);
}
public static void flipVerticallyBitmap(Bitmap bitmap) {
waitForContext();
nativeFlipVertically(bitmap);
}
public static void generateHistogram(Bitmap bitmap, int[] iArr, int[] iArr2, int[] iArr3, int[] iArr4) {
waitForContext();
nativeHistogram(bitmap, iArr, iArr2, iArr3, iArr4);
}
public static void init(Context context2) {
synchronized (f17443d) {
context = context2;
SoLoader.init(context2, false);
NativeLibLoader.loadLibrary("gnustl_shared");
NativeLibLoader.loadLibrary("vkchronicle");
Native.canVote = NativeLibLoader.loadLibrary("sponsorpost");
loadVKMediaLibs();
f17443d.notifyAll();
}
}
public static void intRGBToHSL(int i, float[] fArr) {
waitForContext();
nativeRGBToHSL(Color.red(i), Color.green(i), Color.blue(i), fArr);
}
public static void intRGBToHSV(int i, float[] fArr) {
waitForContext();
nativeRGBToHSV(Color.red(i), Color.green(i), Color.blue(i), fArr);
}
public static void intRGBToLab(int i, float[] fArr) {
waitForContext();
nativeRGBToLab(Color.red(i), Color.green(i), Color.blue(i), fArr);
}
public static boolean isAsus() {
return "asus".equalsIgnoreCase(Build.MANUFACTURER);
}
public static boolean isMediaSupported() {
if (!isMediaMasksLoaded) {
e();
}
return isMediaMasksLoaded;
}
public static boolean isX86() {
try {
String str = Build.SUPPORTED_ABIS[0];
if (str != null) {
return str.startsWith("x86");
}
return false;
} catch (Throwable unused) {
return false;
}
}
public static void lookupBitmap(Bitmap bitmap, Bitmap bitmap2) {
waitForContext();
nativeLookup(bitmap, bitmap2, Runtime.getRuntime().availableProcessors());
}
public static long mediaEncoderCreate(MediaEncoderSettings mediaEncoderSettings) {
waitForContext();
return nativeCreateEncoder(mediaEncoderSettings);
}
public static int mediaEncoderDoEncode(long j) {
waitForContext();
return nativeDoEncode(j);
}
public static void mediaEncoderDoRelease(long j) {
waitForContext();
nativeReleaseEncoder(j);
}
private static native String nativeAllInOneShader();
private static native long nativeAnimationPlayerCreate(String str, int i, int i2, boolean z);
private static native int nativeAnimationPlayerDecode(long j, Bitmap bitmap);
private static native int nativeAnimationPlayerGetSize(long j);
private static native void nativeAnimationPlayerRelease(long j);
private static native boolean nativeAnimationPlayerSeek(long j, int i);
private static native long nativeAudioGetTotalPcmDuration();
private static native byte[] nativeAudioGetWaveform(short[] sArr, int i);
private static native int nativeAudioIsOpusFile(String str);
private static native int nativeAudioOpenOpusFile(String str);
private static native void nativeAudioReadOpusFile(ByteBuffer byteBuffer, int i, int[] iArr);
private static native int nativeAudioSeekOpusFile(float f2);
private static native int nativeAudioStartRecord(String str);
private static native void nativeAudioStopRecord();
private static native int nativeAudioWriteFrame(ByteBuffer byteBuffer, int i);
private static native void nativeBlur(Bitmap bitmap, int i);
private static native void nativeColorCorrection(Bitmap bitmap, Bitmap bitmap2, float[] fArr, int i, int i2);
private static native String nativeCreateColorCorrectionShader(float[] fArr, int i, int i2);
private static native void nativeCreateCurve(int[] iArr, int[] iArr2, int[] iArr3, int[] iArr4, int[] iArr5, float f2, float f3, float f4, float f5, float f6);
private static native long nativeCreateEncoder(MediaEncoderSettings mediaEncoderSettings);
private static native void nativeCurveSaturation(Bitmap bitmap, int[] iArr, double d2, int i);
private static native int nativeDoEncode(long j);
private static native void nativeEnhance(Bitmap bitmap, double d2, int i);
private static native void nativeFlipHorizontally(Bitmap bitmap);
private static native void nativeFlipVertically(Bitmap bitmap);
private static native void nativeHSLToRGB(float f2, float f3, float f4, int[] iArr);
private static native void nativeHSVToRGB(float f2, float f3, float f4, int[] iArr);
private static native void nativeHistogram(Bitmap bitmap, int[] iArr, int[] iArr2, int[] iArr3, int[] iArr4);
private static native byte[] nativeJpegTurboCompress(Bitmap bitmap, int i);
private static native void nativeLabToRGB(float f2, float f3, float f4, int[] iArr);
private static native void nativeLookup(Bitmap bitmap, Bitmap bitmap2, int i);
private static native String nativeOneInAllShader();
private static native void nativePinBitmap(Bitmap bitmap);
private static native void nativeProcessorCreate();
private static native boolean nativeProcessorDo(byte[] bArr, long[] jArr);
private static native int nativeProcessorGetVersion();
private static native boolean nativeProcessorInit(String str, int i, int i2);
private static native boolean nativeProcessorLoad(String str, boolean z);
private static native void nativeProcessorMouseTap(int i, float f2, float f3);
private static native void nativeProcessorRelease();
private static native void nativeRGBToHSL(int i, int i2, int i3, float[] fArr);
private static native void nativeRGBToHSV(int i, int i2, int i3, float[] fArr);
private static native void nativeRGBToLab(int i, int i2, int i3, float[] fArr);
private static native void nativeReleaseEncoder(long j);
private static native void nativeResize(Bitmap bitmap, Bitmap bitmap2, int i);
public static int openOpusFile(String str) {
waitForContext();
return nativeAudioOpenOpusFile(str);
}
public static void pinBitmap(Bitmap bitmap) {
waitForContext();
nativePinBitmap(bitmap);
}
public static void resizeBitmap(Bitmap bitmap, Bitmap bitmap2) {
waitForContext();
nativeResize(bitmap, bitmap2, Runtime.getRuntime().availableProcessors());
}
private static String getProcMaps(String str) {
try (InputStream inputStream = Runtime.getRuntime().exec("cat /proc/" + str + "/maps").getInputStream()) {
return new Scanner(inputStream).useDelimiter("\\A").next();
} catch (Exception e) {
return "empty";
}
}
public static class EncoderHandler extends Handler {
private Callback a;
public EncoderHandler(Looper looper) {
super(looper);
}
@Keep
public static Object postEventFromNative(Object obj, int i, int i2, int i3) {
EncoderHandler encoderHandler;
if (obj != null && (encoderHandler = (EncoderHandler) ((WeakReference<?>) obj).get()) != null) {
if (i == 2) {
return encoderHandler.a.getLayerBitmap(i2, i3);
}
encoderHandler.sendMessage(encoderHandler.obtainMessage(i, i2, i3, null));
}
return null;
}
@Override // android.os.Handler
public void handleMessage(Message message) {
Callback callback = this.a;
if (callback == null) {
return;
}
int i = message.what;
if (i == 0) {
callback.onBytes(message.arg1);
} else if (i != 1) {
String str = MediaNative.a;
Log.e(str, "Unknown message type " + message.what);
} else {
callback.onProgress(message.arg1);
}
}
public void setCallback(Callback callback) {
this.a = callback;
}
public interface Callback {
@Nullable
Bitmap getLayerBitmap(int i, int i2);
void onBytes(int i);
void onProgress(int i);
}
}
}
@@ -0,0 +1,174 @@
package com.vk.music.view.x;
import android.app.Activity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.vk.api.audio.AudioGetLyrics;
import com.vk.api.base.ApiCallback;
import com.vk.api.sdk.exceptions.VKApiExecutionException;
import com.vk.common.k.PodcastTimeCodeClickListener;
import com.vk.common.links.LinkParser;
import com.vk.core.util.ContextExtKt;
import com.vk.dto.music.MusicTrack;
import com.vk.music.artists.chooser.MusicArtistSelector;
import com.vk.music.common.MusicPlaybackLaunchContext;
import com.vk.music.dto.PlayerInfo;
import com.vk.music.player.PlayerModel;
import com.vk.music.player.TrackInfo;
import com.vk.profile.ui.BaseProfileFragment;
import com.vtosters.lite.LinkParserParams;
import com.vtosters.lite.R;
import com.vtosters.lite.ViewUtils;
import com.vtosters.lite.ui.MusicErrorViewHelper;
import com.vtosters.lite.ui.holder.RecyclerHolder;
import ru.vtosters.hooks.other.Preferences;
import ru.vtosters.lite.music.Genius;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
/* loaded from: classes3.dex */
public class LyricsHolder extends RecyclerHolder<PlayerInfo> implements View.OnClickListener {
private final AtomicBoolean B;
private final MusicPlaybackLaunchContext C;
private final PodcastTimeCodeClickListener D;
private final LinkParserParams E;
private final TextView f18325c;
private final TextView f18326d;
private final TextView f18327e;
private final MusicErrorViewHelper f18328f;
private final View g;
private final View h;
public LyricsHolder(ViewGroup viewGroup, PlayerModel playerModel) {
super(R.layout.music_player_fr_lyrics, viewGroup);
this.B = new AtomicBoolean(false);
this.C = MusicPlaybackLaunchContext.p0.h(128);
this.E = new LinkParserParams();
this.f18325c = i(R.id.title);
this.f18326d = i(R.id.artist);
this.f18326d.setOnClickListener(this);
this.f18327e = i(R.id.lyrics);
this.g = i(R.id.progress);
this.h = i(R.id.content);
this.f18328f = new MusicErrorViewHelper.b(i(R.id.error)).a();
this.f18328f.a(new a());
this.f18328f.b(8);
this.D = new PodcastTimeCodeClickListener(viewGroup.getContext(), playerModel);
this.E.b(907);
this.E.a(this.D);
}
public void g0() {
TrackInfo trackInfo;
if (this.B.get() || (trackInfo = this.b.a) == null || !trackInfo.n() || trackInfo.e().G == 0) {
return;
}
MusicTrack e2 = trackInfo.e();
if (e2.G <= 0 || !TextUtils.isEmpty(e2.H)) {
return;
}
this.B.set(true);
this.f18328f.b(8);
ViewUtils.a(this.g, 0);
ViewUtils.a(this.h, 8);
new AudioGetLyrics(e2.G, e2.y1(), e2).a(new b(e2)).a();
}
@Override // android.view.View.OnClickListener
public void onClick(View view) {
Object obj = this.b;
MusicTrack e = ((PlayerInfo) obj).a != null ? ((PlayerInfo) obj).a.e() : null;
Activity e2 = ContextExtKt.e(view.getContext());
if (e == null || e2 == null) {
return;
}
if (e.D1()) {
new BaseProfileFragment.z(e.e).a(e2);
} else {
MusicArtistSelector.a(e2, e, this.b.d);
}
}
@Override // com.vtosters.lite.ui.holder.RecyclerHolder
public void b(PlayerInfo playerInfo) {
CharSequence charSequence;
TrackInfo trackInfo = playerInfo.a;
if (trackInfo == null || !trackInfo.n() || trackInfo.e().G == 0) {
return;
}
MusicTrack e2 = trackInfo.e();
this.f18325c.setText(e2.f);
this.f18325c.setSelected(true);
this.f18326d.setText(e2.C);
if (e2.D1()) {
this.E.a(e2.h);
this.D.a(e2, this.C);
charSequence = LinkParser.a(e2.H, this.E);
} else {
charSequence = e2.H;
}
if (!Objects.equals(this.f18327e.getText(), charSequence)) {
this.h.setScrollY(0);
}
this.f18327e.setText(charSequence);
g0();
}
class a implements View.OnClickListener {
a() {
}
@Override // android.view.View.OnClickListener
public void onClick(View view) {
LyricsHolder.this.g0();
}
}
public class b implements ApiCallback<AudioGetLyrics.a> {
final MusicTrack a;
b(MusicTrack musicTrack) {
this.a = musicTrack;
}
@Override // com.vk.api.base.ApiCallback
public void a(AudioGetLyrics.a aVar) {
this.a.H = aVar.a;
LyricsHolder.this.f18328f.b(8);
ViewUtils.a(LyricsHolder.this.g, 8);
ViewUtils.a(LyricsHolder.this.h, 0);
LyricsHolder.this.f0();
LyricsHolder.this.B.set(false);
}
@Override // com.vk.api.base.ApiCallback
public void a(VKApiExecutionException vKApiExecutionException) {
if (Preferences.getBoolValue("useGenius", false) && !Preferences.serverFeaturesDisable()) {
var text = Genius.getTextMusic(a);
var lyrics = new AudioGetLyrics.a();
lyrics.a = text;
a(lyrics);
return;
}
LyricsHolder.this.B.set(false);
LyricsHolder.this.f18328f.a(vKApiExecutionException);
LyricsHolder.this.f18328f.b(0);
ViewUtils.a(LyricsHolder.this.g, 8);
ViewUtils.a(LyricsHolder.this.h, 8);
}
}
}

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