Compare commits

...
200 Commits
Author SHA1 Message Date
ZekerZhayard 73c31593f2 Fix #351 (#352)
* Fix #351

* a -> .1
2025-10-20 23:31:46 +08:00
ZekerZhayard 59a515ba61 Support 1.21.10. (#348) 2025-10-10 20:54:07 +09:00
ZekerZhayard 1f3d19ac6e Support 1.21.9. (#347) 2025-10-07 08:31:05 +09:00
33 1fbe258365 Update build.properties 2025-08-08 23:41:52 +08:00
33 d4cc4740d3 Update build.properties 2025-08-08 23:25:24 +08:00
ZekerZhayard d0d71b8557 Support 1.21.8. Split GameProfileLoader and MojangAPILoader. (#343) 2025-08-08 23:24:20 +08:00
ZekerZhayard 1a15951791 Support 1.21.6. (#341) 2025-06-21 21:54:07 +08:00
33 a195b42bc4 Update build.properties 2025-06-12 23:30:03 +08:00
ZekerZhayard 5d2f945d45 Support 1.21.5 (#334) 2025-03-26 20:06:21 +08:00
ZekerZhayard 6bf959de49 Fix repeated player skull texture download attempts during RenderTick on downloading failure. (#331) 2025-02-08 15:18:05 +08:00
ZekerZhayard 2f26a07dc9 Fix local profile cache. (#327) 2025-01-24 14:27:55 +08:00
33 5764d81d6d Update build.properties 2025-01-16 18:09:29 +08:00
ZekerZhayard 8080aa7ab5 Fix rendering lag when skull's username is empty. (#324) 2025-01-12 00:10:00 +08:00
8Mi_Yile 4d0ebcc1f7 Update common.yml (#323) 2025-01-12 00:08:29 +08:00
ZekerZhayard 1cb4cf40b0 1.21.4 (#321)
* 1.21.4

* Disable making the source jar.
2024-12-23 21:43:38 +08:00
cewno a9b2484b3e 更新与 Mojang API Wiki 相关的地址 (#320) 2024-12-20 12:13:03 +08:00
ZekerZhayard 8e63429293 Fix IllegalAccessError. (#317) 2024-11-12 21:36:24 +08:00
8Mi_Yile aa68af31e5 [skip ci] 修复缺少括号引起的执行问题 (#316)
手生了 还把括号搞丢了 太草了
2024-11-12 12:33:00 +08:00
8Mi_Yile bab30e4f0a 修复版本号问题和Quilt标签 (#312)
* [skip ci] fix cannot get minecraft versions

* [skip ci] fix cannot auto add tag `Quilt`
2024-11-08 13:14:45 +08:00
ZekerZhayard 571d61118d Fix #314 (#315) 2024-11-08 08:33:39 +08:00
33 5d3326c333 feat: 14.21 2024-11-06 10:49:15 +08:00
ZekerZhayard b2095998e5 1.21.2 (#311) 2024-10-30 12:31:15 +08:00
ZekerZhayard cdf2fbe644 24w33a (#310) 2024-09-27 20:29:27 +08:00
xand fa0f820143 Bump Fabric and ForgeV3 (Forge & Neoforge) versions to 1.21.1 (#306)
* Bump Fabric and Forge/Neoforge compatibility to 1.21.1

* Bump version to 14.21

* Fix version in build.properties
2024-08-10 21:07:12 +08:00
8Mi_Yile 23f08a3a64 support upload add tag NeoForge (#298)
* Update common.yml

* Update common.yml

* Update common.yml

* Update common.yml

* Update common.yml
2024-08-10 20:50:16 +08:00
ZekerZhayard 3e4b06f5d1 Fix NullPointerException (#299) 2024-08-10 20:49:09 +08:00
33 18d31bed8f feat: 1.21 2024-07-03 00:14:19 +08:00
ZekerZhayard 64490f1d18 Support 1.21. (#297) 2024-07-02 22:43:35 +08:00
33 cd1922844c feat: bump version to 14.19.3 2023-12-21 22:57:00 +08:00
ZekerZhayard 4185e5bb5f Fix #286 (#287) 2023-12-21 22:28:03 +08:00
ZekerZhayard 7fd5ff84ee Fix #284 (#285) 2023-12-18 21:04:28 +08:00
33 d2772697f3 feat: remove forceIgnoreHttpsCertificate for security 2023-12-15 17:39:36 +08:00
ZekerZhayard 0ffa9ef137 23w42a (#281) 2023-12-12 00:04:05 +08:00
33 f4b5954dad feat: version 14.19 2023-12-12 00:03:41 +08:00
8Mi_Yile 009895c018 fix: issues: report-bug: CSL.log is requried (#280)
* Update report_bug.zh_CN.yml

* Update report_bug.en_US.yml
2023-12-06 19:12:30 +08:00
33 c273dc396e feat: fix upload 2023-11-01 13:39:37 +08:00
33 6cb37301b6 feat: add cloudflare r2 2023-11-01 12:12:56 +08:00
33 e9e1955fad feat: change version to 14.18.3 2023-10-19 15:28:59 +08:00
33 933f64b810 feat: fix method not found in 1.8-1.12.2 2023-10-19 15:28:08 +08:00
33 e839362f09 feat: fix build 2023-10-16 20:31:19 +08:00
ZekerZhayard 220bddbebb Fix #272 (#273) 2023-10-15 14:51:50 +08:00
33 00c931d434 feat: fix MinecraftCapes 2023-10-11 12:29:02 +08:00
33 119892489f feat: rename enum AuthlibField 2023-10-10 13:58:32 +08:00
ZekerZhayard 9a55a4c615 Adapting to Authlib changes (#269) 2023-10-10 13:54:23 +08:00
33 1ed98534c9 feat: version 14.18 2023-10-09 19:35:03 +08:00
ZekerZhayard b8ca913848 Support 1.20.2. (#266) 2023-09-28 20:49:25 +08:00
33 d5ae6226ae feat: update Java version in action 2023-07-14 01:06:39 +08:00
33 f274278419 feat: update README.md 2023-07-14 01:04:24 +08:00
33 f6f043fc7c feat: remove illegal EOF 2023-07-14 01:04:24 +08:00
33 9571e367df feat: tweak into multi line output 2023-07-14 01:04:24 +08:00
33 48efe58d52 feat: use multiple version in action 2023-07-14 01:04:24 +08:00
33 16520f72a4 feat: add multiple version in release 2023-07-14 01:04:24 +08:00
33 fd08f65af3 feat: cherry pick from 14-develop 2023-07-14 01:03:51 +08:00
33 83799da6ae feat: cheery pick from 14-develop 2023-07-14 01:01:10 +08:00
33 54d24a2800 fix: mod version in action 2023-07-14 00:59:31 +08:00
33 f2698b4ccf fix: GitHub pre-release in action 2023-07-14 00:59:31 +08:00
33 4a344ed653 fix: CurseForge and Modrinth upload 2023-07-14 00:59:31 +08:00
33 7074c8509d fix: CurseForge and Modrinth upload 2023-07-14 00:59:31 +08:00
33 10950a21ee fix: CurseForge upload 2023-07-14 00:59:31 +08:00
33 9889e05a81 feat: remove GitHub release action 2023-07-14 00:59:31 +08:00
8Mi_Yile e65ab7a9ea Update common.yml (#258) 2023-07-13 15:22:53 +08:00
33 a4f30a4bf1 fix: curseforge and modrinth release 2023-06-28 13:56:20 +08:00
33 68ac9f67df fix: use correct environment in upload task 2023-06-27 14:46:01 +08:00
33 647532629e fix: pull request won't run upload 2023-06-27 14:31:43 +08:00
33 71befeb300 fix: publish snapshot and canary to Tencent COS 2023-06-27 14:26:14 +08:00
8Mi_Yileandgithub-actions[bot] 8db9bf3de6 Add: common.yaml: CI Build Sync to Github Pre-Release (#256)
* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-06-27 13:49:59 +08:00
8Mi_Yileandgithub-actions[bot] 0c9a4033c4 add: common.yml: use matrix to multi-process upload file (#252)
* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-05-12 11:14:27 +08:00
ZekerZhayard d8d955224d Fix crash when the URL of skull profiles is not valid. (#255)
* Fix crash when the URL of skull profiles is not valid.

* Fix crash when the URL of skull profiles is not valid.
2023-05-07 16:38:36 +08:00
ZekerZhayard 8c0cdfb7b5 Support Fabric 23w16a. (#253) 2023-04-23 20:13:11 +08:00
33 919b69aaad Fix: GitHub Action Release 2023-04-17 21:57:55 +08:00
8Mi_Yileandgithub-actions[bot] 4de06aae50 issues-template: add option / common.yml: add support github release (#251)
* Auto Sync From

* Auto Sync From8MiYile/15-develop.zip

* Auto Sync From 8MiYile / 15-develop

* Auto Sync From 8MiYile / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

* Auto Sync From 8MiYile / MCCustomSkinLoader / 15-develop

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-17 21:45:32 +08:00
ZekerZhayard f3f80a1f00 Merge remote-tracking branch 'origin/14-develop' into 15-develop 2023-03-18 21:42:57 +08:00
ZekerZhayard f5b1989453 Fix: Skull textures not loading when using local skins. 2023-03-18 11:07:34 +08:00
ZekerZhayard 85923855d8 Support 1.19.4. Remove Vanilla 1.19.3. 2023-03-15 23:34:05 +08:00
ZekerZhayard 755f7647ed Remove: all vanilla editions 2023-01-29 22:52:21 +08:00
33 c2dad72690 Add: 15-develop 2023-01-29 16:03:22 +08:00
8Mi_Yile c8e96c11cd Add Github Issue Template's options in Report Bug (#242)
* Update report_bug.en_US.yml

* Update report_bug.zh_CN.yml

* Update report_bug.zh_CN.yml

* Update report_bug.en_US.yml

* Update report_bug.zh_CN.yml

* Update report_bug.en_US.yml

* Update report_bug.en_US.yml

* Update report_bug.zh_CN.yml

* Update report_bug.zh_CN.yml

* Update report_bug.zh_CN.yml

* Update report_bug.en_US.yml

* Update report_bug.zh_CN.yml
2023-01-28 12:42:38 +08:00
33 32e3e2e5a2 Add: GameProfile cache for Mojang API 2023-01-26 19:34:58 +08:00
33 b7b5e9d6c8 Add: LogManager 2023-01-26 18:51:38 +08:00
ZekerZhayard dfa7db1731 Fix: Modrinth release for Fabric edition 2023-01-26 16:26:08 +08:00
33 b645fd1665 Fix: Modrinth release 2023-01-26 15:39:37 +08:00
33 28fc81cb9a Fix: release build 2023-01-26 15:21:26 +08:00
33 bb0a47de4b Release: 14.15.2 2023-01-26 14:46:52 +08:00
33 d09b1d9807 Tweak: log file format 2023-01-24 18:43:17 +08:00
33 c207bdfc0e Fix: build action 2023-01-13 15:43:38 +08:00
33 69d35a69b7 Tweak: release build action 2023-01-13 15:22:29 +08:00
8Mi_Yile d767f40d32 添加 Issue Template (#238) 2023-01-13 15:12:40 +08:00
ZekerZhayard 5329a27d1a Fix: #199 2023-01-12 22:12:40 +08:00
33 ddefe00ac0 Add: more cape 2023-01-12 00:09:57 +08:00
33 dd4b706827 Add: support WynntilsAPI cape 2023-01-11 22:06:58 +08:00
33 84072c62f3 Add: support OptiFine cape 2023-01-11 18:51:44 +08:00
33 2d00e12f0a Update: README.md 2023-01-07 04:33:22 +08:00
33 b2b56f5be5 Add: GitHub Action for Pull Request 2023-01-07 01:24:12 +08:00
33 43c8ceb21e Add: show Quilt loader in CurseForge and Modrinth 2023-01-07 01:09:08 +08:00
33 a0ad239770 Release: 14.15.1 2023-01-07 00:26:22 +08:00
ZekerZhayard c8f0f7e283 Fix: loadSkin not being remapped 2023-01-07 00:20:17 +08:00
33 bfbd6ee31a Update: README.md 2023-01-05 15:28:27 +08:00
33 f8f3caad39 Fix: trigger release action by tag 2023-01-04 17:15:40 +08:00
33 bd409ae169 Tweak: trigger release action by tag 2023-01-04 17:11:43 +08:00
33 82f0aad9ff Release: 14.15 2023-01-04 16:37:33 +08:00
33 f2fce38137 Fix: pass secrets to reuse workflow 2023-01-04 16:27:28 +08:00
33 7d19f3114c Add: GitHub Action Test 2023-01-04 16:15:47 +08:00
33 d7a1e0f31f Update: certificate 2023-01-04 15:56:11 +08:00
33 201210f567 Fix: GitHub Action 2023-01-04 15:40:53 +08:00
33 26ed002689 Fix: GitHub Action 2023-01-04 15:39:55 +08:00
33 7d7e5c9060 Update: reuse GitHub Action workflow 2023-01-04 15:37:43 +08:00
33 81bf422250 Add: environment in GitHub Action 2023-01-04 15:12:17 +08:00
33 776e31e158 Fix: cos beta build upload 2023-01-04 14:50:30 +08:00
33 4a92223158 Fix: GitHub Action 2023-01-04 14:38:43 +08:00
33 264aacc8c0 Add: upload beta to cos 2023-01-04 14:34:46 +08:00
33 0b000731b5 Remove: Circle CI 2023-01-04 13:57:39 +08:00
33 f0012b58df Tweak: GitHub Action 2023-01-04 13:50:38 +08:00
33 013c22ae95 Add: GitHub Action 2023-01-04 13:43:08 +08:00
33 01d02a27b0 Update: circle ci version 2.1 2023-01-04 12:01:48 +08:00
33 077551e161 Tweak: only build release branch in circle ci 2023-01-04 12:01:48 +08:00
ZekerZhayard bd642d0106 Don't use ClassWriter.COMPUTE_FRAME anymore. (#234) 2023-01-02 14:21:51 +08:00
ZekerZhayard fbec7ce6bb Support 1.19.3. Remove Vanilla 1.19.2. (#231) 2022-12-12 02:26:22 +08:00
33 ea1b25a38f Tweak: add debug argument to Gradle 2022-12-07 21:24:51 +08:00
33 62018a3e8b Tweak: use Gradle Wrapper 2022-12-07 19:52:11 +08:00
ZekerZhayard f38a8ddcef Refactor SkinManager (#230) 2022-12-07 19:38:24 +08:00
33 63251c9f5e Add: a switch for printing to standard output 2022-11-24 21:42:45 +08:00
33 e94f4b0e99 Release: 14.14 2022-10-19 11:35:43 +08:00
33 5ee2eee382 Add: LICENSE 2022-08-27 10:42:38 +08:00
ZekerZhayard 3063de7ff0 Support 1.19.2. Remove Vanilla 1.19.1. (#220) 2022-08-17 10:47:26 +08:00
33 583bf1fe6a Tweak: calculate correct hash for base64 texture 2022-07-29 02:29:15 +08:00
33 a3de21497d Fix: MinecraftCapesAPI 2022-07-29 02:15:19 +08:00
33 51aec265be Tweak: LegacyLoader UUID fallback logic 2022-07-29 01:14:50 +08:00
33 52caeb3bdc Tweak: compatible with authlib 3.11.50 2022-07-29 00:07:04 +08:00
33 a3fa4e47c6 Fix: MinecraftCapesAPI load profile only with existing UUID 2022-07-29 00:05:51 +08:00
33 e1cde0afc7 Tweak: correct MinecraftCapesAPI name 2022-07-28 11:04:27 +08:00
33 3f379f3cbe Tweak: register MinecraftCapesAPI 2022-07-28 11:03:27 +08:00
33 f50640139a Add: MinecraftCapesAPI 2022-07-28 10:59:54 +08:00
ZekerZhayard 46b8635e10 Support 1.19.1. Remove Vanilla 1.19. (#218) 2022-07-28 09:24:44 +08:00
33 02b24229f3 Update: LittleSkin root url 2022-07-28 08:44:30 +08:00
33 941b421d86 Fix: CDN cache wasn't be updated correctly 2022-07-28 08:43:41 +08:00
33 a67ed507ec Fix: CurseForge metadata json 2022-07-27 20:32:55 +08:00
33 851fa81f31 Tweak: change log level in build 2022-07-27 19:47:12 +08:00
33 5bb16ededa Fix: CurseForge uploading 2022-07-27 19:31:32 +08:00
33 1e5bfcd1e7 Fix: Minecraft version getting logic 2022-07-27 17:23:50 +08:00
ZekerZhayard 1b85fa8ff9 Convert all build scripts to buildSrc. (#216) 2022-07-20 23:11:48 +08:00
33 e1e5319bdb Add: detail.json with detailed downloading information 2022-07-19 22:22:14 +08:00
33 187be47e88 Add: Custom Gradle Plugin in buildSrc 2022-07-19 20:40:53 +08:00
ZekerZhayard b2f8d2cc38 Support 1.19, Remove Vanilla 1.17.1 (#211) 2022-06-09 10:00:10 +08:00
ZekerZhayard 8b641e0227 Support Fabric 22w14a. (#208) 2022-04-14 19:52:11 +08:00
ZekerZhayard c90cea3721 Remove transformers of SkullTileEntity (#207)
* Bump to 14.14

* Remove transformers of SkullTileEntity
2022-04-01 13:56:20 +08:00
33 b0c11d11c6 Fix curseforge and modrinth release 2022-03-17 11:07:25 +08:00
33 c77ac58f6d Release CustomSkinLoader 14.13 2022-03-17 10:41:59 +08:00
ZekerZhayard 16fadc56b4 Support Forge/Fabric/Vanilla 1.18.2. Remove Vanilla 1.18.1. (#206) 2022-03-03 17:31:20 +08:00
33 fc6c43bac9 Fix standalone elytra url (#204) 2022-02-22 17:38:53 +08:00
ZekerZhayard b6fc1610bc Fix skull not loading if not need to judge type. (#201) 2022-01-24 13:58:06 +08:00
ZekerZhayard c7d04976e6 Fix skin type judgement from cache. (#200)
Signed-off-by: ZekerZhayard <[email protected]>
2022-01-09 21:58:59 +08:00
ZekerZhayard 0eaf1960bf Support Fabric/Forge/Vanilla 1.18.1. (#196)
* Support Fabric and Vanilla 1.18.

Signed-off-by: ZekerZhayard <[email protected]>

* Support Fabric and Vanilla 1.18.

Signed-off-by: ZekerZhayard <[email protected]>

* Support Fabric, Forge and Vanilla 1.18.1.

Signed-off-by: ZekerZhayard <[email protected]>
2021-12-11 16:27:36 +08:00
ZekerZhayard cff5846e7f Fix NPE if type is null. (#195)
* Fix NPE if type is null.

Signed-off-by: ZekerZhayard <[email protected]>

* Forge does not support Java 18 for now.

Signed-off-by: ZekerZhayard <[email protected]>
2021-11-28 02:17:38 +08:00
ZekerZhayard c8fb6e216e Finish loader names for Modrinth. (#193)
Signed-off-by: ZekerZhayard <[email protected]>
2021-11-12 19:14:07 +08:00
ZekerZhayard a5d466e0a7 Added support for automatic upload to CurseForge and Modrinth. (#190)
* Added support for automatic upload to CurseForge and Modrinth.

Signed-off-by: ZekerZhayard <[email protected]>

* Fix defining environment variable in circle ci.

Signed-off-by: ZekerZhayard <[email protected]>

* Fix defining environment variable in circle ci.

Signed-off-by: ZekerZhayard <[email protected]>

* Finish fixing defining environment.

Signed-off-by: ZekerZhayard <[email protected]>
2021-11-04 14:55:59 +08:00
Uriel 31fffa5d23 support tlauncher (#188)
* support tlauncher

* it works

* Update README.md

* simplify things

* undo wildcard

* facepalm

* update tlauncher info
2021-11-04 14:52:05 +08:00
ZekerZhayard 7e9f7fa498 Compatible with fabric-loader-0.12.x in development environment. (#189)
Signed-off-by: ZekerZhayard <[email protected]>
2021-10-16 01:41:54 +08:00
ZekerZhayard f51b55be6e Fix compatible with OptiFine 1.17.1. (#186) 2021-10-03 18:06:58 +08:00
ZekerZhayard 584c7b7518 Improve skin loading logic. (#180) 2021-09-24 11:19:06 +08:00
ZekerZhayard 51c8900562 Support Forge 1.17.1. (#177) 2021-07-25 15:48:50 +08:00
ZekerZhayard ab7aebb753 Support Vanilla and Fabric 1.17.1. Remove Vanilla 1.17. (#175) 2021-07-07 00:21:36 +08:00
ZekerZhayard dc5ecfb576 Support Vanilla and Fabric 1.17. Remove Vanilla 1.15.2. (#171)
* Support Fabric 1.17-rc2.

* Support Vanilla and Fabric 1.17. Remove Vanilla 1.15.2.
2021-06-09 14:55:20 +08:00
ZekerZhayard 04899ff676 Support Fabric 1.17-pre1. (#170) 2021-05-29 18:53:27 +08:00
ZekerZhayard 4df8ce38d6 Fix CustomSkinAPIPlus loading incorrectly. Fix unable to complete config with default value. (#168) 2021-05-25 12:55:42 +08:00
ZekerZhayard 3e001c4cdf Fix elytra can not be rendered when the cape doesn't contain elytra. (#160)
* Fix elytra can not be rendered when the cape doesn't contain elytra.

* Fix typo.

* Streamline IFakeThreadDownloadImageData.

* Fix wrong arguments.

* Add compatible with other custom player model mods, such as tr7zw/FirstPersonModel
2021-05-07 17:15:45 +08:00
ZekerZhayard d5dea652ff Induce users to download the pre-release version. (#164)
* Induce users to download the pre-release version.

* Add contact us.

* Some versions of forge-1.13.2 is not compatible because of the strong limitation of CoreMods-0.3.0.
2021-05-07 17:10:01 +08:00
ZekerZhayard 2a4226527d Prevent authlib-injector from modifying urls. (#159) 2021-05-01 22:46:02 +08:00
ZekerZhayard 6c9494970f Enhanced default skin loaders. (#157)
* Enhance ICustomSkinLoaderPlugin.

* Support auto update config file per snapshot. Fix crash with forge 1.14.2 ~ 1.15.2.

* ElyByAPI should check root now.

* Remove unnecessary packages, add some deprecated loaders.

* Reformat imports.

* Move forge stuffs to another commit.

* Fix config updating incorrectly.
2021-04-24 10:33:18 +08:00
ZekerZhayard c84f506af1 Fix crash with forge 1.14.2~1.16.2. Upgrade forge maven. (#158)
* Fix crash with forge 1.14.2~1.16.2. Upgrade forge maven.

* Update forge maven url.
2021-04-23 22:07:53 +08:00
ZekerZhayard a0e31ed883 Change Mixin priority to prevent potential Mixin conflict. (#154) 2021-04-22 11:03:06 +08:00
ZekerZhayard 8befcb32d8 No longer remove any elements in SkinManager. (#151) 2021-03-27 19:32:00 +08:00
ZekerZhayard fb50a3db6d Support Fabric 21w10a. (#148) 2021-03-13 19:47:18 +08:00
ZekerZhayard 4daacd18e8 Make it easier to build the development environment. (Phase 2) (#147)
* Make it easier to build the development environment. (Phase 2)

* Provide sources jar.

* Add development guide.

* Improve development guide.
2021-03-13 19:46:51 +08:00
ZekerZhayard 98681e8251 Remove updateGameProfile transformer. (#143)
* Add an option to control updateGameProfile transformer.

* Remove unnecessary FrameNodes
2021-02-08 11:37:04 +08:00
ZekerZhayard ea5d890992 Support 1.16.5. Remove 1.16.4 Vanilla. (#141) 2021-01-17 01:57:36 +08:00
ZekerZhayard f5135872cc Fix rendering transparent capes for Forge 1.15+. (#140) 2021-01-12 22:59:14 +08:00
ZekerZhayard 5d736dd4b5 Fix sign jar. (#137) 2021-01-04 15:29:34 +08:00
ZekerZhayard 1b2a4dc260 Make it easier to build the development environment. (#133)
* Fix the warning about removing duplicate source roots when open the project with Intellij IDEA.

* Add Gradle wrapper.

* CustomSkinLoader can be loaded in Forge development environment now.

* CustomSkinLoader can be loaded in Fabric development environment now.
2021-01-03 02:53:57 +08:00
ZekerZhayard 855131d1aa Fix DefaultFMLPlatform can't be loaded when other FML platform being used. (#132) 2020-12-20 01:02:07 +08:00
ZekerZhayard 581a2dddea Change the ordinal of FMLLoadingPlugin to fix the crash with BetterFps before Minecraft 1.10.2. (#131)
Clean up codes.
2020-12-15 21:17:10 +08:00
ZekerZhayard a1b52eb7ac Fix version.json parser, compatible with 20w45a. (#128) 2020-11-05 21:54:43 +08:00
Alexander Xia 0ed371fdc1 Remove GitHub maven temporarily 2020-11-05 18:08:26 +08:00
ZekerZhayard ee7e57cf78 Support 1.16.4. Remove 1.16.3 Vanilla. (#127) 2020-11-05 11:53:12 +08:00
ZekerZhayard 90ed224dd8 Fix ResourceLocation characters limitation for Minecraft 1.13+ (#126) 2020-11-05 11:52:49 +08:00
ZekerZhayard a65445e989 Make sure the mod being absent on the other network side does not cause the client to display the server as incompatible after forge-1.13.2-25.0.107. (#124) 2020-11-05 11:52:36 +08:00
ZekerZhayard da79597a16 Fix crash on launch with forge-1.16.3-34.1.27. (#122) 2020-10-27 21:52:29 +08:00
ZekerZhayard 9c6102a813 Fix incorrect method descriptions. (#119) 2020-09-29 21:19:15 +08:00
ZekerZhayard 573c5e4a20 Fabric and vanilla jars can be signed now. (#118) 2020-09-27 16:57:36 +08:00
ZekerZhayard 12441cc379 Fix rendering transparent skins and capes for 19w41a+. (#117)
* Support 1.16.3. Remove 1.16.2 Vanilla.

* Fix rendering transparent skins and capes for 19w41a+.
2020-09-20 21:12:14 +08:00
ZekerZhayard 7df6336b56 Support 1.16.3. Remove 1.16.2 Vanilla. (#116) 2020-09-11 22:55:26 +08:00
ZekerZhayard 2dd69e08da Fix InvalidMixinException before 1.15-snapshot. (#115) 2020-09-02 12:30:25 +08:00
ZekerZhayard 67fbcf5cec Fix crashes caused by incorrect stack frames. (#114) 2020-09-02 12:29:54 +08:00
ZekerZhayard f898831276 Prepare for compatibility with 1.7.10. (#113) 2020-08-29 17:20:44 +08:00
ZekerZhayard 83042f45bd Allow APortingCore to load CustomSkinLoader. (#112) 2020-08-24 11:52:23 +08:00
ZekerZhayard dc6d135699 Add the function to print the System and Java version to the log file. (#111) 2020-08-21 12:51:59 +08:00
Alexander Xia f42496e04c Tweak cache config 2020-08-16 22:18:25 +08:00
Alexander Xia f003d57ddf Tweak thread pool 2020-08-16 21:55:06 +08:00
Alexander Xia b64700b9fb Add forceDisableCache 2020-08-16 21:07:22 +08:00
ZekerZhayard f64af50a07 Improve downloading http textures. (#108) 2020-08-16 19:50:19 +08:00
Alexander XiaandZekerZhayard a8c8edaf20 Support 1.16.2 Fabric, Forge and Vanilla. Remove 1.16.1 Vanilla. (#107)
* Support 1.16.2 Fabric, Forge and Vanilla. Remove 1.16.1 Vanilla.

* Delete build.properties

* Create build.properties

Co-authored-by: ZekerZhayard <[email protected]>
2020-08-13 16:22:16 +08:00
293 changed files with 10344 additions and 4452 deletions

No files matched your search

-38
View File
@@ -1,38 +0,0 @@
# Java Gradle CircleCI 2.0 configuration file
version: 2
jobs:
build:
docker:
- image: circleci/openjdk@sha256:7be33522f6f0ca65c2e78b22b1ef3e6739038494c1de1b8fb6d96da400dccf53
working_directory: ~/repo
environment:
JVM_OPTS: -Xmx3200m
TERM: dumb
steps:
- checkout
- restore_cache:
keys:
- gradle-cache
# Gradle Wrapper
# - run: sudo chmod +x gradlew
# - run: ./gradlew --version
# - run: ./gradlew clean build
# Gradle
- run: gradle --version
- run: gradle clean build
- run: gradle upload
- run: gradle publishGprPublicationToGitHubPackagesRepository
- store_artifacts:
path: ./build/libs
- save_cache:
paths:
- ~/.gradle
key: gradle-cache
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: Telegram
url: https://t.me/customskinloader
about: Gugugu
- name: QQ
url: https://jq.qq.com/?_wv=1027&k=vF16R5tg
about: Gugugu
+126
View File
@@ -0,0 +1,126 @@
name: Report Bug
description: Report a bug and help us improve CustomSkinLoader
labels: [ bug ]
title: "[Bug] "
body:
- type: markdown
attributes:
value: |
Here is the Report Bug issue for CustomSkinLoader
With a red asterisk for the mandatory items
Please keep the work order content neat and tidy, do not paste the contents of the log file directly onto the work order, it will look very messy and unattractive work orders
- type: textarea
id: description
attributes:
label: Describe the bug
description: |
A clear and concise description of what the issue is.
Provide as much information as possible, videos, crash reports, etc.
DO NOT PASTE A CRASH REPORT HERE!!!
validations:
required: true
- type: textarea
id: reproducing
attributes:
label: Steps to reproduce
description: How do you trigger this bug?
render: bash
value: |
1.
2.
3.
validations:
required: true
- type: input
id: crash-report
attributes:
label: Link to crash-report if applicable
description: |
The files are in the folder `<minecraft-directory>/crash-reports`
[Generate URL](https://mclo.gs)
placeholder: "Ex: https://mclo.gs/xxxxxx"
- type: input
id: csl-log
validations:
required: true
attributes:
label: Link to CustomSkinLoader.log if applicable
description: |
The path to the file is `<minecraft-directory>/CustomSkinLoader/CustomSkinLoader.log`.
[Generate URL](https://mclo.gs)
placeholder: "Ex: https://mclo.gs/xxxxxx"
- type: input
id: latest-log
attributes:
label: Link to latest.log if applicable
description: |
The path to the file is `<minecraft-directory>/logs/latest.log`.
[Generate URL](https://mclo.gs)
placeholder: "Ex: https://mclo.gs/xxxxxx"
- type: input
id: forge-log
attributes:
label: "[Only Forge User] Link to Forge Log if applicable"
description: |
The path to the file is `<minecraft-directory>/logs/debug.log` or `<minecraft-directory>/logs/fml-client-latest.log`.
if your mod loader isn't `Forge`, URL can set empty
[Generate URL](https://mclo.gs)
placeholder: "Ex: https://mclo.gs/xxxxxx"
- type: input
id: mod-version
attributes:
label: Mod Version
placeholder: "Ex: 14.16"
validations:
required: true
- type: input
id: mc-version
attributes:
label: Minecraft Version
placeholder: "Ex: 1.19.4"
validations:
required: true
- type: input
id: mc-launcher-version
attributes:
label: Minecraft Launcher Name and Version
placeholder: "Ex: HMCL v3.5.4.232"
description: |
If you don't know the version of the game, you can just fill in the name of the game launcher
- type: dropdown
id: loader-type
attributes:
label: Mod Loader
options:
- Quilt
- Fabric
- Forge
- <without mod loader>
validations:
required: true
- type: dropdown
id: operating-systems
attributes:
label: Operating System
options:
- Windows
- Linux
- macOS
- Other
validations:
required: true
- type: checkboxes
id: prerequisites
attributes:
label: Before submitting a bug report
options:
- label: |
This bug wasn't already reported (I have searched bug reports on GitHub).
required: true
- label: |
This is a valid bug (I am able to reproduce this on the latest dev build).
required: true
- label: |
This problem is triggered in the latest version of the mod (if not the latest please upgrade the mod first)
required: true
+127
View File
@@ -0,0 +1,127 @@
name: 提交问题
description: 报告问题以帮助我们改进CustomSkinLoader
labels: [ bug ]
title: "[Bug] "
body:
- type: markdown
attributes:
value: |
你好,这里是 `CustomSkinLoader`
标注红色星号的为必填项
以及,保持工单干净整洁,不要直接将日志内容粘贴到工单上,比如粘贴到描述内是不行的
- type: textarea
id: description
attributes:
label: 描述问题
description: |
简单的描述问题, 并提供类似图片、视频,以更好的报告错误(如果可以)
!注意:请不要在这里放日志文件或崩溃报告文件的内容
validations:
required: true
- type: textarea
id: reproducing
attributes:
label: 复现步骤
description: 请问你是如何触发这个问题的
render: bash
value: |
1.
2.
3.
validations:
required: true
- type: input
id: crash-report
attributes:
label: 崩溃报告查看地址
description: |
在游戏目录下的 `crash-reports` 文件夹下,里面找最近的报告生成时间
客户端若无崩溃则直接填写 `客户端无崩溃`
[生成连接](https://mclo.gs)
placeholder: "示例: https://mclo.gs/xxxxxx"
- type: input
id: csl-log
validations:
required: true
attributes:
label: CustomSkinLoader.log 查看地址
description: |
文件路径:`<游戏路径>/CustomSkinLoader/CustomSkinLoader.log`.
[生成连接](https://mclo.gs)
placeholder: "示例: https://mclo.gs/xxxxxx"
- type: input
id: latest-log
attributes:
label: latest.log 查看地址
description: |
文件路径:`<游戏路径>/logs/latest.log`.
[生成连接](https://mclo.gs)
placeholder: "示例: https://mclo.gs/xxxxxx"
- type: input
id: forge-log
attributes:
label: "[仅Forge用户] Forge Log 查看地址"
description: |
文件路径:`<游戏路径>/logs/debug.log` 或者 `<游戏路径>/logs/fml-client-latest.log`.
若没有使用 `Forge` 加载器的,可以不填写
[生成连接](https://mclo.gs)
placeholder: "示例: https://mclo.gs/xxxxxx"
- type: input
id: mod-version
attributes:
label: 模组版本
placeholder: "示例: 14.16"
validations:
required: true
- type: input
id: mc-version
attributes:
label: Minecraft游戏版本
placeholder: "示例: 1.19.4"
validations:
required: true
- type: input
id: mc-launcher-version
attributes:
label: Minecraft启动器 名称 及 版本
placeholder: "示例: HMCL v3.5.4.232"
description: |
若不知道游戏版本 可以只填写游戏启动器的名称
validations:
required: true
- type: dropdown
id: loader-type
attributes:
label: 模组加载器
options:
- Quilt
- Fabric
- Forge
- 不使用加载器
validations:
required: true
- type: dropdown
id: operating-systems
attributes:
label: 操作系统
options:
- Windows
- Linux
- macOS
- 其他操作系统
validations:
required: true
- type: checkboxes
id: prerequisites
attributes:
label: 在提交错误报告之前,有没有做到...
options:
- label: |
先尝试搜索issues里面, 查看并确认打开或关闭的工单, 是否搜索不到
required: true
- label: |
确认你的模组版本是最新的开发版本,且文件下载正确,没有出现类似forge下载了fabric版的这类基础问题
required: true
- label: |
这个问题是在最新的mod版本触发(若不是最新的请先升级mod)
required: true
@@ -0,0 +1,22 @@
name: Suggestion
description: Suggest a new feature or change for CustomSkinLoader.
labels: [ enhancement ]
body:
- type: textarea
id: description
attributes:
label: Describe the feature
description: A clear and concise description of what the feature/change is.
validations:
required: true
- type: checkboxes
id: prerequisites
attributes:
label: Before submitting a suggestion
options:
- label: |
This feature doesn't already exist in the client. (I have checked every module and their settings on the **latest dev build**)
required: true
- label: |
This wasn't already suggested. (I have searched suggestions on GitHub and read the FAQ)
required: true
@@ -0,0 +1,22 @@
name: 反馈或建议
description: 给CustomSkinLoader这个模组提个建议
labels: [ enhancement ]
body:
- type: textarea
id: description
attributes:
label: 描述一下
description: 简单描述一下该功能/变化是什么。
validations:
required: true
- type: checkboxes
id: prerequisites
attributes:
label: 在提交反馈或建议之前,请先确认...
options:
- label: |
你要提交的反馈或者建议不存在于本模组的最新开发版下.
required: true
- label: |
以及在issues或者Wiki内搜索过, 并且无结果
required: true
+14
View File
@@ -0,0 +1,14 @@
name: Beta
on:
push:
branches:
- '14-develop'
jobs:
build-beta:
name: Build Beta
uses: ./.github/workflows/common.yml
with:
type: Beta
publish-task: uploadBeta
secrets: inherit
+14
View File
@@ -0,0 +1,14 @@
name: Canary
on:
push:
branches:
- '15-develop'
jobs:
build-canary:
name: Build Canary
uses: ./.github/workflows/common.yml
with:
type: Canary
publish-task: uploadCanary
secrets: inherit
+238
View File
@@ -0,0 +1,238 @@
name: Common
on:
workflow_call:
inputs:
type:
required: true
type: string
publish-task:
required: false
type: string
is-snapshot:
required: false
type: boolean
default: true
jobs:
build-common:
name: Build
runs-on: ubuntu-latest
environment: Build
steps:
-
name: Checkout
uses: actions/checkout@v4
-
name: Set up JDK
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '8'
cache: 'gradle'
-
name: Build
env:
KEY_PASS: ${{ secrets.KEY_PASS }}
IS_SNAPSHOT: ${{ inputs.is-snapshot }}
run: |
echo Snapshot: $IS_SNAPSHOT
export GIT_COMMIT_DESC=$(git log --format=%B -n 1 $GITHUB_SHA)
./gradlew clean build --stacktrace
-
uses: actions/upload-artifact@v4
name: Publish to Github Artifact
with:
name: CustomSkinLoader-${{ inputs.type }}-${{ github.run_number }}
path: build/libs
Upload:
if: inputs.publish-task
needs: build-common
continue-on-error: true
environment: Build
strategy:
matrix:
website: [CurseForge_Modrinth]
modtype: [Fabric,ForgeV1,ForgeV2,ForgeV3]
include:
-
website: ObjectStorage
modtype: All
# -
# website: GitHub-Release
# modtype: All
-
website: GitHub-PreRelease
modtype: All
name: ${{ matrix.website }} (${{ matrix.modtype}})
runs-on: ubuntu-latest
steps:
-
name: Checkout Git Repository
uses: actions/checkout@v4
-
uses: actions/download-artifact@v4
name: Download Artifact Zips
with:
path: build
-
name: Preparation Folder
run: |
rsync -avz "build/$(ls build|grep "CustomSkinLoader")/" build/libs/
ls -lh build
-
if: ${{ matrix.modtype != 'All' }}
name: Checking and setting the environment
id: cslenv
run: |
output="$(ls build/libs | grep -v "sources")"
case "${{ matrix.modtype }}" in
"ForgeV1")
modloader="Forge"
path=`echo "${{ matrix.modtype }}" | sed 's#V#/V#'`
;;
"ForgeV2" | "ForgeV3")
modloader=$(cat <<EOF
Forge
NeoForge
EOF
)
path=`echo "${{ matrix.modtype }}" | sed 's#V#/V#'`
;;
"Fabric")
modloader=$(cat <<EOF
Fabric
Quilt
EOF
)
path="${{ matrix.modtype }}"
;;
*)
echo "Unsupported modtype: ${{ matrix.modtype }}"
exit 1
;;
esac
echo "path=$path" >> $GITHUB_OUTPUT
echo "modloader="$modloader"" >> $GITHUB_OUTPUT
echo "filename=$(echo "$output"|grep $(echo ${{ matrix.modtype }}|sed "s#-##") )" >> $GITHUB_OUTPUT
echo "version=$(grep "version=" build.properties | grep -v "#" | sed "s/version=//")" >> $GITHUB_OUTPUT
echo "edition=$(echo ${{ matrix.modtype }} | sed "s/-//")" >> $GITHUB_OUTPUT
echo "minecraft_vers<<EOF" >> $GITHUB_OUTPUT
grep "dependencies=" "$path"/build.properties | grep -v "#" | awk -F '|' '{print $2}' | sed 's#\;\\##' | sed "s/,/\n/g" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
echo "java_vers<<EOF" >> $GITHUB_OUTPUT
grep "java_full_versions=" "$path"/build.properties | grep -v "#" | sed "s/java_full_versions=//" | sed "s/,/\n/g" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
-
if: startsWith(matrix.website, 'GitHub-')
name: Settings more strings to Environment
id: cslenv-github
run: |
#展开
echo "buildtime=$(TZ=Asia/Shanghai date "+%Y.%m.%d %H:%M")" >> $GITHUB_OUTPUT
echo "pathlist="$(find build/libs -type f|grep -v "sources"|grep -v "json")"" >> $GITHUB_OUTPUT
-
if: ${{ matrix.website == 'GitHub-PreRelease' && startsWith(github.ref, 'refs/heads') }}
name: "[GitHub Pre-Release] Delete"
uses: 8Mi-Tech/delete-release-assets-action@main
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
tag: CI-Build
deleteOnlyFromDrafts: false
-
if: ${{ matrix.website == 'GitHub-PreRelease' && startsWith(github.ref, 'refs/heads') }}
name: 【GitHub Pre-Release】 Set CI-Build Text
run: |
cat > build/ci-build.md << 'EOF'
Build Time / 构建时间 : ${{ steps.cslenv-github.outputs.buildtime }}
自动同步分支 ${{ github.ref_name }} 的代码,以保持最新
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
<br>
[如何使用 / How to uses?](https://github.com/xfl03/MCCustomSkinLoader/wiki/How-to-Use)
EOF
-
if: ${{ matrix.website == 'GitHub-PreRelease' && startsWith(github.ref, 'refs/heads') }}
name: "[GitHub Pre-Release] Upload Tag"
uses: richardsimko/update-tag@v1
with:
tag_name: CI-Build
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-
if: ${{ matrix.website == 'GitHub-PreRelease' && startsWith(github.ref, 'refs/heads') }}
name: "[GitHub Pre-Release] Publish"
uses: softprops/action-gh-release@v2
with:
token: ${{ secrets.GITHUB_TOKEN }}
name: CustomSkinLoader CI-Build
tag_name: CI-Build
prerelease: true
body_path: build/ci-build.md
files: build/libs/*
#files: "${{ steps.cslenv-github.outputs.pathlist }}"
-
if: ${{ matrix.website == 'GitHub-Release' && inputs.type == 'Release' }}
uses: softprops/action-gh-release@v1
name: "[GitHub Release] Publish"
with:
token: ${{ secrets.GITHUB_TOKEN }}
name: CustomSkinLoader ${{ github.ref }}
tag_name: ${{ github.ref }}
#generate_release_notes: true
files: ${{ steps.cslenv-github.outputs.pathlist }}
-
if: ${{ matrix.website == 'ObjectStorage' }}
name: "[ObjectStorage] Force JDK 8"
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '8'
cache: 'gradle'
-
if: ${{ matrix.website == 'ObjectStorage' }}
name: "[ObjectStorage] Publish"
env:
COS_BUCKET: ${{ secrets.COS_BUCKET }}
COS_SECRET_ID: ${{ secrets.COS_SECRET_ID }}
COS_SECRET_KEY: ${{ secrets.COS_SECRET_KEY }}
R2_BASE_URL: ${{ secrets.R2_BASE_URL }}
R2_BUCKET: ${{ secrets.R2_BUCKET }}
R2_SECRET_ID: ${{ secrets.R2_SECRET_ID }}
R2_SECRET_KEY: ${{ secrets.R2_SECRET_KEY }}
IS_SNAPSHOT: ${{ inputs.is-snapshot }}
run: |
export GIT_COMMIT_DESC=$(git log --format=%B -n 1 $GITHUB_SHA)
./gradlew ${{ inputs.publish-task }} --info --stacktrace
# ./gradlew publishGprPublicationToGitHubPackagesRepository
-
if: ${{ matrix.website == 'CurseForge_Modrinth' && inputs.type == 'Release' }}
name: "[CurseForge & Modrinth] Publish"
uses: Kir-Antipov/[email protected]
with:
modrinth-id: idMHQ4n2
modrinth-featured: true
modrinth-unfeature-mode: subset
modrinth-token: ${{ secrets.MODRINTH_TOKEN }}
curseforge-id: 286924
curseforge-token: ${{ secrets.CURSEFORGE_API_KEY }}
name: CustomSkinLoader_${{ steps.cslenv.outputs.edition }}_${{ steps.cslenv.outputs.version }}
version: ${{ steps.cslenv.outputs.version }}-${{ steps.cslenv.outputs.edition }}
version-type: release
loaders: ${{ steps.cslenv.outputs.modloader }}
game-versions: |
${{ steps.cslenv.outputs.minecraft_vers }}
game-version-filter: releases
java: |
${{ steps.cslenv.outputs.java_vers }}
retry-attempts: 2
retry-delay: 10000
fail-mode: fail
files: |
build/libs/${{ steps.cslenv.outputs.filename }}
+17
View File
@@ -0,0 +1,17 @@
name: Pull Request
on:
pull_request:
types:
- opened
- synchronize
- reopened
branches:
- '14-develop'
- '15-develop'
jobs:
build-pull-request:
name: Build Pull Request
uses: ./.github/workflows/common.yml
with:
type: PullRequest
+14
View File
@@ -0,0 +1,14 @@
name: Release
on:
release:
types: [released]
jobs:
build-release:
name: Build Release
uses: ./.github/workflows/common.yml
with:
type: Release
publish-task: upload
is-snapshot: false
secrets: inherit
+8 -3
View File
@@ -11,6 +11,7 @@ hs_err_pid*
.vscode/
# eclipse
bin/
*/.classpath
.classpath
*/.project
@@ -21,11 +22,15 @@ hs_err_pid*
# gradle
.gradle/
build/
gradle/
gradlew*
logs/
run/
# IDEA
.idea/
*.iml
out/
*.ipr
*.iws
out/
#mac OS
.DS_Store
-153
View File
@@ -1,153 +0,0 @@
/**
* Gradle Script for COS
* It can be used to upload or download file from Tencent Cloud COS.
* COS: https://cloud.tencent.com/document/product/436
*/
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.qcloud:cos_api:5.4.6'
}
}
import com.qcloud.cos.COSClient
import com.qcloud.cos.ClientConfig
import com.qcloud.cos.auth.BasicCOSCredentials
import com.qcloud.cos.auth.COSCredentials
import com.qcloud.cos.model.PutObjectRequest
import com.qcloud.cos.model.GetObjectRequest
import com.qcloud.cos.region.Region
String getMcVersion(String filename) {
if (filename.endsWith(".json"))
return filename.substring(0, filename.indexOf('-'))
return filename.substring(filename.indexOf('_') + 1, filename.indexOf('-'))
}
String getKey(String filename) {
String name = filename.substring(0, filename.lastIndexOf('.'))
if (name.indexOf('-') == -1) return null
if (filename.endsWith(".json"))
return String.format(
"versions/%s/%s",
name,
filename
)
if (filename.endsWith(".jar")) {
if (filename.contains("Fabric") || filename.contains("Forge")) {
return String.format(
"mods/%s",
filename
)
} else {
return String.format(
"libraries/customskinloader/%s/%s/%s",
name.substring(0, name.indexOf('-')),
name.substring(name.indexOf('-') + 1),
filename
)
}
}
return filename
}
ext.bucketName = System.getenv("COS_BUCKET")
ext.cosUrl = "https://csl.littleservice.cn/"
ext.cosClient0 = null
COSClient getCosClient() {
if (cosClient0 != null) return cosClient0
COSCredentials cred = new BasicCOSCredentials(System.getenv("COS_SECRET_ID"), System.getenv("COS_SECRET_KEY"))
ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"))
cosClient0 = new COSClient(cred, clientConfig)
}
void uploadFile(String key, File file) {
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file)
getCosClient().putObject(putObjectRequest)
}
void downloadFile(String key, File file) {
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key)
getCosClient().getObject(getObjectRequest, file)
}
String toJson(Map<String, Object> map, int d) {
StringBuilder sb = new StringBuilder("{\n")
Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator()
while (it.hasNext()) {
Map.Entry<String, Object> e = it.next()
String k = e.key
String v = null
if (e.value instanceof String) {
v = "\"" + e.value + "\""
} else if (e.value instanceof Map) {
v = toJson((Map) e.value, d + 1)
}
for (int i = 0; i < d * 2; i++) {
sb.append(' ')
}
if (it.hasNext()) {
sb.append(String.format("\"%s\" : %s,\n", k, v))
} else {
sb.append(String.format("\"%s\" : %s\n", k, v))
}
}
for (int i = 0; i < (d - 1) * 2; i++) {
sb.append(' ')
}
sb.append("}")
return sb.toString()
}
String toJson(Map<String, Object> map) {
return toJson(map, 1)
}
void writeToFile(File f, String s) {
FileWriter fw = new FileWriter(f)
fw.write(s)
fw.flush()
fw.close()
}
void uploadArtifacts(String shortVersion) {
File dir = rootProject.file("build/libs")
if (!dir.isDirectory()) return
String cslversion = shortVersion.replace(".", "")
LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>()
LinkedHashMap<String, String> map2 = new LinkedHashMap<String, String>()
LinkedHashMap<String, String> map3 = new LinkedHashMap<String, String>()
map.put("version", shortVersion)
map.put("downloads", map2)
map.put("launchermeta", map3)
File[] files = dir.listFiles()
for (file in files) {
String key = getKey(file.getName())
if (key == null) continue
uploadFile(key, file)
String url = cosUrl + key
String mcversion = getMcVersion(file.getName())
println(String.format("csl-%s-%s\t%s", mcversion.replace(".", "").toLowerCase(), cslversion, url))
if (key.endsWith(".jar")) {
map2.put(mcversion, url)
} else if (key.endsWith(".json")) {
map3.put(mcversion, url)
}
}
File latest = new File("build/libs/latest.json")
writeToFile(latest, toJson(map))
uploadFile("latest.json", latest)
}
ext {
uploadArtifacts = this.&uploadArtifacts
}
-63
View File
@@ -1,63 +0,0 @@
/**
* Gradle Script for Remap
* Designed for remapping jar.
* Remap Jar: mcp<->srg<->notch
*/
buildscript {
repositories {
mavenCentral()
maven {
name = "forge"
url = "http://files.minecraftforge.net/maven"
}
}
dependencies {
classpath 'net.md-5:SpecialSource:1.8.6'
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
}
}
import net.md_5.specialsource.JarMapping
import net.md_5.specialsource.JarRemapper
import net.md_5.specialsource.provider.JarProvider
import net.md_5.specialsource.provider.JointProvider
void reobfSrgToNotch() {
def srgName = "${archivesBaseName}-${version}-srg.jar"
def notchName = srgName.replace('-srg', '')
if (config.srg_notch_map == null) {
//Default Map
def mcpName = srgName.replace('-srg', '-dev')
applySpecialSource(srgName, mcpName, getDefaultMap("srg-mcp"))
applySpecialSource(mcpName, notchName, getDefaultMap("mcp-notch"))
} else {
//Custom Map
applySpecialSource(srgName, notchName, config.srg_notch_map)
}
}
void applySpecialSource(String inputName, String outputName, String mapFile) {
def mapping = new JarMapping()
def srgFile = file(mapFile)
def inputFile = file("build/libs/${inputName}")
def outputFile = file("build/libs/${outputName}")
def remapper = new JarRemapper(null, mapping)
def inputJar = net.md_5.specialsource.Jar.init(inputFile)
def inheritanceProviders = new JointProvider()
def jarProvider = new JarProvider(inputJar)
inheritanceProviders.add(jarProvider)
mapping.loadMappings(srgFile)
mapping.setFallbackInheritanceProvider(inheritanceProviders)
remapper.remapJar(inputJar, outputFile)
}
String getDefaultMap(String srgType) {
def mcpVersion = minecraft.mappings.replace('_', "/")
return System.getProperty('user.home') + "/.gradle/caches/minecraft/de/oceanlabs/mcp/mcp_${mcpVersion}/${config.forge_mc_version}/srgs/${srgType}.srg"
}
ext {
reobfSrgToNotch = this.&reobfSrgToNotch
}
-35
View File
@@ -1,35 +0,0 @@
/**
* Gradle Script for Version
* Format Version String
*/
boolean isRelease() {
String s = rootProject.ext.config.snapshot
return s == null || s == "" || s == "0"
}
boolean isSnapshot() {
return !isRelease()
}
String getBuildNum() {
if (System.getenv("CIRCLE_BUILD_NUM") != null)
return System.getenv("CIRCLE_BUILD_NUM")
return "00"
}
//Example: 14.10a-SNAPSHOT-33
String getCSLVersion() {
return rootProject.ext.config.version + rootProject.ext.config.dev_version +
(isRelease() ? '' : ('-SNAPSHOT-' + getBuildNum()))
}
//Example: 14.10a-s33
String getShortVersion() {
return getCSLVersion().replace("SNAPSHOT-", "s")
}
ext {
getCSLVersion = this.&getCSLVersion
getShortVersion = this.&getShortVersion
}
+157
View File
@@ -0,0 +1,157 @@
# Development and Contribution
## Building
1. Run `./gradlew setupDecompWorkspace clean build` command.
1. The built jars are all in `${rootprojectDir}/build/libs` folder.
*NOTICE: The jar file with specific Minecraft version is for the vanilla edition without Forge and Fabric. The json files are launcher profiles which only work when building with our CI server.*
## Running and Testing
For now, CustomSkinLoader is unable to run under self development environment, so it needs to add to another development environment as a library.
There are the available versions in different environments below:
| | Forge | Fabric |
|:-----------------------:|:-----------------------------------------------------------------------------------------------------------------------:|:----------------------------------------------------------------------------------------------------------------------------:|
| Runtime Environment | forge-1.8-11.14.0.1237 ~ 1.13.2-25.0.22<br/> forge-1.13.2-25.0.42 ~ latest | fabric-loader-0.4.3+build.134 ~ latest<br/> Minecraft 18w43b ~ latest<br/> *fabric-api is not required* |
| Development Environment | ForgeGradle-2.1-SNAPSHOT ~ latest<br/> forge-1.8-11.14.3.1503 ~ 1.12.2-14.23.5.2860<br/> forge-1.13.2-25.0.198 ~ latest | fabric-loom-(?) ~ latest<br/> fabric-loader-0.12.0 ~ latest<br/> Minecraft 18w49a ~ latest<br/> *fabric-api is not required* |
### Preliminary steps for testing local builds
1. Create a new empty minecraft development environment.
1. Add below contents to `build.gradle`:
```gradle
repositories {
maven {
url = "file:/${projectDir}/local-repo"
}
}
```
1. Create these folders in the new project directory, then copy the built jar and source jar into it:
```
Forge 1.8 ~ 1.16.5: ./local-repo/mods/CustomSkinLoader_ForgeV1/${version}
Forge 1.17.1 ~ 1.20.4 / NeoForge 1.20.1: ./local-repo/mods/CustomSkinLoader_ForgeV2/${version}
Forge 1.20.6 ~ latest / NeoForge 1.20.2 ~ latest: ./local-repo/mods/CustomSkinLoader_ForgeV3/${version}
Fabric: ./local-repo/mods/CustomSkinLoader_Fabric/${version}
```
*`${version}` should be repalced with something like `15.0-SNAPSHOT-00` manually*
1. Create a pom file in the same folder:
- Forge 1.8 ~ 1.16.5: `CustomSkinLoader_ForgeV1-${version}.pom`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>mods</groupId>
<artifactId>CustomSkinLoader_ForgeV1</artifactId>
<!-- `${version}` should be repalced with something like `15.0-SNAPSHOT-00` manually -->
<version>${version}</version>
</project>
```
- Forge 1.17.1 ~ 1.20.4 / NeoForge 1.20.1: `CustomSkinLoader_ForgeV2-${version}.pom`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>mods</groupId>
<artifactId>CustomSkinLoader_ForgeV2</artifactId>
<!-- `${version}` should be repalced with something like `15.0-SNAPSHOT-00` manually -->
<version>${version}</version>
</project>
```
- Forge 1.20.6 ~ latest / NeoForge 1.20.2 ~ latest: `CustomSkinLoader_ForgeV3-${version}.pom`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>mods</groupId>
<artifactId>CustomSkinLoader_ForgeV3</artifactId>
<!-- `${version}` should be repalced with something like `15.0-SNAPSHOT-00` manually -->
<version>${version}</version>
</project>
```
- Fabric: `CustomSkinLoader_Fabric-${version}.pom`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>mods</groupId>
<artifactId>CustomSkinLoader_Fabric</artifactId>
<!-- `${version}` should be repalced with something like `15.0-SNAPSHOT-00` manually -->
<version>${version}</version>
</project>
```
### For ForgeGradle 2.x ( forge-1.8-11.14.3.1503 ~ forge-1.12.2-14.23.5.2847 )
1. Add below contents to `build.gradle`:
```gradle
dependencies {
deobfCompile "mods:CustomSkinLoader_ForgeLegacy:15.0-SNAPSHOT-00"
}
minecraft {
clientRunArgs += ["--tweakClass", "customskinloader.forge.ForgeDevTweaker", "--username", "<Your username>"]
}
```
1. Run `./gradlew setupDecompWorkspace` command.
1. Then you can debug the mod in IDE or through `./gradlew runClient` command.
### For ForgeGradle 3.x ~ latest ( forge-1.12.2-14.23.5.2851 ~ latest )
1. Add below contents to `build.gradle`:
```gradle
dependencies {
implementation fg.deobf("mods:CustomSkinLoader_ForgeLegacy:15.0-SNAPSHOT-00") // Only required for MinecraftForge 1.8 ~ 1.16.5
implementation fg.deobf("mods:CustomSkinLoader_ForgeActive:15.0-SNAPSHOT-00") // Only required for MinecraftForge 1.17.1 ~ latest
}
minecraft {
runs {
client {
args += ["--username", "<Your username>"]
args += ["--tweakClass", "customskinloader.forge.ForgeDevTweaker"] // Only required for MinecraftForge 1.12.2
}
}
}
```
1. Setup the development environment and run the game as usual.
### For fabric-loom ( fabric-loader-0.12.0 ~ latest )
1. Add below contents to `build.gradle`:
```gradle
dependencies {
modImplementation "mods:CustomSkinLoader_Fabric:15.0-SNAPSHOT-00"
}
loom.runs.client.programArgs "--username", "<Your username>"
```
1. Setup the development environment and run the game as usual.
## Depend on release builds
1. Check the latest version in https://littlesk.in/csl-latest .
1. Add below contents to `build.gradle`:
```gradle
// Before Gradle 5.x
repositories {
ivy {
url = "https://csl.littleservice.cn/"
layout "pattern", {
artifact "[organisation]/[artifact]-[revision](-[classifier])(.[ext])"
}
}
}
// After Gradle 6.x
repositories {
ivy {
url = "https://csl.littleservice.cn/"
metadataSources {
artifact()
}
patternLayout {
artifact "[organisation]/[artifact]-[revision](-[classifier])(.[ext])"
}
}
}
```
1. Follow the same steps in **Running and Testing**.
## Developing
- CustomSkinLoader is based on forge-1.12.2-14.23.5.2768 currently, including Fabric edition. We use custom reobfuscation mappings such as [Fabric.tsrg](Fabric/Fabric.tsrg) and [mixin.tsrg](Fabric/mixin.tsrg) to generate different editions jar and Mixin reference jsons.
- Do not add other required mods.
File renamed without changes.
+5
View File
@@ -0,0 +1,5 @@
// This subproject is only to provide dependency for other subprojects.
dependencies {
implementation project(':Dummy')
}
+5
View File
@@ -0,0 +1,5 @@
forge_mc_version=1.12.2
forge_version=14.23.5.2768
mappings_version=stable_39
# this subproject is only to provide dependency for other subprojects.
is_real_project=false
@@ -1,192 +0,0 @@
package customskinloader;
import java.io.File;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import customskinloader.config.Config;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.*;
import customskinloader.profile.DynamicSkullManager;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.ProfileCache;
import customskinloader.profile.UserProfile;
import customskinloader.utils.MinecraftUtil;
/**
* Custom skin loader mod for Minecraft.
* @author (C) Jeremy Lam [JLChnToZ] 2013-2014 & Alexander Xia [xfl03] 2014-2020
* @version @MOD_FULL_VERSION@
*/
public class CustomSkinLoader {
public static final String CustomSkinLoader_VERSION="@MOD_VERSION@";
public static final String CustomSkinLoader_FULL_VERSION="@MOD_FULL_VERSION@";
public static final File DATA_DIR=new File(MinecraftUtil.getMinecraftDataDir(),"CustomSkinLoader"),
LOG_FILE=new File(DATA_DIR,"CustomSkinLoader.log"),
CONFIG_FILE=new File(DATA_DIR,"CustomSkinLoader.json");
public static final SkinSiteProfile[] DEFAULT_LOAD_LIST={
SkinSiteProfile.createMojangAPI("Mojang"),
SkinSiteProfile.createCustomSkinAPI("LittleSkin","https://littlesk.in/csl/"),
SkinSiteProfile.createCustomSkinAPI("BlessingSkin","http://skin.prinzeugen.net/"),
//OneSkin has been removed temporarily
//SkinSiteProfile.createCustomSkinAPI("OneSkin","http://fleey.cn/skin/skin_user/skin_json.php/"),
//Minecrack could not load skin correctly
//SkinSiteProfile.creatLegacy("Minecrack","http://minecrack.fr.nf/mc/skinsminecrackd/{USERNAME}.png","http://minecrack.fr.nf/mc/cloaksminecrackd/{USERNAME}.png",null),
SkinSiteProfile.createElyByAPI("ElyBy"),
SkinSiteProfile.createUniSkinAPI("SkinMe","http://www.skinme.cc/uniskin/"),
SkinSiteProfile.createLegacy("LocalSkin","LocalSkin/skins/{USERNAME}.png","LocalSkin/capes/{USERNAME}.png","LocalSkin/elytras/{USERNAME}.png"),
SkinSiteProfile.createGlitchlessAPI("GlitchlessGames","https://games.glitchless.ru/api/minecraft/users/profiles/textures/?nickname=")};
public static final Gson GSON=new GsonBuilder().setPrettyPrinting().create();
public static final Logger logger=initLogger();
public static final Config config=Config.loadConfig0();
private static final ProfileCache profileCache=new ProfileCache();
private static final DynamicSkullManager dynamicSkullManager=new DynamicSkullManager();
private static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(config.threadPoolSize, config.threadPoolSize, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>());
//For User Skin
public static Map<Type, MinecraftProfileTexture> loadProfile(GameProfile gameProfile){
String username=gameProfile.getName();
String credential=MinecraftUtil.getCredential(gameProfile);
//Fix: http://hopper.minecraft.net/crashes/minecraft/MCX-2773713
if(username==null){
logger.warning("Could not load profile: username is null.");
return Maps.newHashMap();
}
String tempName=Thread.currentThread().getName();
Thread.currentThread().setName(username);//Change Thread Name
UserProfile profile;
if(profileCache.isReady(credential)){
logger.info("Cached profile will be used.");
profile=profileCache.getProfile(credential);
if(profile==null){
logger.warning("(!Cached Profile is empty!) Expiry:"+profileCache.getExpiry(credential));
if(profileCache.isExpired(credential))//force load
profile=loadProfile0(gameProfile);
}
else
logger.info(profile.toString(profileCache.getExpiry(credential)));
}else{
profileCache.setLoading(credential, true);
profile=loadProfile0(gameProfile);
}
Thread.currentThread().setName(tempName);
return ModelManager0.fromUserProfile(profile);
}
//Core
public static UserProfile loadProfile0(GameProfile gameProfile){
String username=gameProfile.getName();
String credential=MinecraftUtil.getCredential(gameProfile);
profileCache.setLoading(credential, true);
logger.info("Loading "+username+"'s profile.");
if(config.loadlist==null||config.loadlist.isEmpty()){
logger.info("LoadList is Empty.");
return null;
}
UserProfile profile0=new UserProfile();
for(int i=0;i<config.loadlist.size();i++){
SkinSiteProfile ssp=config.loadlist.get(i);
logger.info((i+1)+"/"+config.loadlist.size()+" Try to load profile from '"+ssp.name+"'.");
ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if(loader==null){
logger.info("Type '"+ssp.type+"' is not defined.");
continue;
}
UserProfile profile=null;
try{
profile=loader.loadProfile(ssp, gameProfile);
}catch(Exception e){
logger.warning("Exception occurs while loading.");
logger.warning(e);
if(e.getCause()!=null) {
logger.warning("Caused By:");
logger.warning(e.getCause());
}
}
if(profile==null)
continue;
if(!config.forceLoadAllTextures){
profile0=profile;
break;
}
profile0.mix(profile);
if(profile0.isFull())
break;
}
if(!profile0.isEmpty()){
logger.info(username+"'s profile loaded.");
if(!config.enableCape)
profile0.capeUrl = null;
profileCache.updateCache(credential, profile0);
profileCache.setLoading(credential, false);
logger.info(profile0.toString(profileCache.getExpiry(credential)));
return profile0;
}
logger.info(username+"'s profile not found in load list.");
if(config.enableLocalProfileCache){
UserProfile profile=profileCache.getLocalProfile(credential);
if(profile==null)
logger.info(username+"'s LocalProfile not found.");
else{
profileCache.updateCache(credential, profile, false);
profileCache.setLoading(credential, false);
logger.info(username+"'s LocalProfile will be used.");
logger.info(profile.toString(profileCache.getExpiry(credential)));
return profile;
}
}
profileCache.setLoading(credential, false);
return null;
}
//For Skull
public static Map<Type, MinecraftProfileTexture> loadProfileFromCache(final GameProfile gameProfile) {
String username=gameProfile.getName();
String credential=MinecraftUtil.getCredential(gameProfile);
if(username == null || credential == null)
return dynamicSkullManager.getTexture(gameProfile);
if(config.enableUpdateSkull?profileCache.isReady(credential):profileCache.isExist(credential)){
UserProfile profile=profileCache.getProfile(credential);
return ModelManager0.fromUserProfile(profile);
}
if (!profileCache.isLoading(credential)) {
profileCache.setLoading(credential, true);
Runnable loadThread = () -> {
String tempName = Thread.currentThread().getName();
Thread.currentThread().setName(username + "'s skull");
loadProfile0(gameProfile);//Load in thread
Thread.currentThread().setName(tempName);
};
if (config.enableUpdateSkull) {
new Thread(loadThread).start();
} else {
threadPool.execute(loadThread);
}
}
return Maps.newHashMap();
}
private static Logger initLogger() {
Logger logger=new Logger(LOG_FILE);
logger.info("CustomSkinLoader "+CustomSkinLoader_FULL_VERSION);
logger.info("DataDir: "+DATA_DIR.getAbsolutePath());
logger.info("Minecraft: "+MinecraftUtil.getMinecraftMainVersion()+"("+MinecraftUtil.getMinecraftVersionText()+")");
return logger;
}
}
-106
View File
@@ -1,106 +0,0 @@
package customskinloader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
@SuppressWarnings("ResultOfMethodCallIgnored")
public class Logger {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public enum Level{
DEBUG("DEBUG",false),
INFO("INFO",true),
WARNING("WARNING",true);
String name;
boolean display;
Level(String name,boolean display){
this.name=name;
this.display=display;
}
public String getName(){
return name;
}
public boolean display(){
return display;
}
}
private BufferedWriter writer=null;
public Logger(){
//Logger isn't created.
}
public Logger(String logFile) {
this(new File(logFile));
}
public Logger(File logFile){
try {
if(!logFile.getParentFile().exists()){
logFile.getParentFile().mkdirs();
}
if(!logFile.exists())
logFile.createNewFile();
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logFile), "UTF-8"));
System.out.println("Log Path: " + logFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
public void close(){
if(writer!=null){
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void log(Level level,String msg){
if(!level.display()&&writer==null)
return;
String sb = String.format("[%s %s] %s", Thread.currentThread().getName(), level.getName(), msg);
if(level.display())
System.out.println(sb);
if(writer==null)
return;
try {
String sb2 = String.format("[%s] %s\r\n", DATE_FORMAT.format(new Date()), sb);
writer.write(sb2);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public void debug(String msg){
log(Level.DEBUG,msg);
}
public void debug(String format, Object... objs) {
debug(String.format(format, objs));
}
public void info(String msg){
log(Level.INFO,msg);
}
public void info(String format, Object... objs){
info(String.format(format, objs));
}
public void warning(String msg){
log(Level.WARNING,msg);
}
public void warning(String format, Object... objs){
warning(String.format(format, objs));
}
public void warning(Throwable e){
log(Level.WARNING,"Exception: "+e.toString());
StackTraceElement[] stes=e.getStackTrace();
for(StackTraceElement ste : stes){
log(Level.WARNING,ste.toString());
}
}
}
@@ -1,194 +0,0 @@
package customskinloader.config;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import customskinloader.utils.Version;
import org.apache.commons.io.FileUtils;
import customskinloader.CustomSkinLoader;
import customskinloader.loader.ProfileLoader;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpUtil0;
@SuppressWarnings("ResultOfMethodCallIgnored")
public class Config {
//Program
public String version;
public List<SkinSiteProfile> loadlist;
//Function
public boolean enableDynamicSkull=true;
public boolean enableTransparentSkin=true;
public boolean ignoreHttpsCertificate=false;
public boolean forceLoadAllTextures=false;
public boolean enableCape = true;
public int threadPoolSize = 1;
//Cache
public int cacheExpiry=30;
public boolean enableUpdateSkull=false;
public boolean enableLocalProfileCache=false;
public boolean enableCacheAutoClean=false;
//Init config
public Config(SkinSiteProfile[] loadlist){
this.version=CustomSkinLoader.CustomSkinLoader_VERSION;
this.loadlist=Arrays.asList(loadlist);
}
public static Config loadConfig0() {
Config config=loadConfig();
//LoadList null checker
if(config.loadlist==null){
config.loadlist=new ArrayList<SkinSiteProfile>();
}else{
for(int i=0;i<config.loadlist.size();i++){
if(config.loadlist.get(i)==null)
config.loadlist.remove(i--);
}
}
//Init program
config.loadExtraList();
config.initLocalFolder();
config.threadPoolSize = Math.max(config.threadPoolSize, 1);
if(config.ignoreHttpsCertificate)
HttpUtil0.ignoreHttpsCertificate();
if(config.enableCacheAutoClean && !config.enableLocalProfileCache){
try{
FileUtils.deleteDirectory(HttpRequestUtil.CACHE_DIR);
FileUtils.deleteDirectory(HttpTextureUtil.getCacheDir());
CustomSkinLoader.logger.info("Successfully cleaned cache.");
}catch(Exception e){
CustomSkinLoader.logger.warning("Exception occurs while cleaning cache: "+e.toString());
}
}
//Check config version
Version configVersion = Version.of(config.version);
if (configVersion.compareTo(CustomSkinLoader.CustomSkinLoader_VERSION) < 0) {
CustomSkinLoader.logger.info("Config File is out of date: " + config.version);
config.version = CustomSkinLoader.CustomSkinLoader_VERSION;
//Update some config
if (configVersion.compareTo("14.10") < 0)//Lower than 14.10
config.enableCape = true;
writeConfig(config, true);
}
//Output config
for (Field field : config.getClass().getDeclaredFields()) {
try {
Object value = field.get(config);
if (value instanceof String || value instanceof Integer || value instanceof Boolean)
CustomSkinLoader.logger.info(field.getName() + " : " + value);
} catch (Exception ignored) { }
}
CustomSkinLoader.logger.info("loadList : " + (config.loadlist == null ? 0 : config.loadlist.size()));
return config;
}
private static Config loadConfig() {
CustomSkinLoader.logger.info("Config File: "+CustomSkinLoader.CONFIG_FILE.getAbsolutePath());
if(!CustomSkinLoader.CONFIG_FILE.exists()){
CustomSkinLoader.logger.info("Config file not found, use default instead.");
return initConfig();
}
try {
CustomSkinLoader.logger.info("Try to load config.");
String json=FileUtils.readFileToString(CustomSkinLoader.CONFIG_FILE, "UTF-8");
Config config=CustomSkinLoader.GSON.fromJson(json, Config.class);
CustomSkinLoader.logger.info("Successfully load config.");
return config;
}catch (Exception e) {
CustomSkinLoader.logger.info("Failed to load config, use default instead.("+e.toString()+")");
File brokenFile=new File(CustomSkinLoader.DATA_DIR,"BROKEN-CustomSkinLoader.json");
if(brokenFile.exists())
brokenFile.delete();
CustomSkinLoader.CONFIG_FILE.renameTo(brokenFile);
return initConfig();
}
}
private void loadExtraList(){
File listAddition=new File(CustomSkinLoader.DATA_DIR,"ExtraList");
if(!listAddition.isDirectory()){
listAddition.mkdirs();
return;
}
List<SkinSiteProfile> adds=new ArrayList<SkinSiteProfile>();
File[] files=listAddition.listFiles();
for(File file: files != null ? files : new File[0]){
if(!file.getName().toLowerCase().endsWith(".json")&&!file.getName().toLowerCase().endsWith(".txt"))
continue;
try {
CustomSkinLoader.logger.info("Try to load Extra List.("+file.getName()+")");
String json=FileUtils.readFileToString(file, "UTF-8");
SkinSiteProfile ssp=CustomSkinLoader.GSON.fromJson(json, SkinSiteProfile.class);
CustomSkinLoader.logger.info("Successfully load Extra List.");
file.delete();
ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if(loader==null){
CustomSkinLoader.logger.info("Extra List will be ignore: Type '"+ssp.type+"' is not defined.");
continue;
}
boolean duplicate=false;
for(SkinSiteProfile ssp0:this.loadlist){
if(!ssp0.type.equalsIgnoreCase(ssp.type))
continue;
if(loader.compare(ssp0, ssp)){
duplicate=true;
break;
}
}
if(!duplicate){
adds.add(ssp);
CustomSkinLoader.logger.info("Successfully apply Extra List.("+ssp.name+")");
}else{
CustomSkinLoader.logger.info("Extra List will be ignore: Duplicate.("+ssp.name+")");
}
}catch (Exception e) {
CustomSkinLoader.logger.info("Failed to load Extra List.("+e.toString()+")");
}
}
if(adds.size()!=0){
adds.addAll(this.loadlist);
this.loadlist=adds;
writeConfig(this,true);
}
}
private void initLocalFolder(){
for(SkinSiteProfile ssp:this.loadlist){
ProfileLoader.IProfileLoader loader=ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if(loader==null)
continue;
loader.init(ssp);
}
}
private static Config initConfig() {
Config config=new Config(CustomSkinLoader.DEFAULT_LOAD_LIST);
writeConfig(config,false);
return config;
}
private static void writeConfig(Config config,boolean update){
String json=CustomSkinLoader.GSON.toJson(config);
if(CustomSkinLoader.CONFIG_FILE.exists())
CustomSkinLoader.CONFIG_FILE.delete();
try {
CustomSkinLoader.CONFIG_FILE.createNewFile();
FileUtils.write(CustomSkinLoader.CONFIG_FILE, json, "UTF-8");
CustomSkinLoader.logger.info("Successfully "+(update?"update":"create")+" config.");
} catch (Exception e) {
CustomSkinLoader.logger.info("Failed to "+(update?"update":"create")+" config.("+e.toString()+")");
}
}
}
@@ -1,80 +0,0 @@
package customskinloader.config;
public class SkinSiteProfile {
//Common
public String name;
public String type;
public String userAgent;
//Mojang API
public String apiRoot;
public String sessionRoot;
//Json API
public String root;
//Legacy
public Boolean checkPNG;//Not suitable for local skin
public String skin;
public String model;
public String cape;
public String elytra;
public static SkinSiteProfile createMojangAPI(String name) {
SkinSiteProfile ssp = new SkinSiteProfile();
ssp.name = name;
ssp.type = "MojangAPI";
return ssp;
}
public static SkinSiteProfile createCustomSkinAPI(String name, String root) {
SkinSiteProfile ssp = new SkinSiteProfile();
ssp.name = name;
ssp.type = "CustomSkinAPI";
ssp.root = root;
return ssp;
}
public static SkinSiteProfile creatCustomSkinAPIPlus(String name, String root) {
SkinSiteProfile ssp = new SkinSiteProfile();
ssp.name = name;
ssp.type = "CustomSkinAPIPlus";
ssp.root = root;
return ssp;
}
public static SkinSiteProfile createGlitchlessAPI(String name, String root) {
SkinSiteProfile ssp = new SkinSiteProfile();
ssp.name = name;
ssp.type = "GlitchlessAPI";
ssp.root = root;
return ssp;
}
public static SkinSiteProfile createUniSkinAPI(String name, String root) {
SkinSiteProfile ssp = new SkinSiteProfile();
ssp.name = name;
ssp.type = "UniSkinAPI";
ssp.root = root;
return ssp;
}
public static SkinSiteProfile createLegacy(String name, String skin, String cape, String elytra) {
SkinSiteProfile ssp = new SkinSiteProfile();
ssp.name = name;
ssp.type = "Legacy";
ssp.checkPNG = false;
ssp.skin = skin;
ssp.model = "auto";
ssp.cape = cape;
ssp.elytra = elytra;
return ssp;
}
public static SkinSiteProfile createElyByAPI(String name) {
SkinSiteProfile ssp = new SkinSiteProfile();
ssp.name = name;
ssp.type = "ElyByAPI";
return ssp;
}
}
@@ -1,132 +0,0 @@
package customskinloader.fake;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import customskinloader.CustomSkinLoader;
import customskinloader.fake.itf.IFakeMinecraft;
import customskinloader.fake.itf.IFakeTextureManager_1;
import customskinloader.fake.itf.IFakeTextureManager_2;
import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpTextureUtil.HttpTextureInfo;
import customskinloader.utils.MinecraftUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.Texture;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.client.resources.SkinManager.SkinAvailableCallback;
import net.minecraft.util.ResourceLocation;
public class FakeSkinManager {
private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(CustomSkinLoader.config.threadPoolSize, CustomSkinLoader.config.threadPoolSize, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>());
private final TextureManager textureManager;
private final Map<ResourceLocation, MinecraftProfileTexture> modelCache = new HashMap<>();
public FakeSkinManager(TextureManager textureManagerInstance, File skinCacheDirectory, MinecraftSessionService sessionService) {
this.textureManager = textureManagerInstance;
HttpTextureUtil.defaultCacheDir = skinCacheDirectory;
}
public ResourceLocation loadSkin(MinecraftProfileTexture profileTexture, Type textureType) {
return this.loadSkin(profileTexture, textureType, null);
}
public ResourceLocation loadSkin(final MinecraftProfileTexture profileTexture, final Type textureType, final SkinAvailableCallback skinAvailableCallback) {
HttpTextureInfo info = HttpTextureUtil.toHttpTextureInfo(profileTexture.getUrl());
final ResourceLocation resourcelocation = new ResourceLocation("skins/" + info.hash);
if (((IFakeTextureManager_1) this.textureManager).func_229267_b_(resourcelocation) != null) {//Have already loaded
makeCallback(skinAvailableCallback, textureType, resourcelocation, modelCache.getOrDefault(resourcelocation, profileTexture));
} else {
SimpleTexture threaddownloadimagedata = MinecraftUtil.createThreadDownloadImageData(info.cacheFile, info.url, DefaultPlayerSkin.getDefaultSkinLegacy(), new BaseBuffer(skinAvailableCallback, textureType, resourcelocation, profileTexture), textureType);
if (skinAvailableCallback instanceof FakeClientPlayer.LegacyBuffer)//Cache for client player
FakeClientPlayer.textureCache.put(resourcelocation, threaddownloadimagedata);
((IFakeTextureManager_2) this.textureManager).func_229263_a_(resourcelocation, (Texture) threaddownloadimagedata);
}
return resourcelocation;
}
public void loadProfileTextures(final GameProfile profile, final SkinAvailableCallback skinAvailableCallback, final boolean requireSecure) {
THREAD_POOL.execute(new Runnable() {
public void run() {
final Map<Type, MinecraftProfileTexture> map = Maps.newHashMap();
map.putAll(customskinloader.CustomSkinLoader.loadProfile(profile));
((IFakeMinecraft) Minecraft.getMinecraft()).execute(() -> {
for (Type type : Type.values()) {
if (map.containsKey(type)) {
CustomSkinLoader.logger.debug("Loading type:" + type);
FakeSkinManager.this.loadSkin(map.get(type), type, skinAvailableCallback);
}
}
});
}
});
}
public Map<Type, MinecraftProfileTexture> loadSkinFromCache(GameProfile profile) {
return CustomSkinLoader.loadProfileFromCache(profile);
}
private static void makeCallback(SkinAvailableCallback callback, Type type, ResourceLocation location, MinecraftProfileTexture texture) {
if (callback != null)
callback.skinAvailable(type, location, texture);
}
private class BaseBuffer implements IImageBuffer {
private IImageBuffer buffer;
private SkinAvailableCallback callback;
private Type type;
private ResourceLocation location;
private MinecraftProfileTexture texture;
public BaseBuffer(SkinAvailableCallback callback, Type type, ResourceLocation location, MinecraftProfileTexture texture) {
this.buffer = (type == Type.SKIN ? new FakeSkinBuffer() : null);
this.callback = callback;
this.type = type;
this.location = location;
this.texture = texture;
}
public net.minecraft.client.renderer.texture.NativeImage func_195786_a(net.minecraft.client.renderer.texture.NativeImage image) {
return buffer instanceof FakeSkinBuffer ? ((FakeSkinBuffer) buffer).func_195786_a(image) : image;
}
public BufferedImage parseUserSkin(BufferedImage image) {
return buffer == null ? image : buffer.parseUserSkin(image);
}
public void skinAvailable() {
if (buffer != null) {
buffer.skinAvailable();
if ("auto".equals(texture.getMetadata("model")) && buffer instanceof FakeSkinBuffer) {
//Auto judge skin type
Map<String, String> metadata = Maps.newHashMap();
String type = ((FakeSkinBuffer) buffer).judgeType();
metadata.put("model", type);
texture = new MinecraftProfileTexture(texture.getUrl(), metadata);
FakeSkinManager.this.modelCache.put(location, texture);
}
}
FakeSkinManager.makeCallback(callback, type, location, texture);
}
}
}
@@ -1,9 +0,0 @@
package customskinloader.fake.itf;
import net.minecraft.client.Minecraft;
public interface IFakeMinecraft {
default void execute(Runnable runnable) {
((Minecraft) this).addScheduledTask(runnable);
}
}
@@ -1,16 +0,0 @@
package customskinloader.fake.itf;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.Texture;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
public interface IFakeTextureManager_1 {
default boolean func_229263_a_(ResourceLocation textureLocation, Texture textureObj) {
return ((TextureManager) this).loadTexture(textureLocation, (ITextureObject) textureObj);
}
default Texture func_229267_b_(ResourceLocation textureLocation) {
return (Texture) ((TextureManager) this).getTexture(textureLocation);
}
}
@@ -1,10 +0,0 @@
package customskinloader.fake.itf;
import net.minecraft.client.renderer.texture.Texture;
import net.minecraft.util.ResourceLocation;
public interface IFakeTextureManager_2 {
default void func_229263_a_(ResourceLocation textureLocation, Texture textureObj) {
((IFakeTextureManager_1) this).func_229263_a_(textureLocation, textureObj);
}
}
@@ -1,106 +0,0 @@
package customskinloader.loader;
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import com.mojang.authlib.GameProfile;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.jsonapi.*;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpUtil0;
import customskinloader.utils.HttpRequestUtil.HttpRequest;
import customskinloader.utils.HttpRequestUtil.HttpResponce;
public class JsonAPILoader implements ProfileLoader.IProfileLoader {
public interface IJsonAPI {
String toJsonUrl(String root, String username);
String getPayload(SkinSiteProfile ssp);
UserProfile toUserProfile(String root, String json, boolean local);
String getName();
}
public static class ErrorProfile{
public int errno;
public String msg;
}
public enum Type{
CustomSkinAPI(new CustomSkinAPI()),
CustomSkinAPIPlus(new CustomSkinAPIPlus()),
UniSkinAPI(new UniSkinAPI()),
ElyByAPI(new ElyByAPI()),
GlitchlessAPI(new GlitchlessAPI());
public IJsonAPI jsonAPI;
Type(IJsonAPI jsonAPI){
this.jsonAPI=jsonAPI;
}
}
private Type type;
public JsonAPILoader(Type type){
this.type=type;
}
@Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception {
String username=gameProfile.getName();
if(StringUtils.isEmpty(ssp.root) && type!=Type.ElyByAPI){
CustomSkinLoader.logger.info("Root not defined.");
return null;
}
boolean local = HttpUtil0.isLocal(ssp.root);
String jsonUrl=type.jsonAPI.toJsonUrl(ssp.root, username);
String json;
if(local){
File jsonFile = new File(CustomSkinLoader.DATA_DIR, jsonUrl);
if(!jsonFile.exists()){
CustomSkinLoader.logger.info("Profile File not found.");
return null;
}
json=IOUtils.toString(new FileInputStream(jsonFile), "UTF-8");
}else{
HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(jsonUrl).setCacheTime(90).setUserAgent(ssp.userAgent).setPayload(type.jsonAPI.getPayload(ssp)));
json=responce.content;
}
if(json==null||json.equals("")){
CustomSkinLoader.logger.info("Profile not found.");
return null;
}
ErrorProfile profile=CustomSkinLoader.GSON.fromJson(json, ErrorProfile.class);
if(profile.errno!=0){
CustomSkinLoader.logger.info("Error "+profile.errno+": "+profile.msg);
return null;
}
UserProfile p=type.jsonAPI.toUserProfile(ssp.root, json, local);
if(p==null||p.isEmpty()){
CustomSkinLoader.logger.info("Both skin and cape not found.");
return null;
}else{
return p;
}
}
@Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return !StringUtils.isNoneEmpty(ssp0.root) || ssp0.root.equalsIgnoreCase(ssp1.root);
}
@Override
public String getName() {
return type.jsonAPI.getName();
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public void init(SkinSiteProfile ssp) {
if(HttpUtil0.isLocal(ssp.root)){
File f=new File(ssp.root);
if(!f.exists())
f.mkdirs();
}
}
}
@@ -1,118 +0,0 @@
package customskinloader.loader;
import java.io.File;
import com.mojang.util.UUIDTypeAdapter;
import org.apache.commons.lang3.StringUtils;
import com.mojang.authlib.GameProfile;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpRequestUtil.HttpRequest;
import customskinloader.utils.HttpRequestUtil.HttpResponce;
import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpUtil0;
import javax.annotation.Nonnull;
public class LegacyLoader implements ProfileLoader.IProfileLoader {
public static final String USERNAME_PLACEHOLDER = "{USERNAME}";
public static final String UUID_PLACEHOLDER = "{UUID}";
@Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception {
String username = gameProfile.getName();
UserProfile profile = new UserProfile();
if (StringUtils.isNoneEmpty(ssp.skin)) {
String skin = expandURL(ssp.skin, username);
if (HttpUtil0.isLocal(ssp.skin)) {
File skinFile = new File(CustomSkinLoader.DATA_DIR, skin);
if (skinFile.exists() && skinFile.isFile())
profile.skinUrl = HttpTextureUtil.getLocalLegacyFakeUrl(skin, HttpTextureUtil.getHash(skin, skinFile.length(), skinFile.lastModified()));
} else {
HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequest(skin).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG != null && ssp.checkPNG).setLoadContent(false).setCacheTime(90));
if (responce.success)
profile.skinUrl = HttpTextureUtil.getLegacyFakeUrl(skin);
}
profile.model = profile.hasSkinUrl() ? ssp.model : null;
}
if (StringUtils.isNoneEmpty(ssp.cape)) {
String cape = expandURL(ssp.cape, username);
if (HttpUtil0.isLocal(ssp.cape)) {
File capeFile = new File(CustomSkinLoader.DATA_DIR, cape);
if (capeFile.exists() && capeFile.isFile())
profile.capeUrl = HttpTextureUtil.getLocalLegacyFakeUrl(cape, HttpTextureUtil.getHash(cape, capeFile.length(), capeFile.lastModified()));
} else {
HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequest(cape).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG != null && ssp.checkPNG).setLoadContent(false).setCacheTime(90));
if (responce.success)
profile.capeUrl = HttpTextureUtil.getLegacyFakeUrl(cape);
}
}
if (ModelManager0.isElytraSupported() && StringUtils.isNoneEmpty(ssp.elytra)) {
String elytra = expandURL(ssp.elytra, username);
if (HttpUtil0.isLocal(ssp.elytra)) {
File elytraFile = new File(CustomSkinLoader.DATA_DIR, elytra);
if (elytraFile.exists() && elytraFile.isFile())
profile.elytraUrl = HttpTextureUtil.getLocalLegacyFakeUrl(elytra, HttpTextureUtil.getHash(elytra, elytraFile.length(), elytraFile.lastModified()));
} else {
HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequest(elytra).setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG != null && ssp.checkPNG).setLoadContent(false).setCacheTime(90));
if (responce.success)
profile.elytraUrl = HttpTextureUtil.getLegacyFakeUrl(elytra);
}
}
if (profile.isEmpty()) {
CustomSkinLoader.logger.info("Both skin and cape not found.");
return null;
}
return profile;
}
@Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return (!StringUtils.isNoneEmpty(ssp0.skin) || ssp0.skin.equalsIgnoreCase(ssp1.skin)) || (!StringUtils.isNoneEmpty(ssp0.cape) || ssp0.cape.equalsIgnoreCase(ssp1.cape));
}
@Override
public String getName() {
return "Legacy";
}
@Override
public void init(SkinSiteProfile ssp) {
if (HttpUtil0.isLocal(ssp.skin))
initFolder(ssp.skin);
if (HttpUtil0.isLocal(ssp.cape))
initFolder(ssp.cape);
if (HttpUtil0.isLocal(ssp.elytra))
initFolder(ssp.elytra);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void initFolder(String target) {
String file = target.replace(USERNAME_PLACEHOLDER, "init");
File folder = new File(CustomSkinLoader.DATA_DIR, file).getParentFile();
if (folder != null && !folder.exists())
folder.mkdirs();
}
private String expandURL(String url, String username) {
String t = url.replace(USERNAME_PLACEHOLDER, username);
if (t.contains(UUID_PLACEHOLDER))
t = t.replace(UUID_PLACEHOLDER, getMojangUUID(username));
return t;
}
@Nonnull
private String getMojangUUID(String username) {
GameProfile profile = MojangAPILoader.loadGameProfile(MojangAPILoader.getMojangApiRoot(), username);
if (profile == null) {
CustomSkinLoader.logger.info("UUID for %s not found.", username);
return "{ABORT}";
}
return UUIDTypeAdapter.fromUUID(profile.getId());
}
}
@@ -1,139 +0,0 @@
package customskinloader.loader;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import com.google.common.collect.Maps;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Iterables;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse;
import com.mojang.authlib.yggdrasil.response.MinecraftTexturesPayload;
import com.mojang.util.UUIDTypeAdapter;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpRequestUtil.HttpRequest;
import customskinloader.utils.HttpRequestUtil.HttpResponce;
public class MojangAPILoader implements ProfileLoader.IProfileLoader {
@Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception {
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = getTextures(gameProfile);
if (!map.isEmpty()) {
CustomSkinLoader.logger.info("Default profile will be used.");
return ModelManager0.toUserProfile(map);
}
String username = gameProfile.getName();
GameProfile newGameProfile = loadGameProfile(ssp.apiRoot, username);
if (newGameProfile == null) {
CustomSkinLoader.logger.info("Profile not found.(" + username + "'s profile not found.)");
return null;
}
newGameProfile = fillGameProfile(ssp.sessionRoot, newGameProfile);
map = getTextures(newGameProfile);
if (!map.isEmpty()) {
gameProfile.getProperties().putAll(newGameProfile.getProperties());
return ModelManager0.toUserProfile(map);
}
CustomSkinLoader.logger.info("Profile not found.(" + username + " doesn't have skin/cape.)");
return null;
}
//Username -> UUID
public static GameProfile loadGameProfile(String apiRoot, String username) {
//Doc (https://wiki.vg/Mojang_API#Playernames_-.3E_UUIDs)
Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
HttpResponce responce = HttpRequestUtil.makeHttpRequest(
new HttpRequest(apiRoot + "profiles/minecraft")
.setCacheTime(-1).setPayload(gson.toJson(Collections.singletonList(username)))
);
if (StringUtils.isEmpty(responce.content))
return null;
GameProfile[] profiles = gson.fromJson(responce.content, GameProfile[].class);
if (profiles.length == 0) return null;
GameProfile gameProfile = profiles[0];
if (gameProfile.getId() == null)
return null;
return new GameProfile(gameProfile.getId(), gameProfile.getName());
}
//UUID -> Profile
public static GameProfile fillGameProfile(String sessionRoot, GameProfile profile) {
//Doc (http://wiki.vg/Mojang_API#UUID_-.3E_Profile_.2B_Skin.2FCape)
HttpResponce responce = HttpRequestUtil.makeHttpRequest(
new HttpRequest(sessionRoot + "session/minecraft/profile/"
+ UUIDTypeAdapter.fromUUID(profile.getId())).setCacheTime(90));
if (StringUtils.isEmpty(responce.content))
return profile;
Gson gson = new GsonBuilder()
.registerTypeAdapter(UUID.class, new UUIDTypeAdapter())
.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer())
.create();
MinecraftProfilePropertiesResponse propertiesResponce = gson.fromJson(responce.content, MinecraftProfilePropertiesResponse.class);
GameProfile newGameProfile = new GameProfile(propertiesResponce.getId(), propertiesResponce.getName());
newGameProfile.getProperties().putAll(propertiesResponce.getProperties());
return newGameProfile;
}
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getTextures(GameProfile gameProfile) {
if (gameProfile == null)
return Maps.newHashMap();
Property textureProperty = Iterables.getFirst(gameProfile.getProperties().get("textures"), null);
if (textureProperty == null)
return Maps.newHashMap();
String value = textureProperty.getValue();
if (StringUtils.isBlank(value))
return Maps.newHashMap();
@SuppressWarnings("deprecation") String json = new String(Base64.decodeBase64(value), Charsets.UTF_8);
Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
MinecraftTexturesPayload result = gson.fromJson(json, MinecraftTexturesPayload.class);
if (result == null || result.getTextures() == null)
return Maps.newHashMap();
return result.getTextures();
}
@Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return true;
}
@Override
public String getName() {
return "MojangAPI";
}
@Override
public void init(SkinSiteProfile ssp) {
//Init default api & session root for Mojang API
if (ssp.apiRoot == null)
ssp.apiRoot = "https://api.mojang.com/";
if (ssp.sessionRoot == null)
ssp.sessionRoot = "https://sessionserver.mojang.com/";
}
private static final String MOJANG_API_ROOT = "https://api{DO_NOT_MODIFY}.mojang.com/";
public static String getMojangApiRoot() {
return MOJANG_API_ROOT.replace("{DO_NOT_MODIFY}", "");
}
}
@@ -1,38 +0,0 @@
package customskinloader.loader;
import java.util.HashMap;
import com.mojang.authlib.GameProfile;
import customskinloader.config.SkinSiteProfile;
import customskinloader.plugin.PluginLoader;
import customskinloader.profile.UserProfile;
public class ProfileLoader {
private static final IProfileLoader[] DEFAULT_LOADERS={
new MojangAPILoader(),
new JsonAPILoader(JsonAPILoader.Type.CustomSkinAPI),
new JsonAPILoader(JsonAPILoader.Type.CustomSkinAPIPlus),
new JsonAPILoader(JsonAPILoader.Type.UniSkinAPI),
new JsonAPILoader(JsonAPILoader.Type.ElyByAPI),
new JsonAPILoader(JsonAPILoader.Type.GlitchlessAPI),
new LegacyLoader()};
public static final HashMap<String,IProfileLoader> LOADERS=initLoaders();
private static HashMap<String, IProfileLoader> initLoaders() {
HashMap<String, IProfileLoader> loaders=new HashMap<String, IProfileLoader>();
for(IProfileLoader loader:DEFAULT_LOADERS){
loaders.put(loader.getName().toLowerCase(), loader);
}
loaders.putAll(PluginLoader.loadPlugins());
return loaders;
}
public interface IProfileLoader {
UserProfile loadProfile(SkinSiteProfile ssp,GameProfile gameProfile) throws Exception;
boolean compare(SkinSiteProfile ssp0,SkinSiteProfile ssp1);
String getName();
void init(SkinSiteProfile ssp);
}
}
@@ -1,90 +0,0 @@
package customskinloader.loader.jsonapi;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader.IJsonAPI;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.ModelManager0.Model;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpTextureUtil;
public class CustomSkinAPI implements IJsonAPI {
private static final String TEXTURES="textures/";
private static final String SUFFIX=".json";
@Override
public String toJsonUrl(String root, String username) {
return root + username + SUFFIX;
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
CustomSkinAPIProfile profile=CustomSkinLoader.GSON.fromJson(json, CustomSkinAPIProfile.class);
UserProfile p=new UserProfile();
if(StringUtils.isNotBlank(profile.skin)){
p.skinUrl=root+TEXTURES+profile.skin;
if(local)
p.skinUrl=HttpTextureUtil.getLocalFakeUrl(p.skinUrl);
}
if(StringUtils.isNotBlank(profile.cape)){
p.capeUrl=root+TEXTURES+profile.cape;
if(local)
p.capeUrl=HttpTextureUtil.getLocalFakeUrl(p.capeUrl);
}
if(StringUtils.isNotBlank(profile.elytra)){
p.elytraUrl=root+TEXTURES+profile.elytra;
if(local)
p.elytraUrl=HttpTextureUtil.getLocalFakeUrl(p.elytraUrl);
}
Map<String,String> textures=new LinkedHashMap<String,String>();
if(profile.skins!=null)
textures.putAll(profile.skins);
if(profile.textures!=null)
textures.putAll(profile.textures);
if(textures.isEmpty())
return p;
boolean hasSkin=false;
for(String model:textures.keySet()){
Model enumModel=ModelManager0.getEnumModel(model);
if(enumModel==null||StringUtils.isEmpty(textures.get(model)))
continue;
if(ModelManager0.isSkin(enumModel))
if(hasSkin)
continue;
else
hasSkin=true;
String url=root+TEXTURES+textures.get(model);
if(local)
url=HttpTextureUtil.getLocalFakeUrl(url);
p.put(enumModel, url);
}
return p;
}
private class CustomSkinAPIProfile{
public String username;
public LinkedHashMap<String,String> textures;
public LinkedHashMap<String,String> skins;
public String skin;
public String cape;
public String elytra;
}
@Override
public String getPayload(SkinSiteProfile ssp) {
return null;
}
@Override
public String getName() {
return "CustomSkinAPI";
}
}
@@ -1,50 +0,0 @@
package customskinloader.loader.jsonapi;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import customskinloader.utils.MinecraftUtil;
import java.net.URI;
import java.util.Map;
public class ElyByAPI implements JsonAPILoader.IJsonAPI {
@Override
public String toJsonUrl(String root, String username) {
return "http://skinsystem.ely.by/textures/" + username + "?version=2&minecraft_version=" + MinecraftUtil.getMinecraftMainVersion();
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
Map<Type, MinecraftProfileTexture> result = new Gson().fromJson(json, new TypeToken<Map<Type, MinecraftProfileTexture>>() {
}.getType());
if (!result.containsKey(Type.SKIN))
return null;
//Check URL
try {
URI uri = new URI(result.get(Type.SKIN).getUrl());
if (!uri.getHost().endsWith("ely.by"))
return null;
} catch (Exception e) {
return null;
}
return ModelManager0.toUserProfile(result);
}
@Override
public String getPayload(SkinSiteProfile ssp) {
return null;
}
@Override
public String getName() {
return "ElyByAPI";
}
}
@@ -1,80 +0,0 @@
package customskinloader.loader.jsonapi;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader.IJsonAPI;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import customskinloader.profile.ModelManager0.Model;
import customskinloader.utils.HttpTextureUtil;
public class UniSkinAPI implements IJsonAPI {
private static final String TEXTURES="textures/";
private static final String SUFFIX=".json";
@Override
public String toJsonUrl(String root, String username) {
return root + username + SUFFIX;
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
UniSkinAPIProfile profile=CustomSkinLoader.GSON.fromJson(json, UniSkinAPIProfile.class);
UserProfile p=new UserProfile();
if(StringUtils.isNotBlank(profile.cape)){
p.capeUrl=root+TEXTURES+profile.cape;
if(local)
p.capeUrl=HttpTextureUtil.getLocalFakeUrl(p.capeUrl);
}
if(profile.skins==null||profile.skins.isEmpty())
return p;
if(profile.model_preference==null||profile.model_preference.isEmpty())
return p;
boolean hasSkin=false;
for(String model:profile.model_preference){
Model enumModel=ModelManager0.getEnumModel(model);
if(enumModel==null||StringUtils.isEmpty(profile.skins.get(model)))
continue;
if(ModelManager0.isSkin(enumModel))
if(hasSkin)
continue;
else
hasSkin=true;
String url=root+TEXTURES+profile.skins.get(model);
if(local)
url=HttpTextureUtil.getLocalFakeUrl(url);
p.put(enumModel, url);
}
return p;
}
/**
* Json profile for UniSkinAPI
* Source Code: https://github.com/RecursiveG/UniSkinMod/blob/master/src/main/java/org/devinprogress/uniskinmod/UniSkinApiProfile.java#L18-L22
* @author RecursiveG
*/
private class UniSkinAPIProfile{
public String player_name;
public long last_update;
public List<String> model_preference;
public Map<String,String> skins;
public String cape;
}
@Override
public String getPayload(SkinSiteProfile ssp) {
return null;
}
@Override
public String getName() {
return "UniSkinAPI";
}
}
@@ -1,7 +0,0 @@
package customskinloader.plugin;
import customskinloader.loader.ProfileLoader;
public interface ICustomSkinLoaderPlugin {
ProfileLoader.IProfileLoader getProfileLoader();
}
@@ -1,39 +0,0 @@
package customskinloader.plugin;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.ServiceLoader;
import org.apache.commons.io.FileUtils;
import customskinloader.CustomSkinLoader;
import customskinloader.loader.ProfileLoader;
public class PluginLoader {
public static HashMap<String, ProfileLoader.IProfileLoader> loadPlugins() {
File pluginsDir = new File(CustomSkinLoader.DATA_DIR, "Plugins");
ArrayList<URL> urls = new ArrayList<URL>();
if (!pluginsDir.isDirectory()) {
pluginsDir.mkdirs();
} else {
for (File plugin : FileUtils.listFiles(pluginsDir, new String[] {"jar", "zip"}, false)) {
try {
urls.add(plugin.toURI().toURL());
CustomSkinLoader.logger.info("Found a jar or zip file: " + plugin.getName());
} catch (MalformedURLException ignored) {}
}
}
ServiceLoader<ICustomSkinLoaderPlugin> sl = ServiceLoader.load(ICustomSkinLoaderPlugin.class, new URLClassLoader(urls.toArray(new URL[0]), PluginLoader.class.getClassLoader()));
HashMap<String, ProfileLoader.IProfileLoader> profileLoaders = new HashMap<String, ProfileLoader.IProfileLoader>();
for (ICustomSkinLoaderPlugin cslPlugin : sl) {
ProfileLoader.IProfileLoader profileLoader = cslPlugin.getProfileLoader();
profileLoaders.put(profileLoader.getName().toLowerCase(), profileLoader);
CustomSkinLoader.logger.info("Add profile loader: " + profileLoader.getName());
}
return profileLoaders;
}
}
@@ -1,160 +0,0 @@
package customskinloader.profile;
import java.io.File;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.Lists;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import com.mojang.authlib.properties.Property;
import com.mojang.util.UUIDTypeAdapter;
import customskinloader.CustomSkinLoader;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpRequestUtil.HttpRequest;
import customskinloader.utils.HttpRequestUtil.HttpResponce;
import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpUtil0;
public class DynamicSkullManager {
public static class SkullTexture{
public Map<Type,MinecraftProfileTexture> textures;
public String index;//Index File
public ArrayList<String> skins;
public int interval;
public boolean fromZero;
//For program
public long startTime;
public int period;
}
private Map<GameProfile, SkullTexture> dynamicTextures = new ConcurrentHashMap<>();
private Map<GameProfile, Map<Type, MinecraftProfileTexture>> staticTextures = new ConcurrentHashMap<>();
private List<GameProfile> loadingList=new ArrayList<GameProfile>();
private void parseGameProfile(GameProfile profile){
Property textureProperty = Iterables.getFirst(profile.getProperties().get("textures"), null);
if (textureProperty==null){
staticTextures.put(profile, Maps.<Type, MinecraftProfileTexture>newHashMap());
return;
}
String value=textureProperty.getValue();
if(StringUtils.isBlank(value)){
staticTextures.put(profile, Maps.<Type, MinecraftProfileTexture>newHashMap());
return;
}
@SuppressWarnings("deprecation") String json = new String(Base64.decodeBase64(value), Charsets.UTF_8);
Gson gson=new GsonBuilder().registerTypeAdapter(UUID.class,new UUIDTypeAdapter()).create();
SkullTexture result=gson.fromJson(json,SkullTexture.class);
if(result==null){
staticTextures.put(profile, Maps.<Type, MinecraftProfileTexture>newHashMap());
return;
}
staticTextures.put(profile, (result.textures==null || !result.textures.containsKey(Type.SKIN)) ?
Maps.<Type, MinecraftProfileTexture>newHashMap() : parseTextures(result.textures));
if(StringUtils.isNotEmpty(result.index)){
File indexFile=new File(CustomSkinLoader.DATA_DIR,result.index);
try{
String index=FileUtils.readFileToString(indexFile, "UTF-8");
if(StringUtils.isNotEmpty(index)){
String[] skins = CustomSkinLoader.GSON.fromJson(index, String[].class);
if(skins != null && skins.length != 0)
result.skins = Lists.newArrayList(skins);
}
}catch(Exception e){
CustomSkinLoader.logger.warning("Exception occurs while parsing index file: "+e.toString());
}
}
if(!CustomSkinLoader.config.enableDynamicSkull||result.skins==null||result.skins.isEmpty())
return;
CustomSkinLoader.logger.info("Try to load Dynamic Skull: "+json);
for(int i=0;i<result.skins.size();i++){//check and cache skins
String skin=result.skins.get(i);
if(HttpUtil0.isLocal(skin)){
//Local Skin
File skinFile=new File(CustomSkinLoader.DATA_DIR,skin);
if(skinFile.isFile()&&skinFile.length()>0){
//Skin found
String fakeUrl=HttpTextureUtil.getLocalFakeUrl(skin);
result.skins.set(i, fakeUrl);
}else{
//Could not find skin
result.skins.remove(i--);
}
}else{
//Online Skin
HttpResponce responce=HttpRequestUtil.makeHttpRequest(new HttpRequest(skin).setCacheFile(HttpTextureUtil.getCacheFile(FilenameUtils.getBaseName(skin))).setCacheTime(0).setLoadContent(false));
if(!responce.success){
//Could not load skin
result.skins.remove(i--);
}
}
}
if(result.skins.isEmpty()){//Nothing loaded
CustomSkinLoader.logger.info("Failed: Nothing loaded.");
return;
}
result.interval=Math.max(result.interval, 50);
if(result.fromZero)
result.startTime=System.currentTimeMillis();
result.period=result.interval*result.skins.size();
CustomSkinLoader.logger.info("Successfully loaded Dynamic Skull: "+new Gson().toJson(result));
dynamicTextures.put(profile, result);
staticTextures.remove(profile);
}
//Support local skin for skull
public Map<Type, MinecraftProfileTexture> parseTextures(Map<Type, MinecraftProfileTexture> textures) {
MinecraftProfileTexture skin=textures.get(Type.SKIN);
String skinUrl=skin.getUrl();
if(!HttpUtil0.isLocal(skinUrl))
return textures;
File skinFile=new File(CustomSkinLoader.DATA_DIR,skinUrl);
if(!skinFile.isFile())
return Maps.newHashMap();
textures.put(Type.SKIN, ModelManager0.getProfileTexture(HttpTextureUtil.getLocalFakeUrl(skinUrl), null));
return textures;
}
public Map<Type,MinecraftProfileTexture> getTexture(final GameProfile profile){
if(staticTextures.get(profile)!=null)
return staticTextures.get(profile);
if(loadingList.contains(profile))
return Maps.newHashMap();
if(dynamicTextures.containsKey(profile)){
SkullTexture texture=dynamicTextures.get(profile);
long time=System.currentTimeMillis()-texture.startTime;
int index=(int)Math.floor((time%texture.period)/texture.interval);
Map<Type,MinecraftProfileTexture> map=Maps.newHashMap();
map.put(Type.SKIN, ModelManager0.getProfileTexture(texture.skins.get(index), null));
return map;
}
loadingList.add(profile);
Thread loadThread=new Thread(){
public void run(){
parseGameProfile(profile);//Load in thread
loadingList.remove(profile);
}
};
loadThread.setName("Skull "+profile.hashCode());
loadThread.start();
return Maps.newHashMap();
}
}
@@ -1,83 +0,0 @@
package customskinloader.utils;
import java.io.File;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import customskinloader.CustomSkinLoader;
public class HttpTextureUtil {
public static class HttpTextureInfo{
public String url="";
public File cacheFile;
public String hash;
}
private static final String
LEGACY_MARK="(LEGACY)",
LOCAL_MARK="(LOCAL)",
LOCAL_LEGACY_MARK="(LOCAL_LEGACY)";
public static File defaultCacheDir;
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void cleanCacheDir(){
if(defaultCacheDir!=null){
defaultCacheDir.delete();
defaultCacheDir.mkdirs();
}
}
public static File getCacheDir(){
return defaultCacheDir==null?new File(MinecraftUtil.getMinecraftDataDir(),"assets/skins"):defaultCacheDir;
}
public static HttpTextureInfo toHttpTextureInfo(String fakeUrl){
HttpTextureInfo info=new HttpTextureInfo();
if(fakeUrl.startsWith("http")){
info.url=fakeUrl;
info.hash=FilenameUtils.getBaseName(fakeUrl);
info.cacheFile=getCacheFile(info.hash);
return info;
}
if(fakeUrl.startsWith(LOCAL_LEGACY_MARK)){
fakeUrl=fakeUrl.replace(LOCAL_LEGACY_MARK, "");
String[] t=fakeUrl.split(",",2);
if(t.length!=2)
return info;
info.cacheFile=new File(CustomSkinLoader.DATA_DIR,t[1]);
info.hash=t[0];
return info;
}
if(fakeUrl.startsWith(LOCAL_MARK)){
fakeUrl=fakeUrl.replace(LOCAL_MARK, "");
info.cacheFile=new File(CustomSkinLoader.DATA_DIR,fakeUrl);
info.hash=FilenameUtils.getBaseName(fakeUrl);
return info;
}
if(fakeUrl.startsWith(LEGACY_MARK)){
fakeUrl=fakeUrl.replace(LEGACY_MARK, "");
info.url=fakeUrl;
info.hash=DigestUtils.sha1Hex(info.url);
info.cacheFile = HttpRequestUtil.getCacheFile(info.hash);
return info;
}
return info;
}
public static String getLegacyFakeUrl(String url){
return LEGACY_MARK+url;
}
public static String getLocalFakeUrl(String path){
return LOCAL_MARK+path;
}
public static String getLocalLegacyFakeUrl(String path,String hash){
return LOCAL_LEGACY_MARK+hash+","+path;
}
public static String getHash(String url,long size,long lastModified){
return DigestUtils.sha1Hex(size+url+lastModified);
}
public static File getCacheFile(String hash){
return getCacheFile(defaultCacheDir,hash);
}
public static File getCacheFile(File cacheDir,String hash){
return new File(new File(cacheDir,hash.length()>2?hash.substring(0,2):"xx"), hash);
}
}
@@ -1,176 +0,0 @@
package customskinloader.utils;
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.ThreadDownloadImageData;
import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.SkinManager;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.lang3.StringUtils;
/**
* @author Alexander Xia
* @since 13.6
*/
public class MinecraftUtil {
public static File getMinecraftDataDir() {
return Minecraft.getMinecraft().gameDir;
}
public static TextureManager getTextureManager() {
return Minecraft.getMinecraft().getTextureManager();
}
public static SkinManager getSkinManager() {
return Minecraft.getMinecraft().getSkinManager();
}
private static boolean is_1_15_plus = false;
private static Constructor<?> constructor = null;
public static SimpleTexture createThreadDownloadImageData(File cacheFileIn, String imageUrlIn, ResourceLocation textureResourceLocation, IImageBuffer imageBufferIn, MinecraftProfileTexture.Type textureType) {
if (constructor == null) {
Class<?> c;
try {
c = Class.forName("net.minecraft.client.renderer.texture.ThreadDownloadImageData", false, MinecraftUtil.class.getClassLoader()); // Forge 1.13
} catch (ClassNotFoundException e1) {
try {
c = Class.forName("net.minecraft.client.renderer.texture.DownloadingTexture", false, MinecraftUtil.class.getClassLoader()); // Forge 1.14+
} catch (ClassNotFoundException e2) {
c = ThreadDownloadImageData.class; // Forge 1.12- or Fabric or Vanilla
}
}
try {
constructor = c.getConstructor(File.class, String.class, ResourceLocation.class, boolean.class, Runnable.class); // For 1.15+
is_1_15_plus = true;
} catch (NoSuchMethodException e1) {
try {
constructor = c.getConstructor(File.class, String.class, ResourceLocation.class, IImageBuffer.class); // For 1.15-
} catch (NoSuchMethodException e2) {
throw new RuntimeException(e2);
}
}
}
try {
if (is_1_15_plus) {
return (SimpleTexture) constructor.newInstance(cacheFileIn, imageUrlIn, textureResourceLocation, textureType == MinecraftProfileTexture.Type.SKIN, imageBufferIn);
} else {
return (SimpleTexture) constructor.newInstance(cacheFileIn, imageUrlIn, textureResourceLocation, imageBufferIn);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static ArrayList<String> minecraftVersion = new ArrayList<String>();
private static String minecraftMainVersion = null;
private final static Pattern MINECRAFT_VERSION_PATTERN = Pattern.compile(".*?(\\d+\\.\\d+[\\.]?\\d*).*?");
public static ArrayList<String> getMinecraftVersions() {
if (minecraftVersion != null && !minecraftVersion.isEmpty())
return minecraftVersion;
testProbe();
return minecraftVersion;
}
public static String getMinecraftVersionText() {
StringBuilder sb = new StringBuilder();
for (String version : getMinecraftVersions())
sb.append(version).append(" ");
return StringUtils.trim(sb.toString());
}
public static String getMinecraftMainVersion() {
if (minecraftMainVersion != null)
return minecraftMainVersion;
for (String version : getMinecraftVersions()) {
Matcher m = null;
try {
m = MINECRAFT_VERSION_PATTERN.matcher(version);
} catch (Exception e) {
e.printStackTrace();
}
if (m == null || !m.matches())
continue;
minecraftMainVersion = m.group(m.groupCount());
break;
}
return minecraftMainVersion;
}
// (domain|ip)(:port)
public static String getServerAddress() {
net.minecraft.client.multiplayer.ServerData data = Minecraft.getMinecraft().getCurrentServerData();
if (data == null)//Single Player
return null;
return data.serverIP;
}
// ip:port
public static String getStandardServerAddress() {
return HttpUtil0.parseAddress(getServerAddress());
}
public static boolean isLanServer() {
return HttpUtil0.isLanServer(getStandardServerAddress());
}
public static String getCurrentUsername() {
return Minecraft.getMinecraft().getSession().getProfile().getName();
}
private final static Pattern MINECRAFT_CORE_FILE_PATTERN = Pattern.compile("^(.*?)/versions/([^\\/\\\\]*?)/([^\\/\\\\]*?).jar$");
private static void testProbe() {
minecraftVersion.clear();
URL urls[] = JavaUtil.getClasspath();
for (URL url : urls) {
Matcher m = null;
try {
m = MINECRAFT_CORE_FILE_PATTERN.matcher(URLDecoder.decode(url.getPath(), "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
if (m == null || !m.matches())
continue;
minecraftVersion.add(m.group(2));
}
}
public static boolean isCoreFile(URL url) {
return regexMatch(url, MINECRAFT_CORE_FILE_PATTERN);
}
private final static Pattern LIBRARY_FILE_PATTERN = Pattern.compile("^(.*?)/libraries/(.*?)/([^\\/\\\\]*?).jar$");
public static boolean isLibraryFile(URL url) {
return regexMatch(url, LIBRARY_FILE_PATTERN);
}
private static boolean regexMatch(URL url, Pattern p) {
Matcher m;
try {
m = p.matcher(URLDecoder.decode(url.getPath(), "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
return false;
}
return m.matches();
}
public static String getCredential(GameProfile profile) {
return (profile == null || profile.hashCode() == 0) ? null :
(profile.getId() == null ? profile.getName() : String.format("%s-%s", profile.getName(), profile.getId()));
}
}
@@ -1,16 +0,0 @@
package net.minecraft.client.renderer.texture;
import java.io.File;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.util.ResourceLocation;
public class DownloadingTexture extends SimpleTexture {
public DownloadingTexture(File cacheFileIn, String imageUrlIn, ResourceLocation textureResourceLocation, IImageBuffer imageBufferIn) {
super(textureResourceLocation);
}
public DownloadingTexture(File cacheFileIn, String imageUrlIn, ResourceLocation textureResourceLocation, boolean legacySkinIn, Runnable processTaskIn) {
super(textureResourceLocation);
}
}
@@ -1,12 +0,0 @@
package net.minecraft.client.renderer.texture;
import java.io.File;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.util.ResourceLocation;
public class ThreadDownloadImageData extends SimpleTexture {
public ThreadDownloadImageData(File cacheFileIn, String imageUrlIn, ResourceLocation textureResourceLocation, IImageBuffer imageBufferIn) {
super(textureResourceLocation);
}
}
@@ -0,0 +1,241 @@
package customskinloader;
import java.io.File;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.config.Config;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.ProfileLoader;
import customskinloader.log.LogManager;
import customskinloader.log.Logger;
import customskinloader.profile.DynamicSkullManager;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.ProfileCache;
import customskinloader.profile.UserProfile;
import customskinloader.utils.LIFOBlockingQueue;
import customskinloader.utils.MinecraftUtil;
import customskinloader.utils.TextureUtil;
/**
* Custom skin loader mod for Minecraft.
*
* @author Jeremy Lam [JLChnToZ] 2013-2014 & Alexander Xia [xfl03] 2014-2023
* @version @MOD_FULL_VERSION@
*/
public class CustomSkinLoader {
public static final String CustomSkinLoader_VERSION = "@MOD_VERSION@";
public static final String CustomSkinLoader_FULL_VERSION = "@MOD_FULL_VERSION@";
public static final int CustomSkinLoader_BUILD_NUMBER = Integer.parseInt("@MOD_BUILD_NUMBER@");
public static final File
DATA_DIR = new File(MinecraftUtil.getMinecraftDataDir(), "CustomSkinLoader"),
LOG_FILE = new File(DATA_DIR, "CustomSkinLoader.log"),
CONFIG_FILE = new File(DATA_DIR, "CustomSkinLoader.json");
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static final Logger logger = initLogger();
public static final Config config = initConfig();
private static final ProfileCache profileCache = new ProfileCache();
private static final DynamicSkullManager dynamicSkullManager = new DynamicSkullManager();
public static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(config.threadPoolSize, config.threadPoolSize, 1L, TimeUnit.MINUTES, new LIFOBlockingQueue<>(new LinkedBlockingDeque<>()));
//Correct thread name in thread pool
private static final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
private static final ThreadFactory customFactory = r -> {
Thread t = defaultFactory.newThread(r);
if (r instanceof Thread) {
t.setName(((Thread) r).getName());
}
return t;
};
//Thread pool will discard oldest task when queue reaches 333 tasks
private static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
config.threadPoolSize, config.threadPoolSize, 1L, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(333), customFactory, new ThreadPoolExecutor.DiscardOldestPolicy()
);
public static void loadProfileTextures(Runnable runnable) {
THREAD_POOL.execute(runnable);
}
//For User Skin
public static UserProfile loadProfile(GameProfile gameProfile) {
String username = TextureUtil.AuthlibField.GAME_PROFILE_NAME.get(gameProfile);
String credential = MinecraftUtil.getCredential(gameProfile);
// Fix: http://hopper.minecraft.net/crashes/minecraft/MCX-2773713
if (username == null) {
logger.warning("Could not load profile: username is null.");
return new UserProfile();
}
String tempName = Thread.currentThread().getName();
Thread.currentThread().setName(username); // Change Thread Name
UserProfile profile;
if (profileCache.isReady(credential)) {
logger.info("Cached profile will be used.");
profile = profileCache.getProfile(credential);
if (profile == null) {
logger.warning("(Cached Profile is empty!) Expiry: " + profileCache.getExpiry(credential));
if (profileCache.isExpired(credential)) { // force load
profile = loadProfile0(gameProfile, false);
}
} else {
logger.info(profile.toString(profileCache.getExpiry(credential)));
}
} else {
profileCache.setLoading(credential, true);
profile = loadProfile0(gameProfile, false);
}
Thread.currentThread().setName(tempName);
return profile == null ? new UserProfile() : profile;
}
//Core
public static UserProfile loadProfile0(GameProfile gameProfile, boolean isSkull) {
String username = TextureUtil.AuthlibField.GAME_PROFILE_NAME.get(gameProfile);
String credential = MinecraftUtil.getCredential(gameProfile);
profileCache.setLoading(credential, true);
logger.info("Loading " + username + "'s profile.");
if (config.loadlist == null || config.loadlist.isEmpty()) {
logger.info("LoadList is Empty.");
return null;
}
UserProfile profile0 = new UserProfile();
for (int i = 0; i < config.loadlist.size(); i++) {
SkinSiteProfile ssp = config.loadlist.get(i);
logger.info((i + 1) + "/" + config.loadlist.size() + " Try to load profile from '" + ssp.name + "'.");
if (ssp.type == null) {
logger.info("The type of '" + ssp.name + "' is null.");
continue;
}
ProfileLoader.IProfileLoader loader = ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if (loader == null) {
logger.info("Type '" + ssp.type + "' is not defined.");
continue;
}
UserProfile profile = null;
try {
profile = loader.loadProfile(ssp, gameProfile);
} catch (Exception e) {
logger.warning("Exception occurs while loading.");
logger.warning(e);
if (e.getCause() != null) {
logger.warning("Caused By:");
logger.warning(e.getCause());
}
}
if (profile == null) {
continue;
}
profile0.mix(profile);
if (isSkull && !profile0.hasSkinUrl()) {
continue;
}
if (!config.forceLoadAllTextures) {
break;
}
if (profile0.isFull()) {
break;
}
}
if (!profile0.isEmpty()) {
logger.info(username + "'s profile loaded.");
if (!config.enableCape) {
profile0.capeUrl = null;
}
profileCache.updateCache(credential, profile0);
profileCache.setLoading(credential, false);
logger.info(profile0.toString(profileCache.getExpiry(credential)));
return profile0;
}
logger.info(username + "'s profile not found in load list.");
if (config.enableLocalProfileCache) {
UserProfile profile = profileCache.getLocalProfile(credential);
if (profile == null || profile.equals(UserProfile.NULL)) {
logger.info(username + "'s LocalProfile not found.");
} else {
profileCache.updateCache(credential, profile, false);
profileCache.setLoading(credential, false);
logger.info(username + "'s LocalProfile will be used.");
logger.info(profile.toString(profileCache.getExpiry(credential)));
return profile;
}
}
profileCache.setLoading(credential, false);
return null;
}
public final static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> INCOMPLETED = ImmutableMap.of();
//For Skull
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadProfileFromCache(final GameProfile gameProfile) {
String username = TextureUtil.AuthlibField.GAME_PROFILE_NAME.get(gameProfile);
String credential = MinecraftUtil.getCredential(gameProfile);
//CustomSkinLoader needs username to load standard skin, if username not exist, only textures in NBT can be used
//Authlib 3.11.50 makes empty username to " "
if (username == null || username.isEmpty() || username.equals(" ") || credential == null) {
return dynamicSkullManager.getTexture(gameProfile);
}
if (config.forceUpdateSkull ? profileCache.isReady(credential) : profileCache.isExist(credential)) {
UserProfile profile = profileCache.getProfile(credential);
return ModelManager0.fromUserProfile(profile);
}
if (!profileCache.isLoading(credential)) {
profileCache.setLoading(credential, true);
Runnable loadThread = () -> {
String tempName = Thread.currentThread().getName();
Thread.currentThread().setName(username + "'s skull");
loadProfile0(gameProfile, true);//Load in thread
Thread.currentThread().setName(tempName);
};
if (config.forceUpdateSkull) {
new Thread(loadThread).start();
} else {
threadPool.execute(loadThread);
}
}
return INCOMPLETED;
}
private static Logger initLogger() {
LogManager.setLogFile(LOG_FILE.toPath());
Logger logger = LogManager.getLogger("Core");
logger.info("CustomSkinLoader " + CustomSkinLoader_FULL_VERSION);
logger.info("DataDir: " + DATA_DIR.getAbsolutePath());
logger.info("Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + System.getProperty("os.version"));
logger.info("Java Version: " + System.getProperty("java.version") + ", " + System.getProperty("java.vendor"));
logger.info("Java VM Version: " + System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + System.getProperty("java.vm.vendor"));
logger.info("Minecraft: " + MinecraftUtil.getMinecraftMainVersion());
return logger;
}
/**
* Create <code>Config</code> object.
* To use <code>logger</code>, please make sure call this function after <code>initLogger</code>.
*
* @return <code>Config</code>
*/
private static Config initConfig() {
Config config = Config.loadConfig0();
logger.enableLogStdOut = config.enableLogStdOut;
return config;
}
}
@@ -0,0 +1,259 @@
package customskinloader.config;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import customskinloader.CustomSkinLoader;
import customskinloader.loader.ProfileLoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.plugin.PluginLoader;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.Version;
import org.apache.commons.io.FileUtils;
@SuppressWarnings("ResultOfMethodCallIgnored")
public class Config {
//Program
public String version;
public int buildNumber;
public List<SkinSiteProfile> loadlist;
//Function
public boolean enableDynamicSkull = true;
public boolean enableTransparentSkin = true;
public boolean forceLoadAllTextures = true;
public boolean enableCape = true;
public int threadPoolSize = 8;
/**
* Can logger write message to standard output(System.out).
* Because standard output won't write to latest.log after Forge 1.17,
* printing to standard output is meaningless,
* which makes this switch default value is <code>false</code>.
* @since 14.15
*/
public boolean enableLogStdOut = false;
//Profile Cache
public int cacheExpiry = 30;
public boolean forceUpdateSkull = false;
public boolean enableLocalProfileCache = false;
//Network Cache
public boolean enableCacheAutoClean = false;
public boolean forceDisableCache = false;
// Used by Gson to create an instance with default value.
public Config() {
this(new ArrayList<>());
}
//Init config
public Config(List<SkinSiteProfile> loadlist) {
this.version = CustomSkinLoader.CustomSkinLoader_VERSION;
this.buildNumber = CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER;
this.loadlist = loadlist;
}
public static Config loadConfig0() {
Config config = loadConfig();
//LoadList null checker
if (config.loadlist == null) {
config.loadlist = new ArrayList<>();
} else {
for (int i = 0; i < config.loadlist.size(); i++) {
if (config.loadlist.get(i) == null)
config.loadlist.remove(i--);
}
}
//Init program
config.loadExtraList();
config.updateLoadlist();
config.initLocalFolder();
config.threadPoolSize = Math.max(config.threadPoolSize, 1);
if (config.enableCacheAutoClean && !config.enableLocalProfileCache) {
try {
FileUtils.deleteDirectory(HttpRequestUtil.CACHE_DIR);
FileUtils.deleteDirectory(HttpTextureUtil.getCacheDir());
CustomSkinLoader.logger.info("Successfully cleaned cache.");
} catch (Exception e) {
CustomSkinLoader.logger.warning("Exception occurs while cleaning cache: " + e);
}
}
//Check config version
Version configVersion = Version.of(config.version);
if (CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER == 0 // Custom builds
|| configVersion.compareTo(CustomSkinLoader.CustomSkinLoader_VERSION) < 0
|| config.buildNumber < CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER) {
CustomSkinLoader.logger.info("Config File is out of date: " + config.version +
", build number: " + config.buildNumber);
config.version = CustomSkinLoader.CustomSkinLoader_VERSION;
config.buildNumber = CustomSkinLoader.CustomSkinLoader_BUILD_NUMBER;
}
writeConfig(config, true);
//Output config
for (Field field : config.getClass().getDeclaredFields()) {
try {
Object value = field.get(config);
CustomSkinLoader.logger.info(field.getName() + " : " + value);
} catch (Exception ignored) {
}
}
return config;
}
private static Config loadConfig() {
CustomSkinLoader.logger.info("Config File: " + CustomSkinLoader.CONFIG_FILE.getAbsolutePath());
if (!CustomSkinLoader.CONFIG_FILE.exists()) {
CustomSkinLoader.logger.info("Config file not found, use default instead.");
return initConfig();
}
try {
CustomSkinLoader.logger.info("Try to load config.");
String json = FileUtils.readFileToString(CustomSkinLoader.CONFIG_FILE, "UTF-8");
Config config = Objects.requireNonNull(CustomSkinLoader.GSON.fromJson(json, Config.class));
CustomSkinLoader.logger.info("Successfully load config.");
return config;
} catch (Exception e) {
CustomSkinLoader.logger.info("Failed to load config, use default instead.(" + e + ")");
createBrokenFile(CustomSkinLoader.CONFIG_FILE);
return initConfig();
}
}
private void loadExtraList() {
File listAddition = new File(CustomSkinLoader.DATA_DIR, "ExtraList");
if (!listAddition.isDirectory()) {
listAddition.mkdirs();
return;
}
List<SkinSiteProfile> adds = new ArrayList<>();
File[] files = listAddition.listFiles();
for (File file : files != null ? files : new File[0]) {
if (!file.getName().toLowerCase().endsWith(".json") && !file.getName().toLowerCase().endsWith(".txt"))
continue;
try {
CustomSkinLoader.logger.info("Try to load Extra List.(" + file.getName() + ")");
String json = FileUtils.readFileToString(file, "UTF-8");
SkinSiteProfile ssp = CustomSkinLoader.GSON.fromJson(json, SkinSiteProfile.class);
CustomSkinLoader.logger.info("Successfully load Extra List.");
if (ssp.type != null) {
ProfileLoader.IProfileLoader loader = ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if (loader == null) {
CustomSkinLoader.logger.info("Extra List will be ignored: Type '" + ssp.type +
"' is not defined.");
continue;
}
boolean duplicate = false;
for (SkinSiteProfile ssp0 : this.loadlist) {
if (!ssp0.type.equalsIgnoreCase(ssp.type))
continue;
if (loader.compare(ssp0, ssp)) {
duplicate = true;
break;
}
}
if (!duplicate) {
adds.add(ssp);
CustomSkinLoader.logger.info("Successfully apply Extra List.(" + ssp.name + ")");
} else {
CustomSkinLoader.logger.info("Extra List will be ignored: Duplicate.(" + ssp.name + ")");
}
file.delete();
} else {
CustomSkinLoader.logger.info("Extra List is invalid: Type is not defined.(" +
file.getName() + ")");
createBrokenFile(file);
}
} catch (Exception e) {
CustomSkinLoader.logger.info("Failed to load Extra List.(" + e + ")");
createBrokenFile(file);
}
}
if (adds.size() != 0) {
adds.addAll(this.loadlist);
this.loadlist = adds;
}
}
private void updateLoadlist() {
PluginLoader.PLUGINS.stream()
.map(ICustomSkinLoaderPlugin::getDefaultProfiles)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.forEach(profile -> this.loadlist.stream()
.filter(ssp -> profile.getName().equals(ssp.name))
.forEach(profile::updateSkinSiteProfile));
}
private void initLocalFolder() {
for (SkinSiteProfile ssp : this.loadlist) {
if (ssp.type == null)
continue;
ProfileLoader.IProfileLoader loader = ProfileLoader.LOADERS.get(ssp.type.toLowerCase());
if (loader == null)
continue;
loader.init(ssp);
}
}
private static void createBrokenFile(File file) {
try {
File brokenFile = new File(file.getParentFile(), file.getName() + ".broken");
if (brokenFile.exists()) {
brokenFile.delete();
}
file.renameTo(brokenFile);
} catch (Exception e) {
CustomSkinLoader.logger.warning("Failed to create broken file. (" + file.getName() + ")");
CustomSkinLoader.logger.warning(e);
}
}
// The config file does not exist or was broken.
private static Config initConfig() {
List<ICustomSkinLoaderPlugin.IDefaultProfile> profiles = new ArrayList<>();
for (ICustomSkinLoaderPlugin plugin : PluginLoader.PLUGINS) {
List<ICustomSkinLoaderPlugin.IDefaultProfile> defaultProfiles = plugin.getDefaultProfiles();
if (defaultProfiles != null) {
profiles.addAll(defaultProfiles);
}
}
profiles.sort(Comparator.comparingInt(ICustomSkinLoaderPlugin.IDefaultProfile::getPriority));
List<SkinSiteProfile> loadlist = new ArrayList<>();
for (ICustomSkinLoaderPlugin.IDefaultProfile profile : profiles) {
SkinSiteProfile ssp = new SkinSiteProfile();
ssp.name = profile.getName();
profile.updateSkinSiteProfile(ssp);
loadlist.add(ssp);
}
Config config = new Config(loadlist);
writeConfig(config, false);
return config;
}
private static void writeConfig(Config config, boolean update) {
String json = CustomSkinLoader.GSON.toJson(config);
if (CustomSkinLoader.CONFIG_FILE.exists())
CustomSkinLoader.CONFIG_FILE.delete();
try {
CustomSkinLoader.CONFIG_FILE.createNewFile();
FileUtils.write(CustomSkinLoader.CONFIG_FILE, json, "UTF-8");
CustomSkinLoader.logger.info("Successfully " + (update ? "update" : "create") + " config.");
} catch (Exception e) {
CustomSkinLoader.logger.info("Failed to " + (update ? "update" : "create") + " config.(" + e + ")");
}
}
}
@@ -0,0 +1,44 @@
package customskinloader.config;
import java.lang.reflect.Field;
public class SkinSiteProfile {
//Common
public String name;
public String type;
public String userAgent;
//Mojang API
public String apiRoot;
public String sessionRoot;
//Json API
public String root;
//Legacy
public Boolean checkPNG;//Not suitable for local skin
public String skin;
public String model;
public String cape;
public String elytra;
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{ ");
Field[] fields = SkinSiteProfile.class.getDeclaredFields();
boolean first = true;
for (Field field : fields) {
try {
Object value = field.get(this);
if (value == null) continue;
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append("\"").append(field.getName()).append("\": \"").append(value).append("\"");
} catch (Exception ignored) { }
}
return sb.append(" }").toString();
}
}
@@ -0,0 +1,253 @@
package customskinloader.fake;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import customskinloader.CustomSkinLoader;
import customskinloader.fake.itf.FakeInterfaceManager;
import customskinloader.fake.texture.FakeImage;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
public class FakeCapeBuffer extends FakeSkinBuffer {
private static final ResourceLocation TEXTURE_ELYTRA_V1 = new ResourceLocation("minecraft", "textures/entity/elytra.png");
private static final ResourceLocation TEXTURE_ELYTRA_V2 = new ResourceLocation("minecraft", "textures/entity/equipment/wings/elytra.png");
private static int loadedGlobal = 0;
private static FakeImage elytraImage;
private static FakeImage loadElytra(FakeImage originalImage) {
loadedGlobal++;
try {
Object resourceManager = FakeInterfaceManager.Minecraft_getResourceManager(Minecraft.getMinecraft());
InputStream is = FakeInterfaceManager.IResource_getInputStream(FakeInterfaceManager.IResourceManager_getResource(resourceManager, TEXTURE_ELYTRA_V1)
.orElseGet(() -> FakeInterfaceManager.IResourceManager_getResource(resourceManager, TEXTURE_ELYTRA_V2).orElse(null)));
if (is != null) {
FakeImage image = originalImage.createImage(is);
if (image.getWidth() % 64 != 0 || image.getHeight() % 32 != 0) { // wtf?
return elytraImage;
}
image = resetImageFormat(image, 22, 0, 46, 22);
return image;
}
} catch (IOException e) {
CustomSkinLoader.logger.warning(e);
}
return null;
}
private int loaded = 0;
private double ratioX = -1;
private double ratioY = -1;
private String type = null;
@Override
public FakeImage parseUserSkin(FakeImage image) {
if (image == null) return null;
if (isOptiFineCape(image)) {
//OptiFine cape should be converted to standard cape
this.image = convertOptiFineCape(image);
//OptiFine cape contains elytra texture
//this.type = "elytra";//But its elytra texture doesn't work
} else {
this.image = image;
}
// When resource packs were changed, the elytra image needs to be reloaded, and here will be entered again
// The first cape which find elytra texture is outdated will reload it
if (this.loaded == loadedGlobal) {
elytraImage = loadElytra(this.image);
}
this.loaded = loadedGlobal;
if (elytraImage != null) {
if (this.ratioX < 0)
this.ratioX = this.image.getWidth() / 64.0D;
if (this.ratioY < 0)
this.ratioY = this.image.getHeight() / 32.0D;
if (this.type == null)
this.type = this.judgeType();
if ("cape".equals(this.type)) {
this.image = resetImageFormat(this.image, 0, 0, 22, 17);
this.attachElytra(elytraImage);
}
}
return this.image;
}
/**
* Judge the cape type
*
* @return "elytra" if the cape contains elytra texture, otherwise "cape"
*/
@Override
public String judgeType() {
if (this.image != null && elytraImage != null) {
// If all the pixels in ((22, 0), (45, 21)) is same as background, it means the cape doesn't contain elytra
Predicate<Integer> predicate = EQU_BG.apply(this.image.getRGBA(this.image.getWidth() - 1, this.image.getHeight() - 1));
return withElytraPixels((x, y) -> !predicate.test(this.image.getRGBA(x, y)), "elytra", "cape");
}
return "cape";
}
private void attachElytra(FakeImage elytraImage) {
if (this.image != null) {
int capeW = this.image.getWidth(), capeH = this.image.getHeight();
int elytraW = elytraImage.getWidth(), elytraH = elytraImage.getHeight();
// scale cape and elytra to the same size
// cape part ((0, 0), (21, 16)) -> (22 * 17)
if (capeW < elytraW) {
this.image = scaleImage(this.image, true, elytraW / (double) capeW, 1, capeW / 64.0D, capeH / 32.0D, elytraW, capeH, 0, 0, 22, 17);
capeW = elytraW;
}
if (capeH < elytraH) {
this.image = scaleImage(this.image, true, 1, elytraH / (double) capeH, capeW / 64.0D, capeH / 32.0D, capeW, elytraH, 0, 0, 22, 17);
capeH = elytraH;
}
// elytra part ((22, 0), (45, 21)) -> (24 * 22)
if (elytraW < capeW) {
elytraImage = scaleImage(elytraImage, false, capeW / (double) elytraW, 1, elytraW / 64.0D, elytraH / 32.0D, capeW, elytraH, 22, 0, 46, 22);
elytraW = capeW;
}
if (elytraH < capeH) {
elytraImage = scaleImage(elytraImage, false, 1, capeH / (double) elytraH, elytraW / 64.0D, elytraH / 32.0D, elytraW, capeH, 22, 0, 46, 22);
elytraH = capeH;
}
this.ratioX = capeW / 64.0D;
this.ratioY = capeH / 32.0D;
// Overwrite pixels from elytra to cape
FakeImage finalElytraImage = elytraImage;
withElytraPixels((x, y) -> {
this.image.setRGBA(x, y, finalElytraImage.getRGBA(x, y));
return false;
}, null, null);
}
}
/**
* Traverse every elytra pixel
*
* @param predicate the predicate with x and y
* @param returnValue if the condition flag equals the condition, then return this value
* @param defaultReturnValue otherwise return this value
*/
private <R> R withElytraPixels(BiPredicate<Integer, Integer> predicate, R returnValue, R defaultReturnValue) {
int startX = (int) Math.ceil(22 * ratioX), endX = (int) Math.ceil(46 * ratioX);
int startY = (int) Math.ceil(0 * ratioY), endY = (int) Math.ceil(22 * ratioY);
int excludeX0 = (int) Math.ceil(24 * ratioX), excludeX1 = (int) Math.ceil(44 * ratioX);
int excludeY = (int) Math.ceil(2 * ratioY);
for (int x = startX; x < endX; ++x) {
for (int y = startY; y < endY; ++y) {
if (y < excludeY && (x < excludeX0 || x >= excludeX1)) continue;
if (predicate.test(x, y)) {
return returnValue;
}
}
}
return defaultReturnValue;
}
// Some cape image doesn't support alpha channel, so reset image format to ARGB
private static FakeImage resetImageFormat(FakeImage image, int startX, int startY, int endX, int endY) {
if (image != null) {
int width = image.getWidth(), height = image.getHeight();
image = scaleImage(image, true, 1, 1, width / 64.0D, height / 32.0D, width, height, startX, startY, endX, endY);
}
return image;
}
/**
* Scale image
*
* @param image the image to scale.
* @param closeOldImage whether close old image
* @param scaleWidth width enlargement ratio
* @param scaleHeight height enlargement ratio
* @param ratioX the ratio of 64 of the old image width
* @param ratioY the ratio of 32 of the old image height
* @param width the width after scaling.
* @param height the height after scaling.
* @param startX the x where start to copy.
* @param startY the y where start to copy.
* @param endX the x where end to copy.
* @param endY the y where end to copy.
* @return the image after scaling.
*/
private static FakeImage scaleImage(FakeImage image, boolean closeOldImage, double scaleWidth, double scaleHeight, double ratioX, double ratioY, int width, int height, int startX, int startY, int endX, int endY) {
FakeImage newImage = image.createImage(width, height);
startX = (int) (startX * ratioX);
endX = (int) (endX * ratioX);
startY = (int) (startY * ratioY);
endY = (int) (endY * ratioY);
int x0 = (int) (startX * scaleWidth), x1 = (int) ((startX + 1) * scaleWidth), dx0 = x1 - x0;
for (int x = startX; x < endX; ++x) {
int y0 = (int) (startY * scaleHeight), y1 = (int) ((startY + 1) * scaleHeight), dy0 = y1 - y0;
for (int y = startY; y < endY; ++y) {
int rgba = image.getRGBA(x, y);
for (int dx = 0; dx < dx0; dx++) {
for (int dy = 0; dy < dy0; dy++) {
newImage.setRGBA(x0 + dx, y0 + dy, rgba);
}
}
y0 = y1;
y1 = (int) ((y + 2) * scaleHeight);
dy0 = y1 - y0;
}
x0 = x1;
x1 = (int) ((x + 2) * scaleWidth);
dx0 = x1 - x0;
}
if (closeOldImage)
image.close();
return newImage;
}
/**
* Judge OptiFine cape.
* OptiFine cape is 46*22 or 92*44 pixels.
* <a href="https://optifine.net/capes/Notch.png">46*22 example</a>
* <a href="https://optifine.net/capes/OptiFineCape.png">92*44 example</a>
*
* @param image cape image
* @return true if is OptiFine cape
* @since 14.16
*/
private static boolean isOptiFineCape(FakeImage image) {
int ratio = image.getWidth() / 46;
return image.getHeight() == 22 * ratio && image.getWidth() == 46 * ratio;
}
/**
* Convert OptiFine cape to standard cape
*
* @param image OptiFine cape image
* @return standard cape image
* @since 14.16
*/
private static FakeImage convertOptiFineCape(FakeImage image) {
int ratio = image.getWidth() / 46;
FakeImage newImage = image.createImage(64 * ratio, 32 * ratio);
copyImageData(image, newImage);
return newImage;
}
/**
* Copy image data to another image
*
* @param from from image
* @param to to image
*/
private static void copyImageData(FakeImage from, FakeImage to) {
int width = Math.min(from.getWidth(), to.getWidth());
int height = Math.min(from.getHeight(), to.getHeight());
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
to.setRGBA(x, y, from.getRGBA(x, y));
}
}
}
}
@@ -7,7 +7,6 @@ import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import customskinloader.CustomSkinLoader;
import customskinloader.utils.MinecraftUtil;
import net.minecraft.client.renderer.ThreadDownloadImageData;
@@ -16,11 +15,21 @@ import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.DefaultPlayerSkin;
import net.minecraft.client.resources.SkinManager;
import net.minecraft.client.resources.SkinManager.SkinAvailableCallback;
import net.minecraft.client.resources.SkinManager$SkinAvailableCallback;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StringUtils;
public class FakeClientPlayer {
/**
* Invoked from {@link SkinManager#loadSkin(MinecraftProfileTexture, MinecraftProfileTexture.Type, SkinManager$SkinAvailableCallback)}
*/
public static ThreadDownloadImageData putCache(ThreadDownloadImageData threaddownloadimagedata, SkinManager$SkinAvailableCallback skinAvailableCallback, ResourceLocation resourcelocation) {
if (skinAvailableCallback instanceof FakeClientPlayer.LegacyBuffer) {//Cache for client player
textureCache.put(resourcelocation, threaddownloadimagedata);
}
return threaddownloadimagedata;
}
//For Legacy Skin
public static ThreadDownloadImageData getDownloadImageSkin(ResourceLocation resourceLocationIn, String username) {
//CustomSkinLoader.logger.debug("FakeClientPlayer/getDownloadImageSkin "+username);
@@ -59,7 +68,7 @@ public class FakeClientPlayer {
public static Map<ResourceLocation, ITextureObject> textureCache = Maps.newHashMap();
public static class LegacyBuffer implements SkinAvailableCallback {
public static class LegacyBuffer implements SkinManager$SkinAvailableCallback {
ResourceLocation resourceLocationIn;
boolean loaded = false;
@@ -0,0 +1,71 @@
package customskinloader.fake;
import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.CustomSkinLoader;
import customskinloader.utils.HttpTextureUtil;
public class FakeMinecraftProfileTexture extends MinecraftProfileTexture {
private final static Map<String, String> MODEL_CACHE = new ConcurrentHashMap<>();
private final HttpTextureUtil.HttpTextureInfo info;
private final Map<String, String> metadata;
private final CountDownLatch latch = new CountDownLatch(1);
public FakeMinecraftProfileTexture(String url, Map<String, String> metadata) {
super(url, metadata);
this.info = HttpTextureUtil.toHttpTextureInfo(url);
this.metadata = metadata;
}
@Override
public String getUrl() {
return this.info.url;
}
@Override
public String getMetadata(String key) {
return this.getMetadata(key, true);
}
public String getMetadata(String key, boolean lock) {
String value = super.getMetadata(key);
if ("model".equals(key) && "auto".equals(value)) {
String model = MODEL_CACHE.get(this.getHash());
if (model != null) {
return model;
} else {
try {
if (lock && this.latch.await(60L * CustomSkinLoader.config.loadlist.size(), TimeUnit.SECONDS)) {
return this.getMetadata(key, false);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
return value;
}
public void setModel(String model) {
if (this.metadata != null) {
MODEL_CACHE.put(this.getHash(), model);
this.metadata.put("model", model);
this.latch.countDown();
}
}
@Override
public String getHash() {
return this.info.hash == null ? super.getHash() : this.info.hash;
}
public File getCacheFile() {
return this.info.cacheFile;
}
}
@@ -1,6 +1,9 @@
package customskinloader.fake;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.function.Function;
import java.util.function.Predicate;
import customskinloader.CustomSkinLoader;
@@ -8,18 +11,42 @@ import customskinloader.fake.texture.FakeBufferedImage;
import customskinloader.fake.texture.FakeImage;
import customskinloader.fake.texture.FakeNativeImage;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.ThreadDownloadImageData;
import net.minecraft.client.renderer.texture.NativeImage;
import net.minecraft.client.renderer.texture.SkinTextureDownloader;
public class FakeSkinBuffer implements IImageBuffer {
private int ratio = 1;
private FakeImage image = null;
FakeImage image = null;
//parseUserSkin for 1.15+
public static NativeImage processLegacySkin(NativeImage image, Runnable processTask) {
/**
* 24w46a+
* Invoked from {@link SkinTextureDownloader#lambda$downloadAndRegisterSkin$0(Path, String, boolean)}
*/
public static NativeImage processLegacySkin(NativeImage image, String url) {
if (image == null)
return null;
FakeImage img = parseUserSkin0(new FakeNativeImage(image));
if (img instanceof FakeNativeImage) {
return FakeNativeImage.Extended.create((FakeNativeImage) img);
}
CustomSkinLoader.logger.warning("Failed to parseUserSkin(downloadAndRegisterSkin).");
return null;
}
/**
* 19w38a ~ 24w45a
* Invoked from {@link ThreadDownloadImageData#loadTexture(InputStream)}
*/
public static NativeImage processLegacySkin(NativeImage image, Runnable processTask, Function<NativeImage, NativeImage> processLegacySkin) {
if (processTask instanceof IImageBuffer) {
return ((IImageBuffer) processTask).func_195786_a(image);
} else if (processLegacySkin != null) {
return processLegacySkin.apply(image);
} else {
return image;
}
return new FakeSkinBuffer().func_195786_a(image);
}
//parseUserSkin for 1.13+
@@ -49,8 +76,12 @@ public class FakeSkinBuffer implements IImageBuffer {
}
public FakeImage parseUserSkin(FakeImage image) {
return this.image = parseUserSkin0(image);
}
public static FakeImage parseUserSkin0(FakeImage image) {
if (image == null) return null;
this.ratio = image.getWidth() / 64;
int ratio = image.getWidth() / 64;
if (image.getHeight() != image.getWidth()) {//Single Layer
//Create a new image and copy origin image data
@@ -76,24 +107,32 @@ public class FakeSkinBuffer implements IImageBuffer {
image.copyArea(52 * ratio, 20 * ratio, -8 * ratio, 32 * ratio, 4 * ratio, 12 * ratio, true, false);//Back
}
this.image = image;
setAreaDueToConfig(0 * ratio, 0 * ratio, 32 * ratio, 16 * ratio);//Head - 1
setAreaTransparent(32 * ratio, 0 * ratio, 64 * ratio, 16 * ratio);//Head - 2
setAreaDueToConfig(16 * ratio, 16 * ratio, 40 * ratio, 32 * ratio);//Body - 1
setAreaTransparent(16 * ratio, 32 * ratio, 40 * ratio, 48 * ratio);//Body - 2
setAreaDueToConfig(image, 0 * ratio, 0 * ratio, 32 * ratio, 16 * ratio);//Head - 1
setAreaTransparent(image, 32 * ratio, 0 * ratio, 64 * ratio, 16 * ratio);//Head - 2
setAreaDueToConfig(image, 16 * ratio, 16 * ratio, 40 * ratio, 32 * ratio);//Body - 1
setAreaTransparent(image, 16 * ratio, 32 * ratio, 40 * ratio, 48 * ratio);//Body - 2
setAreaDueToConfig(40 * ratio, 16 * ratio, 56 * ratio, 32 * ratio);//Right Arm - 1
setAreaTransparent(40 * ratio, 32 * ratio, 56 * ratio, 48 * ratio);//Right Arm - 2
setAreaDueToConfig(0 * ratio, 16 * ratio, 16 * ratio, 32 * ratio);//Right Leg - 1
setAreaTransparent(0 * ratio, 32 * ratio, 16 * ratio, 48 * ratio);//Right Leg - 2
setAreaDueToConfig(image, 40 * ratio, 16 * ratio, 56 * ratio, 32 * ratio);//Right Arm - 1
setAreaTransparent(image, 40 * ratio, 32 * ratio, 56 * ratio, 48 * ratio);//Right Arm - 2
setAreaDueToConfig(image, 0 * ratio, 16 * ratio, 16 * ratio, 32 * ratio);//Right Leg - 1
setAreaTransparent(image, 0 * ratio, 32 * ratio, 16 * ratio, 48 * ratio);//Right Leg - 2
setAreaDueToConfig(32 * ratio, 48 * ratio, 48 * ratio, 64 * ratio);//Left Arm - 1
setAreaTransparent(48 * ratio, 48 * ratio, 64 * ratio, 64 * ratio);//Left Arm - 2
setAreaDueToConfig(16 * ratio, 48 * ratio, 32 * ratio, 64 * ratio);//Left Leg - 1
setAreaTransparent(0 * ratio, 48 * ratio, 16 * ratio, 64 * ratio);//Left Leg - 2
setAreaDueToConfig(image, 32 * ratio, 48 * ratio, 48 * ratio, 64 * ratio);//Left Arm - 1
setAreaTransparent(image, 48 * ratio, 48 * ratio, 64 * ratio, 64 * ratio);//Left Arm - 2
setAreaDueToConfig(image, 16 * ratio, 48 * ratio, 32 * ratio, 64 * ratio);//Left Leg - 1
setAreaTransparent(image, 0 * ratio, 48 * ratio, 16 * ratio, 64 * ratio);//Left Leg - 2
image.setRatio(ratio);
return image;
}
/** Judge if the color is transparent or same with background */
static final Function<Integer, Predicate<Integer>> EQU_BG = bgColor -> getA(bgColor) == 0 ? (c) -> getA(c) == 0 : (c) -> c.equals(bgColor);
public String judgeType() {
return judgeType0(this.image);
}
/**
* Judge the type of skin
* Must be called after parseUserSkin
@@ -101,9 +140,10 @@ public class FakeSkinBuffer implements IImageBuffer {
* @return type of skin (slim / default)
* @since 14.9
*/
public String judgeType() {
if (this.image == null)
public static String judgeType0(FakeImage image) {
if (image == null)
return "default";
int ratio = image.getRatio();
int bgColor = image.getRGBA(63 * ratio, 20 * ratio);
/*
* If background is transparent, all the pixels in ((54, 20), (55, 31)) areas is transparent,
@@ -112,8 +152,7 @@ public class FakeSkinBuffer implements IImageBuffer {
* which means it is Alex model.
* Otherwise, it is Steve model.
* */
Predicate<Integer> predicate =
getA(bgColor) == 0 ? (c) -> getA(c) == 0 : (c) -> c == bgColor;
Predicate<Integer> predicate = EQU_BG.apply(bgColor);
for (int x = 54 * ratio; x <= 55 * ratio; ++x) {
for (int y = 20 * ratio; y <= 31 * ratio; ++y) {
int color = image.getRGBA(x, y);
@@ -131,7 +170,7 @@ public class FakeSkinBuffer implements IImageBuffer {
private static final int WHITE = getARGB(255, 255, 255, 255);
private static final int BLACK = getARGB(255, 0, 0, 0);
private boolean isFilled(int x0, int y0, int x1, int y1) {
private static boolean isFilled(FakeImage image, int x0, int y0, int x1, int y1) {
int data = image.getRGBA(x0, y0);
if (data != WHITE && data != BLACK)
return false;
@@ -142,8 +181,8 @@ public class FakeSkinBuffer implements IImageBuffer {
return true;
}
private void setAreaTransparent(int x0, int y0, int x1, int y1) {
if (!isFilled(x0, y0, x1, y1))
private static void setAreaTransparent(FakeImage image, int x0, int y0, int x1, int y1) {
if (!isFilled(image, x0, y0, x1, y1))
return;
for (int x = x0; x < x1; ++x)
for (int y = y0; y < y1; ++y)
@@ -156,17 +195,17 @@ public class FakeSkinBuffer implements IImageBuffer {
* 11111111 00000000 00000000 00000000 */
private static final int B = -16777216;
private void setAreaOpaque(int x0, int y0, int x1, int y1) {
private static void setAreaOpaque(FakeImage image, int x0, int y0, int x1, int y1) {
for (int x = x0; x < x1; ++x)
for (int y = y0; y < y1; ++y)
image.setRGBA(x, y, image.getRGBA(x, y) | B);
}
private void setAreaDueToConfig(int x0, int y0, int x1, int y1) {
private static void setAreaDueToConfig(FakeImage image, int x0, int y0, int x1, int y1) {
if (customskinloader.CustomSkinLoader.config.enableTransparentSkin)
setAreaTransparent(x0, y0, x1, y1);
setAreaTransparent(image, x0, y0, x1, y1);
else
setAreaOpaque(x0, y0, x1, y1);
setAreaOpaque(image, x0, y0, x1, y1);
}
public void skinAvailable() {
@@ -0,0 +1,245 @@
package customskinloader.fake;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import com.google.common.collect.ImmutableList;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.SignatureState;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTextures;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.properties.Property;
import customskinloader.CustomSkinLoader;
import customskinloader.fake.texture.FakeResourceLocation;
import customskinloader.profile.ModelManager0;
import customskinloader.utils.HttpTextureUtil;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.texture.NativeImage;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.SkinManager;
import net.minecraft.client.resources.SkinManager$1;
import net.minecraft.client.resources.SkinManager$CacheKey;
import net.minecraft.client.resources.SkinManager$SkinAvailableCallback;
import net.minecraft.client.resources.SkinManager$TextureCache;
import net.minecraft.server.Services;
import net.minecraft.util.ResourceLocation;
public class FakeSkinManager {
/**
* 1.20.1-
* Invoked from {@link SkinManager(TextureManager, File, MinecraftSessionService)}
*/
public static void setSkinCacheDir(File skinCacheDirectory) {
HttpTextureUtil.defaultCacheDir = skinCacheDirectory;
}
/**
* 23w31a ~ 23w45a
* Invoked from {@link SkinManager(TextureManager, Path, MinecraftSessionService, Executor)}
*
* 23w46a ~ 25w33a
* Invoked from {@link SkinManager(Path, MinecraftSessionService, Executor)}
*
* 25w34a+
* Invoked from {@link SkinManager(Path, Services, Executor)}
*/
public static void setSkinCacheDir(Path skinCacheDirectory) {
HttpTextureUtil.defaultCacheDir = skinCacheDirectory.toFile();
}
/**
* 23w42a ~ 25w33a
* Invoked from {@link SkinManager#getOrLoad(GameProfile)}
*
* 25w34a+
* Invoked from {@link SkinManager#get(GameProfile)}
*/
public static Property createProperty(Property property) {
return property == null ? new Property(null, null) : property;
}
/**
* 1.20.1-
* Invoked from {@link SkinManager#loadSkin(MinecraftProfileTexture, MinecraftProfileTexture.Type, SkinManager$SkinAvailableCallback)}
*
* 23w31a+
* Invoked from {@link SkinManager$TextureCache#registerTexture(MinecraftProfileTexture)}
*/
public static Object[] createThreadDownloadImageData(ImmutableList<Object> list, MinecraftProfileTexture profileTexture, MinecraftProfileTexture.Type textureType) {
Object[] params = list.toArray();
if (profileTexture instanceof FakeMinecraftProfileTexture) {
FakeMinecraftProfileTexture fakeProfileTexture = (FakeMinecraftProfileTexture) profileTexture;
File cacheFile = fakeProfileTexture.getCacheFile();
if (params.length == 4) {
if (params[3] instanceof Boolean) { // 24w46a+
if ((Boolean) params[3]) {
params[0] = FakeResourceLocation.create((ResourceLocation) params[0], fakeProfileTexture);
}
params[1] = cacheFile.toPath();
} else { // 19w37a-
params[0] = cacheFile;
params[3] = new BaseBuffer((Runnable) params[3], textureType, fakeProfileTexture);
}
} else if (params.length == 5) { // 19w38a ~ 24w45a
params[0] = cacheFile;
params[3] = true;
params[4] = new BaseBuffer((Runnable) params[4], textureType, fakeProfileTexture);
}
}
return params;
}
/**
* 1.20.1-
* Invoked from {@link SkinManager#loadProfileTextures(GameProfile, SkinManager$SkinAvailableCallback, boolean)}
*/
public static void loadProfileTextures(Runnable runnable) {
CustomSkinLoader.loadProfileTextures(runnable);
}
/**
* 23w31a+
* Invoked from {@link SkinManager$1#load(SkinManager$CacheKey)}
*/
public static Executor loadProfileTextures(Executor executor) {
return CustomSkinLoader.THREAD_POOL;
}
/**
* 1.20.1-
* Invoked from {@link SkinManager#func_210275_a(GameProfile, boolean, SkinManager$SkinAvailableCallback)}
*/
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getUserProfile(MinecraftSessionService sessionService, GameProfile profile, boolean requireSecure) {
return ModelManager0.fromUserProfile(CustomSkinLoader.loadProfile(profile));
}
/**
* 1.20.1-
* Invoked from {@link SkinManager#func_210276_a(Map, SkinManager$SkinAvailableCallback)}
*/
public static void loadElytraTexture(SkinManager skinManager, Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map, SkinManager$SkinAvailableCallback skinAvailableCallback) {
for (int i = 2; i < MinecraftProfileTexture.Type.values().length; i++) {
MinecraftProfileTexture.Type type = MinecraftProfileTexture.Type.values()[i];
if (map.containsKey(type)) {
skinManager.loadSkin(map.get(type), type, skinAvailableCallback);
}
}
}
/**
* 1.20.1-
* Invoked from {@link SkinManager#loadSkinFromCache(GameProfile)}
*/
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadSkinFromCache(GameProfile profile) {
return CustomSkinLoader.loadProfileFromCache(profile);
}
/**
* 23w31a ~ 23w41a
* Invoked from {@link SkinManager$1#lambda$load$0(MinecraftSessionService, GameProfile)}
*/
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> loadSkinFromCache(MinecraftSessionService sessionService, GameProfile profile, boolean requireSecure) {
return getUserProfile(sessionService, profile, requireSecure);
}
/**
* 23w42a ~ 25w33a
* Invoked from {@link SkinManager$1#lambda$load$0(SkinManager$CacheKey, MinecraftSessionService)}
*
* 25w34a+
* Invoked from {@link SkinManager$1#lambda$load$0(SkinManager$CacheKey, Services)}
*/
public static Object loadSkinFromCache(MinecraftSessionService sessionService, Property property, SkinManager$CacheKey cacheKey) {
if (cacheKey instanceof FakeCacheKey) {
return FakeCacheKey.createMinecraftProfileTextures(loadSkinFromCache(sessionService, ((FakeCacheKey) cacheKey).profile(), false));
}
return sessionService.unpackTextures(property);
}
public static class BaseBuffer implements IImageBuffer {
private IImageBuffer buffer;
private final Runnable callback;
private final FakeMinecraftProfileTexture texture;
public BaseBuffer(Runnable callback, MinecraftProfileTexture.Type type, FakeMinecraftProfileTexture texture) {
this.callback = callback;
this.texture = texture;
switch (type) {
case SKIN: this.buffer = new FakeSkinBuffer(); break;
case CAPE: this.buffer = new FakeCapeBuffer(); break;
}
}
@Override
public NativeImage func_195786_a(NativeImage image) {
return this.buffer instanceof FakeSkinBuffer ? this.buffer.func_195786_a(image) : image;
}
@Override
public BufferedImage parseUserSkin(BufferedImage image) {
return this.buffer instanceof FakeSkinBuffer ? this.buffer.parseUserSkin(image) : image;
}
@Override
public void skinAvailable() {
if (this.buffer != null) {
this.buffer.skinAvailable();
if (this.buffer instanceof FakeSkinBuffer) {
judgeType(this.texture, () -> ((FakeSkinBuffer) this.buffer).judgeType());
}
}
if (this.callback != null) {
this.callback.run();
}
}
public static void judgeType(FakeMinecraftProfileTexture texture, Supplier<String> type) {
if (shouldJudgeType(texture)) {
//Auto judge skin type
texture.setModel(type.get());
}
}
private static boolean shouldJudgeType(FakeMinecraftProfileTexture texture) {
return texture != null && "auto".equals(texture.getMetadata("model", false));
}
}
public static class FakeCacheKey extends SkinManager$CacheKey {
private final GameProfile profile;
public FakeCacheKey(UUID uuid, Property property, GameProfile profile) {
super(uuid, property);
this.profile = profile;
}
public GameProfile profile() {
return this.profile;
}
/**
* 23w42a ~ 25w33a
* Invoked from {@link SkinManager#getOrLoad(GameProfile)}
*
* 25w34a+
* Invoked from {@link SkinManager#get(GameProfile)}
*/
public static SkinManager$CacheKey createFakeCacheKey(UUID uuid, Property property, GameProfile profile) {
return new FakeCacheKey(uuid, property, profile);
}
public static Object createMinecraftProfileTextures(Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures) {
return new MinecraftProfileTextures(textures.get(MinecraftProfileTexture.Type.SKIN), textures.get(MinecraftProfileTexture.Type.CAPE), textures.get(MinecraftProfileTexture.Type.ELYTRA), SignatureState.SIGNED);
}
}
}
@@ -0,0 +1,30 @@
package customskinloader.fake.itf;
import java.io.InputStream;
import java.util.Optional;
import net.minecraft.client.resources.IResource;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
public class FakeInterfaceManager {
public static InputStream IResource_getInputStream(Object resource) {
return ((IFakeIResource.V2) resource).open();
}
public static Optional<IResource> IResourceManager_getResource(Object resourceManager, ResourceLocation location) {
return ((IFakeIResourceManager) resourceManager).getResource(location);
}
public static IResourceManager Minecraft_getResourceManager(Object minecraft) {
return (IResourceManager) ((IFakeMinecraft) minecraft).func_195551_G();
}
public static int NativeImage_getPixel(Object nativeImage, int x, int y) {
return ((IFakeNativeImage) nativeImage).getPixel(x, y);
}
public static void NativeImage_setPixel(Object nativeImage, int x, int y, int color) {
((IFakeNativeImage) nativeImage).setPixel(x, y, color);
}
}
@@ -0,0 +1,10 @@
package customskinloader.fake.itf;
import net.minecraft.client.renderer.IImageBuffer;
public interface IFakeIImageBuffer extends Runnable {
@Override
default void run() {
((IImageBuffer) this).skinAvailable();
}
}
@@ -0,0 +1,22 @@
package customskinloader.fake.itf;
import java.io.InputStream;
import net.minecraft.client.resources.IResource;
/** {@link IResource} is no longer an interface since 22w14a */
public interface IFakeIResource {
// 1.13.2 ~ 22w13a
interface V1 {
default InputStream func_199027_b() {
return ((IResource) this).getInputStream();
}
}
// 22w14a+
interface V2 {
default InputStream open() {
return ((IFakeIResource.V1) this).func_199027_b();
}
}
}
@@ -0,0 +1,19 @@
package customskinloader.fake.itf;
import java.util.Optional;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.resources.IResource;
import net.minecraft.util.ResourceLocation;
public interface IFakeIResourceManager {
// 1.13.2 ~ 22w13a
default IResource func_199002_a(ResourceLocation location) {
return (IResource) ((IResourceManager) this).getResource(location);
}
// 22w14a+
default Optional getResource(ResourceLocation location) {
return Optional.ofNullable(this.func_199002_a(location));
}
}
@@ -0,0 +1,11 @@
package customskinloader.fake.itf;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.IResourceManager;
public interface IFakeMinecraft {
// 1.13.2+
default IResourceManager func_195551_G() {
return (IResourceManager) ((Minecraft) this).getResourceManager();
}
}
@@ -0,0 +1,13 @@
package customskinloader.fake.itf;
import net.minecraft.client.renderer.texture.NativeImage;
public interface IFakeNativeImage {
default int getPixel(int x, int y) {
return ((NativeImage) this).func_195709_a(x, y);
}
default void setPixel(int x, int y, int color) {
((NativeImage) this).func_195700_a(x, y, color);
}
}
@@ -1,11 +1,16 @@
package customskinloader.fake.texture;
import java.awt.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
public class FakeBufferedImage implements FakeImage {
private BufferedImage image;
private Graphics graphics;
private int ratio;
public FakeBufferedImage(int width, int height) {
this(new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB));
@@ -25,6 +30,20 @@ public class FakeBufferedImage implements FakeImage {
return new FakeBufferedImage(width, height);
}
public FakeImage createImage(InputStream is) throws IOException {
return new FakeBufferedImage(ImageIO.read(is));
}
@Override
public int getRatio() {
return this.ratio;
}
@Override
public void setRatio(int ratio) {
this.ratio = ratio;
}
public int getWidth() {
return image.getWidth();
}
@@ -1,8 +1,17 @@
package customskinloader.fake.texture;
import java.io.IOException;
import java.io.InputStream;
public interface FakeImage {
FakeImage createImage(int width, int height);
FakeImage createImage(InputStream is) throws IOException;
int getRatio();
void setRatio(int ratio);
int getWidth();
int getHeight();
@@ -1,9 +1,13 @@
package customskinloader.fake.texture;
import java.io.InputStream;
import customskinloader.fake.itf.FakeInterfaceManager;
import net.minecraft.client.renderer.texture.NativeImage;
public class FakeNativeImage implements FakeImage {
private NativeImage image;
private int ratio;
public FakeNativeImage(int width, int height) {
this(new NativeImage(width, height, true));
@@ -21,6 +25,20 @@ public class FakeNativeImage implements FakeImage {
return new FakeNativeImage(width, height);
}
public FakeImage createImage(InputStream is) {
return new FakeNativeImage(NativeImage.func_195713_a(is));
}
@Override
public int getRatio() {
return this.ratio;
}
@Override
public void setRatio(int ratio) {
this.ratio = ratio;
}
public int getWidth() {
return image.func_195702_a();
}
@@ -30,11 +48,11 @@ public class FakeNativeImage implements FakeImage {
}
public int getRGBA(int x, int y) {
return image.func_195709_a(x, y);
return FakeInterfaceManager.NativeImage_getPixel(image, x, y);
}
public void setRGBA(int x, int y, int rgba) {
image.func_195700_a(x, y, rgba);
FakeInterfaceManager.NativeImage_setPixel(image, x, y, rgba);
}
public void copyImageData(FakeImage image) {
@@ -51,5 +69,24 @@ public class FakeNativeImage implements FakeImage {
}
public void close() {
image.close();
}
public static class Extended extends NativeImage {
public static NativeImage create(FakeNativeImage fakeImage) {
return new FakeNativeImage.Extended(fakeImage);
}
private final FakeNativeImage fakeImage;
public Extended(FakeNativeImage fakeImage) {
super(fakeImage.getWidth(), fakeImage.getHeight(), true);
this.func_195703_a(fakeImage.getImage());
this.fakeImage = fakeImage;
}
public FakeNativeImage getFakeImage() {
return this.fakeImage;
}
}
}
@@ -0,0 +1,22 @@
package customskinloader.fake.texture;
import customskinloader.fake.FakeMinecraftProfileTexture;
import net.minecraft.util.ResourceLocation;
public class FakeResourceLocation extends ResourceLocation {
public static FakeResourceLocation create(ResourceLocation location, FakeMinecraftProfileTexture texture) {
String[] s = location.toString().split(":", 2);
return new FakeResourceLocation(s[0], s[1], texture);
}
private final FakeMinecraftProfileTexture texture;
public FakeResourceLocation(String domain, String path, FakeMinecraftProfileTexture texture) {
super(domain, path);
this.texture = texture;
}
public FakeMinecraftProfileTexture getTexture() {
return this.texture;
}
}
@@ -0,0 +1,53 @@
package customskinloader.fake.texture;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import customskinloader.fake.FakeCapeBuffer;
import customskinloader.fake.FakeSkinBuffer;
import customskinloader.fake.FakeSkinManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.NativeImage;
import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.TextureContents;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
// 24w46a+
public class FakeThreadDownloadImageData extends SimpleTexture {
private FakeCapeBuffer buffer;
private FakeNativeImage image;
public static Function<NativeImage, CompletableFuture<?>> createTexture(Function<NativeImage, CompletableFuture<?>> function, ResourceLocation location, boolean bl) {
return bl ? _image -> {
if (location instanceof FakeResourceLocation && _image instanceof FakeNativeImage.Extended) {
FakeSkinManager.BaseBuffer.judgeType(((FakeResourceLocation) location).getTexture(), () -> FakeSkinBuffer.judgeType0(((FakeNativeImage.Extended) _image).getFakeImage()));
}
return function.apply(_image);
} : _image -> function.apply(_image).thenApply(_location -> {
Minecraft.getMinecraft().getTextureManager().registerAndLoad(location, new FakeThreadDownloadImageData(location, copyImage(new FakeNativeImage(_image))));
return _location;
});
}
public FakeThreadDownloadImageData(ResourceLocation location, FakeNativeImage image) {
super(location);
this.buffer = new FakeCapeBuffer();
this.image = image;
}
@Override
public TextureContents loadContents(IResourceManager resourceManager) {
this.image = (FakeNativeImage) this.buffer.parseUserSkin(this.image);
return new TextureContents(copyImage(this.image).getImage(), null);
}
/**
* Protects cached NativeImage instances from external interference (e.g. accidental close operations). All lifecycle management is handled internally by this cache.
*/
private static FakeNativeImage copyImage(FakeNativeImage from) {
FakeNativeImage local = (FakeNativeImage) from.createImage(from.getWidth(), from.getHeight());
local.copyImageData(from);
return local;
}
}
@@ -0,0 +1,112 @@
package customskinloader.loader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.response.MinecraftTexturesPayload;
import com.mojang.util.UUIDTypeAdapter;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import customskinloader.utils.TextureUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
public class GameProfileLoader implements ICustomSkinLoaderPlugin, ProfileLoader.IProfileLoader {
@Override
public ProfileLoader.IProfileLoader getProfileLoader() {
return this;
}
@Override
public List<IDefaultProfile> getDefaultProfiles() {
return Lists.newArrayList(new ServerGameProfile(this));
}
public static class ServerGameProfile implements ICustomSkinLoaderPlugin.IDefaultProfile {
protected final GameProfileLoader loader;
public ServerGameProfile(GameProfileLoader loader) {
this.loader = loader;
}
@Override
public String getName() {
return "GameProfile";
}
@Override
public int getPriority() {
return 50;
}
@Override
public void updateSkinSiteProfile(SkinSiteProfile ssp) {
ssp.type = this.loader.getName();
}
}
@Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception {
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = getTextures(gameProfile);
if (!map.isEmpty()) {
CustomSkinLoader.logger.info("Default profile will be used.");
return ModelManager0.toUserProfile(map);
}
return null;
}
@Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return true;
}
@Override
public String getName() {
return "GameProfile";
}
@Override
public void init(SkinSiteProfile ssp) {
}
public static final Gson GSON = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create();
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getTextures(GameProfile gameProfile) {
if (gameProfile == null) {
return Maps.newHashMap();
}
Property textureProperty = Iterables.getFirst(TextureUtil.AuthlibField.GAME_PROFILE_PROPERTIES.<PropertyMap>get(gameProfile).get("textures"), null);
if (textureProperty == null) {
return Maps.newHashMap();
}
String value = TextureUtil.AuthlibField.PROPERTY_VALUE.get(textureProperty);
if (StringUtils.isBlank(value)) {
return Maps.newHashMap();
}
String json = new String(Base64.decodeBase64(value), StandardCharsets.UTF_8);
MinecraftTexturesPayload result = GSON.fromJson(json, MinecraftTexturesPayload.class);
if (result == null) {
return Maps.newHashMap();
}
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures = TextureUtil.AuthlibField.MINECRAFT_TEXTURES_PAYLOAD_TEXTURES.get(result);
if (textures == null) {
return Maps.newHashMap();
}
return textures;
}
}
@@ -0,0 +1,167 @@
package customskinloader.loader;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import com.mojang.authlib.GameProfile;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpUtil0;
import customskinloader.utils.TextureUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
public class JsonAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.IProfileLoader {
public interface IJsonAPI {
List<IDefaultProfile> getDefaultProfiles(JsonAPILoader loader);
String toJsonUrl(String root, String username);
default String getPayload(SkinSiteProfile ssp) {
return null;
}
/**
* get JSON API payload, which will make a POST request
*
* @param ssp skin site profile
* @param username username
* @return JSON payload
* @since 14.16
*/
default String getPayload(SkinSiteProfile ssp, String username) {
return getPayload(ssp);
}
UserProfile toUserProfile(String root, String json, boolean local);
String getName();
}
public static class ErrorProfile {
public int errno;
public String msg;
}
private final IJsonAPI jsonAPI;
public JsonAPILoader(IJsonAPI jsonAPI) {
this.jsonAPI = jsonAPI;
}
// === ICustomSkinLoaderPlugin ===
@Override
public ProfileLoader.IProfileLoader getProfileLoader() {
return this;
}
@Override
public List<IDefaultProfile> getDefaultProfiles() {
return this.jsonAPI.getDefaultProfiles(this);
}
public abstract static class DefaultProfile implements ICustomSkinLoaderPlugin.IDefaultProfile {
protected final JsonAPILoader loader;
public DefaultProfile(JsonAPILoader loader) {
this.loader = loader;
}
@Override
public void updateSkinSiteProfile(SkinSiteProfile ssp) {
ssp.type = this.loader.getName();
ssp.root = this.getRoot();
}
public abstract String getRoot();
}
// === IProfileLoader ===
@Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) throws Exception {
String username = TextureUtil.AuthlibField.GAME_PROFILE_NAME.get(gameProfile);
if (StringUtils.isEmpty(ssp.root)) {
CustomSkinLoader.logger.info("Root not defined.");
return null;
}
boolean local = HttpUtil0.isLocal(ssp.root);
String jsonUrl = this.jsonAPI.toJsonUrl(ssp.root, username);
//Some API like MinecraftCapesAPI won't load profile at sometime
if (jsonUrl == null) {
CustomSkinLoader.logger.info("Profile url not found.");
return null;
}
String json;
if (local) {
File jsonFile = new File(CustomSkinLoader.DATA_DIR, jsonUrl);
if (!jsonFile.exists()) {
CustomSkinLoader.logger.info("Profile File not found.");
return null;
}
json = IOUtils.toString(Files.newInputStream(jsonFile.toPath()), StandardCharsets.UTF_8);
} else {
try {
HttpRequestUtil.HttpResponce responce = HttpRequestUtil
.makeHttpRequest(new HttpRequestUtil.HttpRequest(jsonUrl).setCacheTime(90)
.setUserAgent(ssp.userAgent).setPayload(this.jsonAPI.getPayload(ssp, username)));
json = responce.content;
} catch (ProfileNotFoundException ignored) {
CustomSkinLoader.logger.info("Profile not found.");
return null;
}
}
if (json == null || json.equals("")) {
CustomSkinLoader.logger.info("Profile not found.");
return null;
}
ErrorProfile profile = CustomSkinLoader.GSON.fromJson(json, ErrorProfile.class);
if (profile.errno != 0) {
CustomSkinLoader.logger.info("Error " + profile.errno + ": " + profile.msg);
return null;
}
UserProfile p = this.jsonAPI.toUserProfile(ssp.root, json, local);
if (p == null || p.isEmpty()) {
CustomSkinLoader.logger.info("Both skin and cape not found.");
return null;
} else {
return p;
}
}
@Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return !StringUtils.isNoneEmpty(ssp0.root) || ssp0.root.equalsIgnoreCase(ssp1.root);
}
@Override
public String getName() {
return this.jsonAPI.getName();
}
@Override
public void init(SkinSiteProfile ssp) {
if (HttpUtil0.isLocal(ssp.root)) {
File f = new File(ssp.root);
if (!f.exists())
//noinspection ResultOfMethodCallIgnored
f.mkdirs();
}
}
/**
* When getting payload, this exception can end skin loading
* @since 14.16
*/
public static class ProfileNotFoundException extends RuntimeException {
}
}
@@ -0,0 +1,236 @@
package customskinloader.loader;
import java.io.File;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import com.google.common.collect.Lists;
import com.mojang.authlib.GameProfile;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpUtil0;
import customskinloader.utils.TextureUtil;
public class LegacyLoader implements ICustomSkinLoaderPlugin, ProfileLoader.IProfileLoader {
@Override
public ProfileLoader.IProfileLoader getProfileLoader() {
return this;
}
@Override
public List<IDefaultProfile> getDefaultProfiles() {
return Lists.newArrayList(new LocalSkin(this),
getCapeProfile(this, "OptiFine", "https://optifine.net/capes/{USERNAME}.png", 810),
getCapeProfile(this, "CloakPlus", "http://161.35.130.99/capes/{USERNAME}.png", 840),
//getCapeProfile(this, "LabyMod", "https://dl.labymod.net/capes/{STANDARD_UUID}", 850),
getCapeProfile(this, "Cosmetica", "https://api.cosmetica.cc/get/cloak?username={USERNAME}&uuid={STANDARD_UUID}&nothirdparty", 860)
);
}
public abstract static class DefaultProfile implements ICustomSkinLoaderPlugin.IDefaultProfile {
protected final LegacyLoader loader;
public DefaultProfile(LegacyLoader loader) {
this.loader = loader;
}
@Override
public void updateSkinSiteProfile(SkinSiteProfile ssp) {
ssp.type = this.loader.getName();
if (ssp.checkPNG == null) {
ssp.checkPNG = false;
}
if (ssp.model == null) {
ssp.model = "auto";
}
//Set texture url when it is empty
//Remote texture url could be changed, it will be auto updated here
if (ssp.skin == null || !HttpUtil0.isLocal(this.getSkinRoot())) {
ssp.skin = this.getSkinRoot();
}
if (ssp.cape == null || !HttpUtil0.isLocal(this.getCapeRoot())) {
ssp.cape = this.getCapeRoot();
}
if (ssp.elytra == null || !HttpUtil0.isLocal(this.getElytraRoot())) {
ssp.elytra = this.getElytraRoot();
}
}
public abstract String getSkinRoot();
public abstract String getCapeRoot();
public abstract String getElytraRoot();
}
public static class LocalSkin extends LegacyLoader.DefaultProfile {
public LocalSkin(LegacyLoader loader) {
super(loader);
}
@Override
public String getName() {
return "LocalSkin";
}
@Override
public int getPriority() {
return 710;
}
@Override
public String getSkinRoot() {
return "LocalSkin/skins/{USERNAME}.png";
}
@Override
public String getCapeRoot() {
return "LocalSkin/capes/{USERNAME}.png";
}
@Override
public String getElytraRoot() {
return "LocalSkin/elytras/{USERNAME}.png";
}
}
/**
* Get cape Profile¬
*
* @since 14.16
*/
public static LegacyLoader.DefaultProfile getCapeProfile(LegacyLoader loader, String name, String capeRoot, int priority) {
return new DefaultProfile(loader) {
@Override
public String getSkinRoot() {
return null;
}
@Override
public String getCapeRoot() {
return capeRoot;
}
@Override
public String getElytraRoot() {
return null;
}
@Override
public String getName() {
return name;
}
@Override
public int getPriority() {
return priority;
}
};
}
public static final String USERNAME_PLACEHOLDER = "{USERNAME}";
public static final String UUID_PLACEHOLDER = "{UUID}";
/**
* Mojang UUID with -
*
* @since 14.16
*/
public static final String STANDARD_UUID_PLACEHOLDER = "{STANDARD_UUID}";
@Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) {
UserProfile profile = new UserProfile();
//Try to load all textures
getTextureUrl(ssp, gameProfile, ssp.skin, it -> {
profile.skinUrl = it;
profile.model = ssp.model;
});
getTextureUrl(ssp, gameProfile, ssp.cape, it -> profile.capeUrl = it);
getTextureUrl(ssp, gameProfile, ssp.elytra, it -> profile.elytraUrl = it);
if (profile.isEmpty()) {
CustomSkinLoader.logger.info("No texture could be found.");
return null;
}
return profile;
}
private void getTextureUrl(SkinSiteProfile ssp, GameProfile gameProfile, String baseUrl, Consumer<String> onSuccess) {
//Base URL is empty
if (baseUrl == null || baseUrl.isEmpty()) {
return;
}
String url = expandURL(baseUrl, TextureUtil.AuthlibField.GAME_PROFILE_NAME.get(gameProfile));
//No texture can be loaded
if (url == null) {
return;
}
//Local texture file logic
if (HttpUtil0.isLocal(url)) {
File file = new File(CustomSkinLoader.DATA_DIR, url);
if (file.exists() && file.isFile()) {
String fakeUrl = HttpTextureUtil.getLocalLegacyFakeUrl(url,
HttpTextureUtil.getHash(url, file.length(), file.lastModified()));
onSuccess.accept(fakeUrl);
}
return;
}
//Remote texture logic
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(url)
.setUserAgent(ssp.userAgent).setCheckPNG(ssp.checkPNG != null && ssp.checkPNG).setLoadContent(false));
if (responce.success) {
onSuccess.accept(HttpTextureUtil.getLegacyFakeUrl(url));
}
}
@Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return Objects.equals(ssp0.skin, ssp1.skin) && Objects.equals(ssp0.cape, ssp1.cape) &&
Objects.equals(ssp0.elytra, ssp1.elytra);
}
@Override
public String getName() {
return "Legacy";
}
@Override
public void init(SkinSiteProfile ssp) {
initFolder(ssp.skin);
initFolder(ssp.cape);
initFolder(ssp.elytra);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void initFolder(String target) {
//Only local skin should init folder
if (!HttpUtil0.isLocal(target)) {
return;
}
String file = target.replace(USERNAME_PLACEHOLDER, "init");
File folder = new File(CustomSkinLoader.DATA_DIR, file).getParentFile();
if (folder != null && !folder.exists()) {
folder.mkdirs();
}
}
private String expandURL(String url, String username) {
String t = url.replace(USERNAME_PLACEHOLDER, username);
if (!t.contains(UUID_PLACEHOLDER) && !t.contains(STANDARD_UUID_PLACEHOLDER)) {
return t;
}
String uuid = MojangAPILoader.getMojangUuidByUsername(username, true);
//If Mojang uuid not found, won't load the texture
if (uuid == null) {
return null;
}
String styledUuid = uuid.replace("-", "");
return t.replace(UUID_PLACEHOLDER, styledUuid).replace(STANDARD_UUID_PLACEHOLDER, uuid);
}
}
@@ -0,0 +1,189 @@
package customskinloader.loader;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.Lists;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.TextureUtil;
import org.apache.commons.lang3.StringUtils;
public class MojangAPILoader implements ICustomSkinLoaderPlugin, ProfileLoader.IProfileLoader {
@Override
public ProfileLoader.IProfileLoader getProfileLoader() {
return this;
}
@Override
public List<IDefaultProfile> getDefaultProfiles() {
return Lists.newArrayList(new Mojang(this));
}
public abstract static class DefaultProfile implements ICustomSkinLoaderPlugin.IDefaultProfile {
protected final MojangAPILoader loader;
public DefaultProfile(MojangAPILoader loader) {
this.loader = loader;
}
@Override
public void updateSkinSiteProfile(SkinSiteProfile ssp) {
ssp.type = this.loader.getName();
ssp.apiRoot = this.getAPIRoot();
ssp.sessionRoot = this.getSessionRoot();
}
public abstract String getAPIRoot();
public abstract String getSessionRoot();
}
public static class Mojang extends MojangAPILoader.DefaultProfile {
public Mojang(MojangAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "Mojang";
}
@Override
public int getPriority() {
return 100;
}
@Override
public String getAPIRoot() {
return getMojangApiRoot();
}
@Override
public String getSessionRoot() {
return getMojangSessionRoot();
}
}
@Override
public UserProfile loadProfile(SkinSiteProfile ssp, GameProfile gameProfile) {
String username = TextureUtil.AuthlibField.GAME_PROFILE_NAME.get(gameProfile);
GameProfile newGameProfile = loadGameProfileCached(ssp.apiRoot, username);
if (newGameProfile == null) {
CustomSkinLoader.logger.info("Profile not found.(" + username + "'s profile not found.)");
return null;
}
newGameProfile = fillGameProfile(ssp.sessionRoot, newGameProfile);
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = GameProfileLoader.getTextures(newGameProfile);
if (!map.isEmpty()) {
return ModelManager0.toUserProfile(map);
}
CustomSkinLoader.logger.info("Profile not found.(" + username + " doesn't have skin/cape.)");
return null;
}
private static final Map<String, GameProfile> gameProfileCache = new ConcurrentHashMap<>();
public static GameProfile loadGameProfileCached(String apiRoot, String username) {
return gameProfileCache.computeIfAbsent(apiRoot + " " + username, ignored -> loadGameProfile(apiRoot, username));
}
//Username -> UUID
public static GameProfile loadGameProfile(String apiRoot, String username) {
//Doc (https://minecraft.wiki/w/Mojang_API#Query_player_UUIDs_in_batch)
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(apiRoot + "profiles/minecraft").setCacheTime(600).setPayload(GameProfileLoader.GSON.toJson(Collections.singletonList(username))));
if (StringUtils.isEmpty(responce.content)) {
return null;
}
MinecraftProfilePropertiesResponse[] profiles = GameProfileLoader.GSON.fromJson(responce.content, MinecraftProfilePropertiesResponse[].class);
if (profiles.length == 0) {
return null;
}
GameProfile gameProfile = createGameProfile(profiles[0]);
UUID id = TextureUtil.AuthlibField.GAME_PROFILE_ID.get(gameProfile);
if (id == null) {
return null;
}
return new GameProfile(id, TextureUtil.AuthlibField.GAME_PROFILE_NAME.get(gameProfile));
}
/**
* Get Mojang UUID by username.
*
* @param username username to query
* @param standard if - in UUID
* @return UUID in Mojang API style string. Returns {@code null} if username not found in Mojang API.
*/
public static String getMojangUuidByUsername(String username, boolean standard) {
GameProfile profile = loadGameProfileCached(getMojangApiRoot(), username);
if (profile == null) {
return null;
}
UUID id = TextureUtil.AuthlibField.GAME_PROFILE_ID.get(profile);
return standard ? id.toString() : TextureUtil.fromUUID(id);
}
//UUID -> Profile
public static GameProfile fillGameProfile(String sessionRoot, GameProfile profile) {
//Doc (https://minecraft.wiki/w/Mojang_API#Query_player's_skin_and_cape)
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(sessionRoot + "session/minecraft/profile/" + TextureUtil.fromUUID(TextureUtil.AuthlibField.GAME_PROFILE_ID.get(profile))).setCacheTime(90));
if (StringUtils.isEmpty(responce.content)) {
return profile;
}
return createGameProfile(GameProfileLoader.GSON.fromJson(responce.content, MinecraftProfilePropertiesResponse.class));
}
public static GameProfile createGameProfile(MinecraftProfilePropertiesResponse response) {
GameProfile profile = new GameProfile(TextureUtil.AuthlibField.MINECRAFT_PROFILE_PROPERTIES_RESPONSE_ID.get(response), TextureUtil.AuthlibField.MINECRAFT_PROFILE_PROPERTIES_RESPONSE_NAME.get(response));
PropertyMap map = TextureUtil.AuthlibField.MINECRAFT_PROFILE_PROPERTIES_RESPONSE_PROPERTIES.get(response);
if (map != null) {
TextureUtil.AuthlibField.PROPERTY_MAP_PROPERTIES.set(TextureUtil.AuthlibField.GAME_PROFILE_PROPERTIES.get(profile), TextureUtil.AuthlibField.PROPERTY_MAP_PROPERTIES.get(map));
}
return profile;
}
@Override
public boolean compare(SkinSiteProfile ssp0, SkinSiteProfile ssp1) {
return (!StringUtils.isNoneEmpty(ssp0.apiRoot) || ssp0.apiRoot.equalsIgnoreCase(ssp1.apiRoot)) || (!StringUtils.isNoneEmpty(ssp0.sessionRoot) || ssp0.sessionRoot.equalsIgnoreCase(ssp1.sessionRoot));
}
@Override
public String getName() {
return "MojangAPI";
}
@Override
public void init(SkinSiteProfile ssp) {
//Init default api & session root for Mojang API
if (ssp.apiRoot == null)
ssp.apiRoot = getMojangApiRoot();
if (ssp.sessionRoot == null)
ssp.sessionRoot = getMojangSessionRoot();
}
// Prevent authlib-injector (https://github.com/yushijinhun/authlib-injector) from modifying these strings
private static final String MOJANG_API_ROOT = "https://api{DO_NOT_MODIFY}.mojang.com/";
private static final String MOJANG_SESSION_ROOT = "https://sessionserver{DO_NOT_MODIFY}.mojang.com/";
public static String getMojangApiRoot() {
return MOJANG_API_ROOT.replace("{DO_NOT_MODIFY}", "");
}
public static String getMojangSessionRoot() {
return MOJANG_SESSION_ROOT.replace("{DO_NOT_MODIFY}", "");
}
}
@@ -0,0 +1,33 @@
package customskinloader.loader;
import java.util.HashMap;
import com.mojang.authlib.GameProfile;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.plugin.PluginLoader;
import customskinloader.profile.UserProfile;
public class ProfileLoader {
public static final HashMap<String, IProfileLoader> LOADERS = initLoaders();
private static HashMap<String, IProfileLoader> initLoaders() {
HashMap<String, ProfileLoader.IProfileLoader> profileLoaders = new HashMap<>();
for (ICustomSkinLoaderPlugin plugin : PluginLoader.PLUGINS) {
ProfileLoader.IProfileLoader profileLoader = plugin.getProfileLoader();
if (profileLoader != null) {
profileLoaders.put(profileLoader.getName().toLowerCase(), profileLoader);
CustomSkinLoader.logger.info("Add a profile loader: " + profileLoader.getName());
}
}
return profileLoaders;
}
public interface IProfileLoader {
UserProfile loadProfile(SkinSiteProfile ssp,GameProfile gameProfile) throws Exception;
boolean compare(SkinSiteProfile ssp0,SkinSiteProfile ssp1);
String getName();
void init(SkinSiteProfile ssp);
}
}
@@ -0,0 +1,144 @@
package customskinloader.loader.jsonapi;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import customskinloader.CustomSkinLoader;
import customskinloader.loader.JsonAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpTextureUtil;
import org.apache.commons.lang3.StringUtils;
public class CustomSkinAPI implements JsonAPILoader.IJsonAPI {
public static class LittleSkin extends JsonAPILoader.DefaultProfile {
public LittleSkin(JsonAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "LittleSkin";
}
@Override
public int getPriority() {
return 200;
}
@Override
public String getRoot() {
return "https://littleskin.cn/csl/";
}
}
public static class BlessingSkin extends JsonAPILoader.DefaultProfile {
public BlessingSkin(JsonAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "BlessingSkin";
}
@Override
public int getPriority() {
return 300;
}
@Override
public String getRoot() {
return "https://skin.prinzeugen.net/";
}
}
// // OneSkin has been removed temporarily
// public static class OneSkin extends JsonAPILoader.DefaultProfile {
// public OneSkin(JsonAPILoader loader) { super(loader); }
// @Override public String getName() { return "OneSkin"; }
// @Override public int getPriority() { return 500; }
// @Override public String getRoot() { return "http://fleey.cn/skin/skin_user/skin_json.php/"; }
// }
private static final String TEXTURES = "textures/";
private static final String SUFFIX = ".json";
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new LittleSkin(loader), new BlessingSkin(loader));
}
@Override
public String toJsonUrl(String root, String username) {
return root + username + SUFFIX;
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
CustomSkinAPIProfile profile = CustomSkinLoader.GSON.fromJson(json, CustomSkinAPIProfile.class);
UserProfile p = new UserProfile();
if (StringUtils.isNotBlank(profile.skin)) {
p.skinUrl = root + TEXTURES + profile.skin;
if (local)
p.skinUrl = HttpTextureUtil.getLocalFakeUrl(p.skinUrl);
}
if (StringUtils.isNotBlank(profile.cape)) {
p.capeUrl = root + TEXTURES + profile.cape;
if (local)
p.capeUrl = HttpTextureUtil.getLocalFakeUrl(p.capeUrl);
}
if (StringUtils.isNotBlank(profile.elytra)) {
p.elytraUrl = root + TEXTURES + profile.elytra;
if (local)
p.elytraUrl = HttpTextureUtil.getLocalFakeUrl(p.elytraUrl);
}
Map<String, String> textures = new LinkedHashMap<>();
if (profile.skins != null)
textures.putAll(profile.skins);
if (profile.textures != null)
textures.putAll(profile.textures);
if (textures.isEmpty())
return p;
boolean hasSkin = false;
for (String model : textures.keySet()) {
ModelManager0.Model enumModel = ModelManager0.getEnumModel(model);
if (enumModel == null || StringUtils.isEmpty(textures.get(model)))
continue;
if (ModelManager0.isSkin(enumModel))
if (hasSkin)
continue;
else
hasSkin = true;
String url = root + TEXTURES + textures.get(model);
if (local)
url = HttpTextureUtil.getLocalFakeUrl(url);
p.put(enumModel, url);
}
return p;
}
private static class CustomSkinAPIProfile {
public String username;
public LinkedHashMap<String, String> textures;
public LinkedHashMap<String, String> skins;
public String skin;
public String cape;
public String elytra;
}
@Override
public String getName() {
return "CustomSkinAPI";
}
}
@@ -1,20 +1,19 @@
package customskinloader.loader.jsonapi;
import java.io.File;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader;
import customskinloader.loader.JsonAPILoader.IJsonAPI;
import customskinloader.profile.UserProfile;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.utils.MinecraftUtil;
import org.apache.commons.io.FileUtils;
public class CustomSkinAPIPlus implements IJsonAPI {
public class CustomSkinAPIPlus extends CustomSkinAPI {
private static String clientID=null;
public CustomSkinAPIPlus(){
@@ -35,9 +34,10 @@ public class CustomSkinAPIPlus implements IJsonAPI {
}
}
}
@Override
public String toJsonUrl(String root, String username) {
return JsonAPILoader.Type.CustomSkinAPI.jsonAPI.toJsonUrl(root, username);
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList();
}
@Override
@@ -45,11 +45,6 @@ public class CustomSkinAPIPlus implements IJsonAPI {
return new Gson().toJson(new CustomSkinAPIPlusPayload());
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
return JsonAPILoader.Type.CustomSkinAPI.jsonAPI.toUserProfile(root, json, local);
}
@Override
public String getName() {
return "CustomSKinAPIPlus";
@@ -0,0 +1,80 @@
package customskinloader.loader.jsonapi;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.loader.JsonAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
public class ElyByAPI implements JsonAPILoader.IJsonAPI {
public static class ElyBy extends JsonAPILoader.DefaultProfile {
public ElyBy(JsonAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "ElyBy";
}
@Override
public int getPriority() {
return 400;
}
@Override
public String getRoot() {
return "http://skinsystem.ely.by/textures/";
}
}
public static class TLauncher extends JsonAPILoader.DefaultProfile {
public TLauncher(JsonAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "TLauncher";
}
@Override
public int getPriority() {
return 550;
}
@Override
public String getRoot() {
return "https://auth.tlauncher.org/skin/profile/texture/login/";
}
}
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new ElyBy(loader), new TLauncher(loader));
}
@Override
public String toJsonUrl(String root, String username) {
return root + username;
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> result = new Gson().fromJson(json, new TypeToken<Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>>() {
}.getType());
return ModelManager0.toUserProfile(result);
}
@Override
public String getName() {
return "ElyByAPI";
}
}
@@ -1,15 +1,44 @@
package customskinloader.loader.jsonapi;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import java.util.Map;
public class GlitchlessAPI implements JsonAPILoader.IJsonAPI {
public static class GlitchlessGames extends JsonAPILoader.DefaultProfile {
public GlitchlessGames(JsonAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "GlitchlessGames";
}
@Override
public int getPriority() {
return 700;
}
@Override
public String getRoot() {
return "https://games.glitchless.ru/api/minecraft/users/profiles/textures/?nickname=";
}
}
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new GlitchlessGames(loader));
}
@Override
public String toJsonUrl(String root, String username) {
return root + username;
@@ -24,11 +53,6 @@ public class GlitchlessAPI implements JsonAPILoader.IJsonAPI {
return ModelManager0.toUserProfile(result.textures);
}
@Override
public String getPayload(SkinSiteProfile ssp) {
return null;
}
@Override
public String getName() {
return "GlitchlessAPI";
@@ -0,0 +1,82 @@
package customskinloader.loader.jsonapi;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import customskinloader.loader.JsonAPILoader;
import customskinloader.loader.MojangAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.UserProfile;
import customskinloader.utils.TextureUtil;
import java.util.List;
public class MinecraftCapesAPI implements JsonAPILoader.IJsonAPI {
public static class MinecraftCapes extends JsonAPILoader.DefaultProfile {
public MinecraftCapes(JsonAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "MinecraftCapes";
}
@Override
public int getPriority() {
return 800;
}
@Override
public String getRoot() {
return "https://api.minecraftcapes.net/profile/";
}
}
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new MinecraftCapes(loader));
}
@Override
public String toJsonUrl(String root, String username) {
String uuid = MojangAPILoader.getMojangUuidByUsername(username, false);
//If uuid cannot be found, we won't load profile in this API.
if (uuid == null) {
return null;
}
//API url is `${root}${uuid}`
return root + uuid;
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
MinecraftCapesApiResponse result = new Gson().fromJson(json, MinecraftCapesApiResponse.class);
if (result.textures == null || result.textures.cape == null) {
return null;
}
UserProfile profile = new UserProfile();
profile.capeUrl = TextureUtil.parseBase64Texture(result.textures.cape);
return profile;
}
@Override
public String getName() {
return "MinecraftCapesAPI";
}
public static class MinecraftCapesApiResponse {
public boolean animatedCape;
public boolean capeGlint;
public boolean upsideDown;
public MinecraftCapesApiTexture textures;
public static class MinecraftCapesApiTexture {
public String cape;
public String ears;
}
}
}
@@ -0,0 +1,105 @@
package customskinloader.loader.jsonapi;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import customskinloader.CustomSkinLoader;
import customskinloader.loader.JsonAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.ModelManager0;
import customskinloader.profile.UserProfile;
import customskinloader.utils.HttpTextureUtil;
import org.apache.commons.lang3.StringUtils;
public class UniSkinAPI implements JsonAPILoader.IJsonAPI {
public static class SkinMe extends JsonAPILoader.DefaultProfile {
public SkinMe(JsonAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "SkinMe";
}
@Override
public int getPriority() {
return 500;
}
@Override
public String getRoot() {
return "http://www.skinme.cc/uniskin/";
}
}
private static final String TEXTURES = "textures/";
private static final String SUFFIX = ".json";
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new SkinMe(loader));
}
@Override
public String toJsonUrl(String root, String username) {
return root + username + SUFFIX;
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
UniSkinAPIProfile profile = CustomSkinLoader.GSON.fromJson(json, UniSkinAPIProfile.class);
UserProfile p = new UserProfile();
if (StringUtils.isNotBlank(profile.cape)) {
p.capeUrl = root + TEXTURES + profile.cape;
if (local)
p.capeUrl = HttpTextureUtil.getLocalFakeUrl(p.capeUrl);
}
if (profile.skins == null || profile.skins.isEmpty())
return p;
if (profile.model_preference == null || profile.model_preference.isEmpty())
return p;
boolean hasSkin = false;
for (String model : profile.model_preference) {
ModelManager0.Model enumModel = ModelManager0.getEnumModel(model);
if (enumModel == null || StringUtils.isEmpty(profile.skins.get(model)))
continue;
if (ModelManager0.isSkin(enumModel))
if (hasSkin)
continue;
else
hasSkin = true;
String url = root + TEXTURES + profile.skins.get(model);
if (local)
url = HttpTextureUtil.getLocalFakeUrl(url);
p.put(enumModel, url);
}
return p;
}
/**
* Json profile for UniSkinAPI
* <a href="https://github.com/RecursiveG/UniSkinMod/blob/master/src/main/java/org/devinprogress/uniskinmod/UniSkinApiProfile.java#L18-L22">Source Code</a>
*
* @author RecursiveG
*/
private static class UniSkinAPIProfile {
public String player_name;
public long last_update;
public List<String> model_preference;
public Map<String, String> skins;
public String cape;
}
@Override
public String getName() {
return "UniSkinAPI";
}
}
@@ -0,0 +1,110 @@
package customskinloader.loader.jsonapi;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import customskinloader.CustomSkinLoader;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.JsonAPILoader;
import customskinloader.loader.MojangAPILoader;
import customskinloader.plugin.ICustomSkinLoaderPlugin;
import customskinloader.profile.UserProfile;
import customskinloader.utils.TextureUtil;
import java.util.List;
/**
* Wynntils cape API
* <a href="https://wynntils.com/">Home</a>
* Test player: Cael
*
* @since 14.16
*/
public class WynntilsAPI implements JsonAPILoader.IJsonAPI {
public static class Wynntils extends JsonAPILoader.DefaultProfile {
public Wynntils(JsonAPILoader loader) {
super(loader);
}
@Override
public String getName() {
return "Wynntils";
}
@Override
public int getPriority() {
return 820;
}
@Override
public String getRoot() {
return "https://athena.wynntils.com/user/getInfo";
}
}
@Override
public List<ICustomSkinLoaderPlugin.IDefaultProfile> getDefaultProfiles(JsonAPILoader loader) {
return Lists.newArrayList(new Wynntils(loader));
}
@Override
public String toJsonUrl(String root, String username) {
return root;
}
@Override
public UserProfile toUserProfile(String root, String json, boolean local) {
WynntilsApiResponse result = new Gson().fromJson(json, WynntilsApiResponse.class);
if (result.user == null || result.user.cosmetics == null || result.user.cosmetics.texture == null) {
return null;
}
UserProfile profile = new UserProfile();
String fakeUrl = TextureUtil.parseBase64Texture(result.user.cosmetics.texture);
if (result.user.cosmetics.hasCape) {
profile.capeUrl = fakeUrl;
} else if (result.user.cosmetics.hasElytra) {
profile.elytraUrl = fakeUrl;
} else {
CustomSkinLoader.logger.warning("Illegal response found in Wynntils");
return null;
}
return profile;
}
@Override
public String getPayload(SkinSiteProfile ssp, String username) {
WynntilsApiRequest req = new WynntilsApiRequest();
req.uuid = MojangAPILoader.getMojangUuidByUsername(username, true);
if (req.uuid == null) {
throw new JsonAPILoader.ProfileNotFoundException();
}
return new Gson().toJson(req);
}
@Override
public String getName() {
return "WynntilsAPI";
}
public static class WynntilsApiRequest {
public String uuid;
}
public static class WynntilsApiResponse {
public User user;
public static class User {
public String accountType;
public Cosmetics cosmetics;
public static class Cosmetics {
public boolean hasCape;
public boolean hasElytra;
public boolean hasEars;
public String texture;
}
}
}
}
@@ -0,0 +1,44 @@
package customskinloader.log;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @since 14.16
*/
public class LogManager {
private static Path logFile;
private static Writer logWriter;
private static final Map<String, Logger> loggers = new ConcurrentHashMap<>();
public static void setLogFile(Path logFile) {
//Not updated
if (logFile == null || logFile.equals(LogManager.logFile)) {
return;
}
LogManager.logFile = logFile;
try {
//Close previous writer
if (logWriter != null) {
logWriter.close();
}
//Set new writer
Files.createDirectories(logFile.getParent());
logWriter = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
loggers.forEach((k, v) -> v.setWriter(logWriter));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Logger getLogger(String loggerName) {
return loggers.computeIfAbsent(loggerName,
it -> new Logger(logWriter, "CustomSkinLoader " + loggerName));
}
}
@@ -0,0 +1,185 @@
package customskinloader.log;
import javax.annotation.Nullable;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* the Logger
* Moved from <code>customskinloader.Logger</code>
*
* @since 14.16
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public class Logger {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* A copy of <code>Config.enableLogStdOut</code>.
* Because <code>Config.loadConfig0()</code> will use <code>Logger.log()</code>,
* which means cannot access <code>CustomSkinLoader.config</code> here.
*
* @see customskinloader.config.Config#enableLogStdOut
* @since 14.15
*/
public boolean enableLogStdOut = false;
public enum Level {
DEBUG("DEBUG", false),
INFO("INFO", true),
WARNING("WARNING", true);
final String name;
final boolean display;
Level(String name, boolean display) {
this.name = name;
this.display = display;
}
public String getName() {
return name;
}
public boolean display() {
return display;
}
}
private Writer writer = null;
public void setWriter(Writer writer) {
this.writer = writer;
}
public Logger() {
//Logger isn't created.
}
public Logger(String logFile) {
this(new File(logFile));
}
public Logger(File logFile) {
this(logFile, "Unknown");
}
/**
* Create Logger with File
*
* @since 14.16
*/
public Logger(File logFile, String loggerName) {
this.loggerName = loggerName;
try {
if (!logFile.getParentFile().exists()) {
logFile.getParentFile().mkdirs();
}
if (!logFile.exists()) {
logFile.createNewFile();
}
writer = new BufferedWriter(new OutputStreamWriter(
Files.newOutputStream(logFile.toPath()), StandardCharsets.UTF_8));
System.out.println("Log Path: " + logFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create Logger with special Writer
*
* @since 14.16
*/
public Logger(@Nullable Writer writer, String loggerName) {
this.loggerName = loggerName;
this.writer = writer;
}
/**
* Logger name in log
*
* @since 14.16
*/
String loggerName;
public void close() {
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Judge if a level can be printed to standard output(System.out) with config.
*
* @param level log level
* @return true - print
*/
private boolean canPrintToStdOut(Level level) {
return level.display() && enableLogStdOut;
}
public void log(Level level, String msg) {
//When it neither be printed to standard output nor write to file
if (!canPrintToStdOut(level) && writer == null) {
return;
}
//Format, print and write
String sb = String.format("[%s] [%s/%s] [%s]: %s",
DATE_FORMAT.format(new Date()), Thread.currentThread().getName(), level.getName(), loggerName, msg);
if (canPrintToStdOut(level)) {
System.out.println(sb);
}
if (writer == null) {
return;
}
try {
String sb2 = String.format("%s\r\n", sb);
writer.write(sb2);//Writer.write has lock
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public void debug(String msg) {
log(Level.DEBUG, msg);
}
public void debug(String format, Object... objs) {
debug(String.format(format, objs));
}
public void info(String msg) {
log(Level.INFO, msg);
}
public void info(String format, Object... objs) {
info(String.format(format, objs));
}
public void warning(String msg) {
log(Level.WARNING, msg);
}
public void warning(String format, Object... objs) {
warning(String.format(format, objs));
}
public void warning(Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log(Level.WARNING, "Exception: " + sw);
}
}
@@ -0,0 +1,35 @@
package customskinloader.plugin;
import java.util.List;
import customskinloader.config.SkinSiteProfile;
import customskinloader.loader.ProfileLoader;
public interface ICustomSkinLoaderPlugin {
/**
* @return return a non-null value if need to add a new profile loader, otherwise return null.
*/
ProfileLoader.IProfileLoader getProfileLoader();
/**
* @return the default implementations which import by {@link ICustomSkinLoaderPlugin#getProfileLoader()}.
*/
List<IDefaultProfile> getDefaultProfiles();
interface IDefaultProfile {
/**
* @return the name of {@link SkinSiteProfile#name}.
*/
String getName();
/**
* @return the lower the number, the first to load.
*/
int getPriority();
/**
* Complete the {@link SkinSiteProfile} from config and write to config.
*/
void updateSkinSiteProfile(SkinSiteProfile ssp);
}
}
@@ -0,0 +1,57 @@
package customskinloader.plugin;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.ServiceLoader;
import com.google.common.collect.Lists;
import customskinloader.CustomSkinLoader;
import customskinloader.loader.GameProfileLoader;
import customskinloader.loader.JsonAPILoader;
import customskinloader.loader.LegacyLoader;
import customskinloader.loader.MojangAPILoader;
import customskinloader.loader.jsonapi.*;
import org.apache.commons.io.FileUtils;
public class PluginLoader {
public static final ICustomSkinLoaderPlugin[] DEFAULT_PLUGINS = new ICustomSkinLoaderPlugin[]{
new GameProfileLoader(),
new MojangAPILoader(),
new LegacyLoader(),
new JsonAPILoader(new CustomSkinAPI()),
new JsonAPILoader(new CustomSkinAPIPlus()),
new JsonAPILoader(new UniSkinAPI()),
new JsonAPILoader(new ElyByAPI()),
new JsonAPILoader(new GlitchlessAPI()),
new JsonAPILoader(new MinecraftCapesAPI()),
new JsonAPILoader(new WynntilsAPI()),
};
public static final ArrayList<ICustomSkinLoaderPlugin> PLUGINS = loadPlugins();
private static ArrayList<ICustomSkinLoaderPlugin> loadPlugins() {
File pluginsDir = new File(CustomSkinLoader.DATA_DIR, "Plugins");
ArrayList<URL> urls = new ArrayList<>();
if (!pluginsDir.isDirectory()) {
//noinspection ResultOfMethodCallIgnored
pluginsDir.mkdirs();
} else {
for (File plugin : FileUtils.listFiles(pluginsDir, new String[]{"jar", "zip"}, false)) {
try {
urls.add(plugin.toURI().toURL());
CustomSkinLoader.logger.info("Found a jar or zip file: " + plugin.getName());
} catch (MalformedURLException ignored) {
}
}
}
ArrayList<ICustomSkinLoaderPlugin> plugins = Lists.newArrayList(DEFAULT_PLUGINS);
ServiceLoader<ICustomSkinLoaderPlugin> sl = ServiceLoader.load(ICustomSkinLoaderPlugin.class, new URLClassLoader(urls.toArray(new URL[0]), PluginLoader.class.getClassLoader()));
for (ICustomSkinLoaderPlugin plugin : sl) {
plugins.add(plugin);
}
return plugins;
}
}
@@ -0,0 +1,159 @@
package customskinloader.profile;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.util.UUIDTypeAdapter;
import customskinloader.CustomSkinLoader;
import customskinloader.utils.HttpRequestUtil;
import customskinloader.utils.HttpTextureUtil;
import customskinloader.utils.HttpUtil0;
import customskinloader.utils.TextureUtil;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
public class DynamicSkullManager {
public static class SkullTexture {
public Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures;
public String index;//Index File
public ArrayList<String> skins;
public int interval;
public boolean fromZero;
//For program
public long startTime;
public int period;
}
private Map<GameProfile, SkullTexture> dynamicTextures = new ConcurrentHashMap<>();
private Map<GameProfile, Map<MinecraftProfileTexture.Type, MinecraftProfileTexture>> staticTextures = new ConcurrentHashMap<>();
private List<GameProfile> loadingList = Lists.newArrayList();
private void parseGameProfile(GameProfile profile) {
Property textureProperty = Iterables.getFirst(TextureUtil.AuthlibField.GAME_PROFILE_PROPERTIES.<PropertyMap>get(profile).get("textures"), null);
if (textureProperty == null) {
staticTextures.put(profile, Maps.newHashMap());
return;
}
String value = TextureUtil.AuthlibField.PROPERTY_VALUE.get(textureProperty);
if (StringUtils.isBlank(value)) {
staticTextures.put(profile, Maps.newHashMap());
return;
}
@SuppressWarnings("deprecation") String json = new String(Base64.decodeBase64(value), Charsets.UTF_8);
Gson gson = new GsonBuilder().registerTypeAdapter(UUID.class, new UUIDTypeAdapter()).create();
SkullTexture result = gson.fromJson(json, SkullTexture.class);
if (result == null) {
staticTextures.put(profile, Maps.newHashMap());
return;
}
staticTextures.put(profile, (result.textures == null || !result.textures.containsKey(MinecraftProfileTexture.Type.SKIN)) ? Maps.newHashMap() : parseTextures(result.textures));
if (StringUtils.isNotEmpty(result.index)) {
File indexFile = new File(CustomSkinLoader.DATA_DIR, result.index);
try {
String index = FileUtils.readFileToString(indexFile, "UTF-8");
if (StringUtils.isNotEmpty(index)) {
String[] skins = CustomSkinLoader.GSON.fromJson(index, String[].class);
if (skins != null && skins.length != 0)
result.skins = Lists.newArrayList(skins);
}
} catch (Exception e) {
CustomSkinLoader.logger.warning("Exception occurs while parsing index file: " + e.toString());
}
}
if (!CustomSkinLoader.config.enableDynamicSkull || result.skins == null || result.skins.isEmpty())
return;
CustomSkinLoader.logger.info("Try to load Dynamic Skull: " + json);
for (int i = 0; i < result.skins.size(); i++) {//check and cache skins
String skin = result.skins.get(i);
if (HttpUtil0.isLocal(skin)) {
//Local Skin
File skinFile = new File(CustomSkinLoader.DATA_DIR, skin);
if (skinFile.isFile() && skinFile.length() > 0) {
//Skin found
String fakeUrl = HttpTextureUtil.getLocalFakeUrl(skin);
result.skins.set(i, fakeUrl);
} else {
//Could not find skin
result.skins.remove(i--);
}
} else {
//Online Skin
HttpRequestUtil.HttpResponce responce = HttpRequestUtil.makeHttpRequest(new HttpRequestUtil.HttpRequest(skin).setCacheFile(HttpTextureUtil.getCacheFile(FilenameUtils.getBaseName(skin))).setCacheTime(0).setLoadContent(false));
if (!responce.success) {
//Could not load skin
result.skins.remove(i--);
}
}
}
if (result.skins.isEmpty()) {//Nothing loaded
CustomSkinLoader.logger.info("Failed: Nothing loaded.");
return;
}
result.interval = Math.max(result.interval, 50);
if (result.fromZero)
result.startTime = System.currentTimeMillis();
result.period = result.interval * result.skins.size();
CustomSkinLoader.logger.info("Successfully loaded Dynamic Skull: " + new Gson().toJson(result));
dynamicTextures.put(profile, result);
staticTextures.remove(profile);
}
//Support local skin for skull
public Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> parseTextures(Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> textures) {
MinecraftProfileTexture skin = textures.get(MinecraftProfileTexture.Type.SKIN);
String skinUrl = skin.getUrl();
if (!HttpUtil0.isLocal(skinUrl))
// Wrap MinecraftProfileTexture to FakeMinecraftProfileTexture
return ModelManager0.fromUserProfile(ModelManager0.toUserProfile(textures));
File skinFile = new File(CustomSkinLoader.DATA_DIR, skinUrl);
if (!skinFile.isFile())
return Maps.newHashMap();
textures.put(MinecraftProfileTexture.Type.SKIN, ModelManager0.getProfileTexture(HttpTextureUtil.getLocalFakeUrl(skinUrl), null));
return textures;
}
public Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getTexture(final GameProfile profile) {
if (staticTextures.get(profile) != null)
return staticTextures.get(profile);
if (loadingList.contains(profile))
return CustomSkinLoader.INCOMPLETED;
if (dynamicTextures.containsKey(profile)) {
SkullTexture texture = dynamicTextures.get(profile);
long time = System.currentTimeMillis() - texture.startTime;
int index = (int) Math.floor((time % texture.period) / texture.interval);
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = Maps.newHashMap();
map.put(MinecraftProfileTexture.Type.SKIN, ModelManager0.getProfileTexture(texture.skins.get(index), null));
return map;
}
loadingList.add(profile);
Thread loadThread = new Thread(() -> {
parseGameProfile(profile);//Load in thread
loadingList.remove(profile);
});
loadThread.setName("Skull " + profile.hashCode());
loadThread.start();
return CustomSkinLoader.INCOMPLETED;
}
}
@@ -3,11 +3,11 @@ package customskinloader.profile;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Maps;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import customskinloader.CustomSkinLoader;
import customskinloader.fake.FakeMinecraftProfileTexture;
import org.apache.commons.lang3.StringUtils;
/**
* Model Manager for 1.8 and higher.
@@ -25,10 +25,10 @@ public class ModelManager0 {
}
private static HashMap<String, Model> models = new HashMap<String, Model>();
private static Type typeElytra = null;
private static MinecraftProfileTexture.Type typeElytra = null;
static {
for (Type type : Type.values()) {
for (MinecraftProfileTexture.Type type : MinecraftProfileTexture.Type.values()) {
if (type.ordinal() == 2)//ELYTRA
typeElytra = type;
}
@@ -76,17 +76,17 @@ public class ModelManager0 {
* @return profile - UserProfile instance
* @since 13.1
*/
public static UserProfile toUserProfile(Map<Type, MinecraftProfileTexture> profile) {
public static UserProfile toUserProfile(Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> profile) {
UserProfile userProfile = new UserProfile();
if (profile == null)
return userProfile;
MinecraftProfileTexture skin = profile.get(Type.SKIN);
MinecraftProfileTexture skin = profile.get(MinecraftProfileTexture.Type.SKIN);
userProfile.skinUrl = skin == null ? null : skin.getUrl();//Avoid NullPointerException
userProfile.model = skin == null ? null : skin.getMetadata("model");
if (StringUtils.isEmpty(userProfile.model))
userProfile.model = "default";
MinecraftProfileTexture cape = profile.get(Type.CAPE);
MinecraftProfileTexture cape = profile.get(MinecraftProfileTexture.Type.CAPE);
userProfile.capeUrl = cape == null ? null : cape.getUrl();
return userProfile;
}
@@ -98,20 +98,20 @@ public class ModelManager0 {
* @return profile - hashMapProfile (HashMap<String,MinecraftProfileTexture>)
* @since 13.1
*/
public static Map<Type, MinecraftProfileTexture> fromUserProfile(UserProfile profile) {
Map<Type, MinecraftProfileTexture> map = Maps.newHashMap();
public static Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> fromUserProfile(UserProfile profile) {
if (profile == null)
return map;
return CustomSkinLoader.INCOMPLETED;
Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> map = Maps.newHashMap();
if (profile.skinUrl != null) {
Map<String, String> metadata = null;
if ("slim".equals(profile.model) || "auto".equals(profile.model)) {
metadata = Maps.newHashMap();
metadata.put("model", profile.model);
}
map.put(Type.SKIN, getProfileTexture(profile.skinUrl, metadata));
map.put(MinecraftProfileTexture.Type.SKIN, getProfileTexture(profile.skinUrl, metadata));
}
if (profile.capeUrl != null)
map.put(Type.CAPE, getProfileTexture(profile.capeUrl, null));
map.put(MinecraftProfileTexture.Type.CAPE, getProfileTexture(profile.capeUrl, null));
if (typeElytra != null && profile.elytraUrl != null)
map.put(typeElytra, getProfileTexture(profile.elytraUrl, null));
return map;
@@ -126,6 +126,6 @@ public class ModelManager0 {
* @since 14.5
*/
public static MinecraftProfileTexture getProfileTexture(String url, Map<String, String> metadata) {
return new MinecraftProfileTexture(url, metadata);
return new FakeMinecraftProfileTexture(url, metadata);
}
}
@@ -1,20 +1,22 @@
package customskinloader.profile;
import java.io.File;
import java.util.HashMap;
import java.util.Deque;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.io.FileUtils;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.function.Function;
import customskinloader.CustomSkinLoader;
import customskinloader.utils.TimeUtil;
import org.apache.commons.io.FileUtils;
public class ProfileCache {
public static File PROFILE_CACHE_DIR=new File(CustomSkinLoader.DATA_DIR,"ProfileCache");
private Map<String, CachedProfile> cachedProfiles = new ConcurrentHashMap<>();
private Map<String, UserProfile> localProfiles = new ConcurrentHashMap<>();
private Map<String, Deque<Function<UserProfile, ?>>> profileLoaders = new ConcurrentHashMap<>();
@SuppressWarnings("ResultOfMethodCallIgnored")
public ProfileCache(){
@@ -49,6 +51,13 @@ public class ProfileCache {
return localProfiles.get(username.toLowerCase());
return loadLocalProfile(username);
}
public Function<UserProfile, ?> getLastLoader(String username) {
Deque<Function<UserProfile, ?>> deque = this.profileLoaders.get(username);
if (deque != null) {
return deque.pollLast();
}
return null;
}
public void setLoading(String username,boolean loading){
getCachedProfile(username).loading=loading;
@@ -59,11 +68,15 @@ public class ProfileCache {
public void updateCache(String username,UserProfile profile,boolean saveLocalProfile){
CachedProfile cp=getCachedProfile(username);
cp.profile=profile;
cp.expiryTime=TimeUtil.getUnixTimestampRandomDelay(CustomSkinLoader.config.cacheExpiry);
cp.expiryTime=TimeUtil.getUnixTimestamp(CustomSkinLoader.config.cacheExpiry);
if(!saveLocalProfile)
return;
saveLocalProfile(username,profile);
}
public void putLoader(String username, Function<UserProfile, ?> loader) {
this.profileLoaders.putIfAbsent(username, new ConcurrentLinkedDeque<>());
this.profileLoaders.get(username).offerLast(loader);
}
private CachedProfile getCachedProfile(String username){
CachedProfile cp=cachedProfiles.get(username.toLowerCase());
@@ -76,7 +89,7 @@ public class ProfileCache {
private UserProfile loadLocalProfile(String username){
File localProfile=new File(PROFILE_CACHE_DIR,username.toLowerCase()+".json");
if(!localProfile.exists()){
localProfiles.put(username.toLowerCase(), null);
localProfiles.put(username.toLowerCase(), UserProfile.NULL);
}
try{
String json = FileUtils.readFileToString(localProfile, "UTF-8");
@@ -86,9 +99,9 @@ public class ProfileCache {
return profile;
}catch(Exception e){
CustomSkinLoader.logger.info("Failed to load LocalProfile.("+e.toString()+")");
localProfiles.put(username.toLowerCase(), null);
localProfiles.put(username.toLowerCase(), UserProfile.NULL);
}
return null;
return UserProfile.NULL;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private void saveLocalProfile(String username, UserProfile profile){
@@ -108,4 +121,4 @@ class CachedProfile{
public UserProfile profile;
public long expiryTime=0;
public boolean loading=false;
}
}
@@ -2,13 +2,13 @@ package customskinloader.profile;
import org.apache.commons.lang3.StringUtils;
import customskinloader.profile.ModelManager0.Model;
/**The instance to storage user's profile in memory temporarily.
* In this manner, it could be easier to pass profile in program.
* @since 13.1
*/
public class UserProfile {
public final static UserProfile NULL = new UserProfile();
/**
* Direct url for skin.
@@ -35,7 +35,7 @@ public class UserProfile {
*/
public String elytraUrl=null;
public void put(Model model,String url){
public void put(ModelManager0.Model model,String url){
if(model==null||StringUtils.isEmpty(url))
return;
switch(model){
@@ -51,7 +51,7 @@ public class UserProfile {
this.capeUrl=url;
return;
case ELYTRA:
this.capeUrl=url;
this.elytraUrl = url;
}
}
@@ -7,6 +7,7 @@ import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
@@ -26,7 +27,11 @@ public class HttpRequestUtil {
public boolean loadContent = true;
public boolean checkPNG = false;
public int cacheTime = 600;//-1=No Cache 0=Always Cache t=Default Cache Time(second)
/**
* Cache Time
* -1=No Cache 0=Always Cache t=Default Cache Time(second)
*/
public int cacheTime = 600;
public File cacheFile = null;//Default Cache File
public HttpRequest(String url) {
@@ -87,14 +92,16 @@ public class HttpRequestUtil {
public static HttpResponce makeHttpRequest(HttpRequest request, int redirectTime) {
try {
if(request.url.contains("{ABORT}")){
CustomSkinLoader.logger.info("ABORT tag found in url, request has been aborted.");
return new HttpResponce();
//No url provided, try to load from special cache file
if (request.url == null || request.url.isEmpty()) {
CustomSkinLoader.logger.debug("Try to read cache '" + request.cacheFile + "'.");
return loadFromCache(request, new HttpResponce());
}
CustomSkinLoader.logger.debug("Try to request '" + request.url + (request.userAgent == null ? "'." : "' with user agent '" + request.userAgent + "'."));
//Check Cache
if (StringUtils.isNotEmpty(request.payload))
if (StringUtils.isNotEmpty(request.payload) || CustomSkinLoader.config.forceDisableCache) {
request.cacheTime = -1;//No Cache
}
File cacheInfoFile = null;
CacheInfo cacheInfo = new CacheInfo();
if (request.cacheFile == null && request.cacheTime >= 0) {
@@ -102,32 +109,38 @@ public class HttpRequestUtil {
request.cacheFile = new File(CACHE_DIR, hash);
cacheInfoFile = new File(CACHE_DIR, hash + ".json");
}
if (request.cacheTime == 0 && request.cacheFile.isFile())
//noinspection BulkFileAttributesRead
if (request.cacheTime == 0 && request.cacheFile.isFile()) {
return loadFromCache(request, new HttpResponce());
}
if (cacheInfoFile != null && cacheInfoFile.isFile()) {
String json = FileUtils.readFileToString(cacheInfoFile, "UTF-8");
if (StringUtils.isNotEmpty(json))
if (StringUtils.isNotEmpty(json)) {
cacheInfo = CustomSkinLoader.GSON.fromJson(json, CacheInfo.class);
if (cacheInfo == null)
}
if (cacheInfo == null) {
cacheInfo = new CacheInfo();
if (cacheInfo.expire >= TimeUtil.getCurrentUnixTimestamp())
}
if (cacheInfo.expire >= TimeUtil.getCurrentUnixTimestamp()) {
return loadFromCache(request, new HttpResponce(), cacheInfo.expire);
}
}
//Init Connection
URL rawUrl = new URL(request.url);
URI uri = new URI(
rawUrl.getProtocol(),
rawUrl.getUserInfo(),
rawUrl.getHost(),
rawUrl.getPort(),
rawUrl.getPath(),
rawUrl.getQuery(),
rawUrl.getRef()
rawUrl.getProtocol(),
rawUrl.getUserInfo(),
rawUrl.getHost(),
rawUrl.getPort(),
rawUrl.getPath(),
rawUrl.getQuery(),
rawUrl.getRef()
);
String url = uri.toASCIIString();
if (!url.equalsIgnoreCase(request.url))
if (!url.equalsIgnoreCase(request.url)) {
CustomSkinLoader.logger.debug("Encoded URL: " + url);
}
HttpURLConnection c = (HttpURLConnection) (new URL(url)).openConnection();
c.setReadTimeout(1000 * 10);
c.setConnectTimeout(1000 * 10);
@@ -136,15 +149,19 @@ public class HttpRequestUtil {
c.setInstanceFollowRedirects(true);
//Make Connection
if (cacheInfo.lastModified >= 0)
if (cacheInfo.lastModified >= 0) {
c.setIfModifiedSince(cacheInfo.lastModified);
if (cacheInfo.etag != null)
}
if (cacheInfo.etag != null) {
c.setRequestProperty("If-None-Match", cacheInfo.etag);
}
c.setRequestProperty("Accept-Encoding", "gzip");
if (request.userAgent != null)
if (request.userAgent != null) {
c.setRequestProperty("User-Agent", request.userAgent);
}
if (StringUtils.isNotEmpty(request.payload)) {
CustomSkinLoader.logger.info("Payload: " + request.payload);
c.setRequestMethod("POST");
c.setRequestProperty("Content-Type", "application/json");
c.setDoOutput(true);
OutputStream os = c.getOutputStream();
@@ -177,10 +194,12 @@ public class HttpRequestUtil {
}
responce.success = true;
CustomSkinLoader.logger.debug("Successfully request (Response Code: " + res + " , Content Length: " + c.getContentLength() + ")");
if (responce.responceCode == HttpURLConnection.HTTP_NOT_MODIFIED)
if (responce.responceCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
return loadFromCache(request, responce);
if (responce.responceCode == HttpURLConnection.HTTP_NO_CONTENT)
}
if (responce.responceCode == HttpURLConnection.HTTP_NO_CONTENT) {
request.cacheTime = 3600;
}
//Load Content
InputStream is = "gzip".equals(c.getContentEncoding()) ? new GZIPInputStream(c.getInputStream()) : c.getInputStream();
@@ -199,16 +218,18 @@ public class HttpRequestUtil {
cacheInfo.expire = getExpire(c, request.cacheTime);
FileUtils.write(cacheInfoFile, CustomSkinLoader.GSON.toJson(cacheInfo), "UTF-8");
}
//noinspection BulkFileAttributesRead
CustomSkinLoader.logger.debug("Saved to cache (Length: " + request.cacheFile.length() + " , Path: '" + request.cacheFile.getAbsolutePath() + "' , Expire: " + cacheInfo.expire + ")");
}
if (!request.loadContent)
if (!request.loadContent) {
return responce;
responce.content = new String(bytes, "UTF-8");
}
responce.content = new String(bytes, StandardCharsets.UTF_8);
CustomSkinLoader.logger.debug("Content: " + responce.content);
return responce;
} catch (Exception e) {
CustomSkinLoader.logger.debug("Failed to request (Exception: " + e.toString() + ")");
CustomSkinLoader.logger.debug("Failed to request " + request.url + " (Exception: " + e + ")");
return loadFromCache(request, new HttpResponce());
}
}
@@ -222,13 +243,15 @@ public class HttpRequestUtil {
}
private static HttpResponce loadFromCache(HttpRequest request, HttpResponce responce, long expireTime) {
if (request.cacheFile == null || !request.cacheFile.isFile())
if (request.cacheFile == null || !request.cacheFile.isFile()) {
return responce;
CustomSkinLoader.logger.debug("Cache file found (Length: " + request.cacheFile.length() + " , Path: '" + request.cacheFile.getAbsolutePath() + "' , Expire: " + expireTime + "')");
}
CustomSkinLoader.logger.debug("Cache file found (Length: " + request.cacheFile.length() + " , Path: '" + request.cacheFile.getAbsolutePath() + "' , Expire: " + expireTime + ")");
responce.fromCache = true;
responce.success = true;
if (!request.loadContent)
if (!request.loadContent) {
return responce;
}
CustomSkinLoader.logger.info("Try to load from cache '" + request.cacheFile.getAbsolutePath() + "'.");
try {
@@ -236,7 +259,7 @@ public class HttpRequestUtil {
CustomSkinLoader.logger.debug("Successfully load from cache");
CustomSkinLoader.logger.debug("Content: " + responce.content);
} catch (IOException e) {
CustomSkinLoader.logger.debug("Failed to load from cache (Exception: " + e.toString() + ")");
CustomSkinLoader.logger.debug("Failed to load from cache (Exception: " + e + ")");
responce.success = false;
}
return responce;
@@ -254,7 +277,6 @@ public class HttpRequestUtil {
long expires = connection.getExpiration();
if (expires > 0)
return expires / 1000;
return TimeUtil.getUnixTimestampRandomDelay(cacheTime == 0 ? 86400 : cacheTime);
return TimeUtil.getUnixTimestampRandomDelay(cacheTime == 0 ? 2592000 : cacheTime);
}
}
@@ -0,0 +1,107 @@
package customskinloader.utils;
import java.io.File;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import customskinloader.CustomSkinLoader;
public class HttpTextureUtil {
public static class HttpTextureInfo {
public String url = "";
public File cacheFile;
public String hash;
}
private static final String
LEGACY_MARK = "(LEGACY)",
LOCAL_MARK = "(LOCAL)",
LOCAL_LEGACY_MARK = "(LOCAL_LEGACY)",
BASE64_MARK = "(BASE64)";
public static File defaultCacheDir;
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void cleanCacheDir() {
if (defaultCacheDir != null) {
defaultCacheDir.delete();
defaultCacheDir.mkdirs();
}
}
public static File getCacheDir() {
return defaultCacheDir == null ? new File(MinecraftUtil.getMinecraftDataDir(), "assets/skins") : defaultCacheDir;
}
public static HttpTextureInfo toHttpTextureInfo(String fakeUrl) {
HttpTextureInfo info = new HttpTextureInfo();
if (fakeUrl.startsWith("http")) {
info.url = fakeUrl;
info.hash = FilenameUtils.getBaseName(fakeUrl);
info.cacheFile = getCacheFile(info.hash);
return info;
}
if (fakeUrl.startsWith(LOCAL_LEGACY_MARK)) {
fakeUrl = fakeUrl.replace(LOCAL_LEGACY_MARK, "");
String[] t = fakeUrl.split(",", 2);
if (t.length != 2)
return info;
info.cacheFile = new File(CustomSkinLoader.DATA_DIR, t[1]);
info.hash = t[0];
return info;
}
if (fakeUrl.startsWith(LOCAL_MARK)) {
fakeUrl = fakeUrl.replace(LOCAL_MARK, "");
info.cacheFile = new File(CustomSkinLoader.DATA_DIR, fakeUrl);
info.hash = FilenameUtils.getBaseName(fakeUrl);
return info;
}
if (fakeUrl.startsWith(LEGACY_MARK)) {
fakeUrl = fakeUrl.replace(LEGACY_MARK, "");
info.url = fakeUrl;
info.hash = DigestUtils.sha1Hex(info.url);
info.cacheFile = HttpRequestUtil.getCacheFile(info.hash);
return info;
}
//Base64 fake url format: `(BASE64)${hash}`
if (fakeUrl.startsWith(BASE64_MARK)) {
fakeUrl = fakeUrl.replace(BASE64_MARK, "");
info.hash = fakeUrl;
info.cacheFile = getCacheFile(info.hash);
return info;
}
return info;
}
public static String getLegacyFakeUrl(String url) {
return LEGACY_MARK + url;
}
public static String getLocalFakeUrl(String path) {
return LOCAL_MARK + path;
}
public static String getLocalLegacyFakeUrl(String path, String hash) {
return LOCAL_LEGACY_MARK + hash + "," + path;
}
public static String getBase64FakeUrl(String hash) {
return BASE64_MARK + hash;
}
public static String getHash(String url, long size, long lastModified) {
return DigestUtils.sha1Hex(size + url + lastModified);
}
public static String getHash(byte[] bytes) {
return DigestUtils.sha256Hex(bytes);
}
public static File getCacheFile(String hash) {
return getCacheFile(defaultCacheDir, hash);
}
public static File getCacheFile(File cacheDir, String hash) {
return new File(new File(cacheDir, hash.length() > 2 ? hash.substring(0, 2) : "xx"), hash);
}
}
@@ -4,42 +4,13 @@ import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.lang3.StringUtils;
public class HttpUtil0 {
public static boolean isLocal(String url){
return url != null && !url.startsWith("http");
}
//From: http://blog.csdn.net/xiyushiyi/article/details/46685387
public static void ignoreHttpsCertificate(){
HostnameVerifier doNotVerify = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain, String authType){}
public void checkServerTrusted(X509Certificate[] chain, String authType){}
}};
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
//HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultSSLSocketFactory(new SSLSocketFactoryFacade());
HttpsURLConnection.setDefaultHostnameVerifier(doNotVerify);
} catch (Exception e) {
e.printStackTrace();
}
return url != null && !url.startsWith("http://") && !url.startsWith("https://");
}
public static String parseAddress(String address) {
@@ -119,4 +90,4 @@ public class HttpUtil0 {
return createSocket(inetAddress, i, inetAddress1, i1);
}
}
}
}
@@ -1,7 +1,6 @@
package customskinloader.utils;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.LinkedList;
@@ -0,0 +1,50 @@
package customskinloader.utils;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import com.google.common.util.concurrent.ForwardingBlockingQueue;
public class LIFOBlockingQueue<E> extends ForwardingBlockingQueue<E> {
private final BlockingDeque<E> deque;
public LIFOBlockingQueue(BlockingDeque<E> deque) {
this.deque = deque;
}
@Override
protected BlockingQueue<E> delegate() {
return deque;
}
@Override
public boolean offer(E e) {
return deque.offerFirst(e);
}
@Override
public void put(E e) throws InterruptedException {
deque.putFirst(e);
}
@Override
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
return deque.offerFirst(e, timeout, unit);
}
@Override
public E take() throws InterruptedException {
return deque.takeFirst();
}
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
return deque.pollFirst(timeout, unit);
}
@Override
public E peek() {
return deque.peekFirst();
}
}
@@ -0,0 +1,90 @@
package customskinloader.utils;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.net.URL;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mojang.authlib.GameProfile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.SkinManager;
/**
* @author Alexander Xia
* @since 13.6
*/
public class MinecraftUtil {
public static File getMinecraftDataDir() {
return Minecraft.getMinecraft().gameDir;
}
public static TextureManager getTextureManager() {
return Minecraft.getMinecraft().getTextureManager();
}
public static SkinManager getSkinManager() {
return Minecraft.getMinecraft().getSkinManager();
}
private static String minecraftMainVersion = null;
public static String getMinecraftMainVersion() {
//Check if cached version found
if (minecraftMainVersion != null) {
return minecraftMainVersion;
}
//version.json can be found in 1.14+
URL versionFile = ClassLoader.getSystemClassLoader().getResource("version.json");
if (versionFile != null) {
try (
InputStream is = versionFile.openStream();
InputStreamReader isr = new InputStreamReader(is)
) {
JsonObject obj = new JsonParser().parse(isr).getAsJsonObject();
minecraftMainVersion = obj.get("name").getAsString();
return minecraftMainVersion;
} catch (Exception ignored) {
}
}
//RealmsSharedConstants.VERSION_STRING is available in 1.16-
try {
Class<?> realmsSharedConstants = Class.forName("net.minecraft.realms.RealmsSharedConstants");
MethodHandle mh = MethodHandles.publicLookup().findStaticGetter(realmsSharedConstants, "VERSION_STRING", String.class);
minecraftMainVersion = (String) mh.invoke();
return minecraftMainVersion;
} catch (Throwable ignored) {
}
//No version can be found
return "unknown";
}
// (domain|ip)(:port)
public static String getServerAddress() {
ServerData data = Minecraft.getMinecraft().getCurrentServerData();
if (data == null)//Single Player
return null;
return data.serverIP;
}
// ip:port
public static String getStandardServerAddress() {
return HttpUtil0.parseAddress(getServerAddress());
}
public static boolean isLanServer() {
return HttpUtil0.isLanServer(getStandardServerAddress());
}
public static String getCredential(GameProfile profile) {
return profile == null ? null : String.format("%s-%s", TextureUtil.AuthlibField.GAME_PROFILE_NAME.get(profile), TextureUtil.AuthlibField.GAME_PROFILE_ID.get(profile));
}
}
@@ -0,0 +1,86 @@
package customskinloader.utils;
import java.io.File;
import java.lang.reflect.Field;
import java.util.UUID;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.properties.PropertyMap;
import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse;
import com.mojang.authlib.yggdrasil.response.MinecraftTexturesPayload;
import customskinloader.CustomSkinLoader;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
public class TextureUtil {
/**
* Save and get fake url of base64 texture
*
* @param base64 texture in base64 string
* @return base64 fake url
* @since 14.16
*/
public static String parseBase64Texture(String base64) {
byte[] capeBytes = Base64.decodeBase64(base64);
String hash = HttpTextureUtil.getHash(capeBytes);
File cacheFile = HttpTextureUtil.getCacheFile(hash);
String fakeUrl = HttpTextureUtil.getBase64FakeUrl(hash);
//Save base64 image to cache file
try {
FileUtils.writeByteArrayToFile(cacheFile, capeBytes);
CustomSkinLoader.logger.info("Saved base64 image to " + cacheFile);
return fakeUrl;
} catch (Exception e) {
CustomSkinLoader.logger.warning("Error parsing base64 image: " + base64);
return null;
}
}
// Some of the classes in Authlib used after Minecraft 23w31a were changed to record classes,
// resulting in changes to method names, so reflection is used here to be compatible with these changes.
public enum AuthlibField {
GAME_PROFILE_ID(GameProfile.class, "id"),
GAME_PROFILE_NAME(GameProfile.class, "name"),
GAME_PROFILE_PROPERTIES(GameProfile.class, "properties"),
PROPERTY_VALUE(Property.class, "value"),
PROPERTY_MAP_PROPERTIES(PropertyMap.class, "properties"),
MINECRAFT_PROFILE_PROPERTIES_RESPONSE_ID(MinecraftProfilePropertiesResponse.class, "id"),
MINECRAFT_PROFILE_PROPERTIES_RESPONSE_NAME(MinecraftProfilePropertiesResponse.class, "name"),
MINECRAFT_PROFILE_PROPERTIES_RESPONSE_PROPERTIES(MinecraftProfilePropertiesResponse.class, "properties"),
MINECRAFT_TEXTURES_PAYLOAD_TEXTURES(MinecraftTexturesPayload.class, "textures");
private final Field field;
AuthlibField(Class<?> clazz, String name) {
try {
this.field = clazz.getDeclaredField(name);
this.field.setAccessible(true);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
@SuppressWarnings("unchecked")
public <R> R get(Object o) {
try {
return (R) this.field.get(o);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
public void set(Object o, Object value) {
try {
this.field.set(o, value);
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
public static String fromUUID(UUID value) {
return value.toString().replace("-", "");
}
}
@@ -2,17 +2,13 @@ package net.minecraft.client.renderer;
import java.awt.image.BufferedImage;
import customskinloader.fake.itf.IFakeIImageBuffer;
import net.minecraft.client.renderer.texture.NativeImage;
public interface IImageBuffer extends Runnable {
public interface IImageBuffer extends IFakeIImageBuffer {
BufferedImage parseUserSkin(BufferedImage image);
NativeImage func_195786_a(NativeImage image);
void skinAvailable();
@Override
default void run() {
this.skinAvailable();
}
}
@@ -2,10 +2,10 @@
"name": "CustomSkinLoader",
"version": "${modVersion}",
"fullVersion": "${modFullVersion}",
"mcVersion": "${mcVersion}",
"mcFullVersions": "${mcFullVersions}",
"forgeVersion": "${forgeVersion}",
"dependencies": {
"${dependencies}"
},
"gitVersion": "${gitVersion}",
"buildUrl": "${buildUrl}",
"buildTime": "${releaseTime}"
}
}
@@ -33,4 +33,4 @@ GPLv3: http://www.gnu.org/licenses/gpl.html
其他 - 有用的链接
源代码: https://github.com/xfl03/MCCustomSkinLoader
发布页面: http://www.mcbbs.net/thread-269807-1-1.html
构建服务器: https://ci.infstudio.net/job/CustomSkinLoader/
构建服务器: https://ci.infstudio.net/job/CustomSkinLoader/
View File
Whitespace-only changes.
+7
View File
@@ -0,0 +1,7 @@
// This subproject is only to provide dependency for other subprojects.
reobf {
jar {
mappings = file("Dummy.srg")
}
}
+5
View File
@@ -0,0 +1,5 @@
forge_mc_version=1.12.2
forge_version=14.23.5.2768
mappings_version=stable_39
# this subproject is only to provide dependency for other subprojects.
is_real_project=false
@@ -0,0 +1,5 @@
package com.google.errorprone.annotations;
public @interface CanIgnoreReturnValue {
}
@@ -0,0 +1,5 @@
package com.mojang.authlib;
public enum SignatureState {
SIGNED
}
@@ -0,0 +1,8 @@
package com.mojang.authlib.minecraft;
import com.mojang.authlib.SignatureState;
public class MinecraftProfileTextures {
public MinecraftProfileTextures(MinecraftProfileTexture skin, MinecraftProfileTexture cape, MinecraftProfileTexture elytra, SignatureState signatureState) {}
public MinecraftProfileTexture skin() { return null; }
}
@@ -0,0 +1,7 @@
package com.mojang.authlib.minecraft;
import com.mojang.authlib.properties.Property;
public interface MinecraftSessionService {
MinecraftProfileTextures unpackTextures(Property packedTextures);
}
@@ -0,0 +1,17 @@
package net.minecraft.client;
import java.io.File;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.resources.SkinManager;
public class Minecraft {
public File gameDir;
public static Minecraft getMinecraft() { return null; }
public ServerData getCurrentServerData() { return null; }
public IResourceManager getResourceManager() { return null; }
public SkinManager getSkinManager() { return null; }
public TextureManager getTextureManager() { return null; }
}
Loaded 100 of 293 files, more files were not shown because too many files have changed in this diff. Show more