aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/data/HypixelData.kt
blob: dd4a91fb97eb9af34460d452875223d8b3a0d11c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package at.hannibal2.skyhanni.data

import at.hannibal2.skyhanni.SkyHanniMod
import at.hannibal2.skyhanni.api.event.HandleEvent
import at.hannibal2.skyhanni.config.ConfigManager.Companion.gson
import at.hannibal2.skyhanni.data.model.TabWidget
import at.hannibal2.skyhanni.events.HypixelJoinEvent
import at.hannibal2.skyhanni.events.IslandChangeEvent
import at.hannibal2.skyhanni.events.LorenzChatEvent
import at.hannibal2.skyhanni.events.LorenzTickEvent
import at.hannibal2.skyhanni.events.LorenzWorldChangeEvent
import at.hannibal2.skyhanni.events.ProfileJoinEvent
import at.hannibal2.skyhanni.events.ScoreboardUpdateEvent
import at.hannibal2.skyhanni.events.WidgetUpdateEvent
import at.hannibal2.skyhanni.events.minecraft.ClientDisconnectEvent
import at.hannibal2.skyhanni.features.bingo.BingoAPI
import at.hannibal2.skyhanni.features.dungeon.DungeonAPI
import at.hannibal2.skyhanni.features.rift.RiftAPI
import at.hannibal2.skyhanni.skyhannimodule.SkyHanniModule
import at.hannibal2.skyhanni.test.command.ErrorManager
import at.hannibal2.skyhanni.utils.ChatUtils
import at.hannibal2.skyhanni.utils.LorenzLogger
import at.hannibal2.skyhanni.utils.LorenzUtils
import at.hannibal2.skyhanni.utils.RegexUtils.matchFirst
import at.hannibal2.skyhanni.utils.RegexUtils.matchMatcher
import at.hannibal2.skyhanni.utils.RegexUtils.matches
import at.hannibal2.skyhanni.utils.SimpleTimeMark
import at.hannibal2.skyhanni.utils.StringUtils.removeColor
import at.hannibal2.skyhanni.utils.TabListData
import at.hannibal2.skyhanni.utils.UtilsPatterns
import at.hannibal2.skyhanni.utils.repopatterns.RepoPattern
import com.google.gson.JsonObject
import io.github.moulberry.notenoughupdates.NotEnoughUpdates
import net.minecraft.client.Minecraft
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import kotlin.concurrent.thread
import kotlin.time.Duration.Companion.seconds

@SkyHanniModule
object HypixelData {

    private val patternGroup = RepoPattern.group("data.hypixeldata")

    // TODO add regex tests
    private val serverNameConnectionPattern by patternGroup.pattern(
        "servername.connection",
        "(?<prefix>.+\\.)?hypixel\\.net",
    )
    private val serverNameScoreboardPattern by patternGroup.pattern(
        "servername.scoreboard",
        "§e(?<prefix>.+\\.)?hypixel\\.net",
    )
    private val islandNamePattern by patternGroup.pattern(
        "islandname",
        "(?:§.)*(Area|Dungeon): (?:§.)*(?<island>.*)",
    )
    private val serverIdScoreboardPattern by patternGroup.pattern(
        "serverid.scoreboard",
        "§7\\d+/\\d+/\\d+ §8(?<servertype>[mM])(?<serverid>\\S+).*",
    )
    private val lobbyTypePattern by patternGroup.pattern(
        "lobbytype",
        "(?<lobbyType>.*lobby)\\d+",
    )
    private val playerAmountPattern by patternGroup.pattern(
        "playeramount",
        "^\\s*(?:§.)+Players (?:§.)+\\((?<amount>\\d+)\\)\\s*$",
    )
    private val playerAmountCoopPattern by patternGroup.pattern(
        "playeramount.coop",
        "^\\s*(?:§.)*Coop (?:§.)*\\((?<amount>\\d+)\\)\\s*$",
    )
    private val playerAmountGuestingPattern by patternGroup.pattern(
        "playeramount.guesting",
        "^\\s*(?:§.)*Guests (?:§.)*\\((?<amount>\\d+)\\)\\s*$",
    )

    /**
     * REGEX-TEST:           §r§b§lParty §r§f(4)
     */
    private val dungeonPartyAmountPattern by patternGroup.pattern(
        "playeramount.dungeonparty",
        "^\\s*(?:§.)+Party (?:§.)+\\((?<amount>\\d+)\\)\\s*$",
    )
    private val soloProfileAmountPattern by patternGroup.pattern(
        "solo.profile.amount",
        "^\\s*(?:§.)*Island\\s*$",
    )
    private val scoreboardVisitingAmoutPattern by patternGroup.pattern(
        "scoreboard.visiting.amount",
        "\\s+§.✌ §.\\(§.(?<currentamount>\\d+)§./(?<maxamount>\\d+)\\)",
    )
    private val guestPattern by patternGroup.pattern(
        "guesting.scoreboard",
        "SKYBLOCK GUEST",
    )
    private val scoreboardTitlePattern by patternGroup.pattern(
        "scoreboard.title",
        "SK[YI]BLOCK(?: CO-OP| GUEST)?",
    )

    /**
     * REGEX-TEST:  §7⏣ §bVillage
     * REGEX-TEST:  §5ф §dWizard Tower
     */
    private val skyblockAreaPattern by patternGroup.pattern(
        "skyblock.area",
        "\\s*§(?<symbol>7⏣|5ф) §(?<color>.)(?<area>.*)",
    )

    private var lastLocRaw = SimpleTimeMark.farPast()
    private var hasScoreboardUpdated = false

    var hypixelLive = false
    var hypixelAlpha = false
    var inLobby = false
    var inLimbo = false
    var skyBlock = false
    var skyBlockIsland = IslandType.UNKNOWN
    var serverId: String? = null

    // Ironman, Stranded and Bingo
    var noTrade = false

    var ironman = false
    var stranded = false
    var bingo = false

    var profileName = ""
    var joinedWorld = SimpleTimeMark.farPast()

    var skyBlockArea: String? = null
    var skyBlockAreaWithSymbol: String? = null

    // Data from locraw
    var locrawData: JsonObject? = null
    private var locraw: MutableMap<String, String> = listOf(
        "server",
        "gametype",
        "lobbyname",
        "lobbytype",
        "mode",
        "map",
    ).associateWith { "" }.toMutableMap()

    val server get() = locraw["server"] ?: ""
    val gameType get() = locraw["gametype"] ?: ""
    val lobbyName get() = locraw["lobbyname"] ?: ""
    val lobbyType get() = locraw["lobbytype"] ?: ""
    val mode get() = locraw["mode"] ?: ""
    val map get() = locraw["map"] ?: ""

    fun checkCurrentServerId() {
        if (!LorenzUtils.inSkyBlock) return
        if (serverId != null) return
        if (LorenzUtils.lastWorldSwitch.passedSince() < 1.seconds) return
        if (!TabListData.fullyLoaded) return

        TabWidget.SERVER.matchMatcherFirstLine {
            serverId = group("serverid")
            return
        }

        ScoreboardData.sidebarLinesFormatted.matchFirst(serverIdScoreboardPattern) {
            val serverType = if (group("servertype") == "M") "mega" else "mini"
            serverId = "$serverType${group("serverid")}"
            return
        }

        ErrorManager.logErrorWithData(
            Exception("NoServerId"),
            "Could not find server id",
            "islandType" to LorenzUtils.skyBlockIsland,
            "tablist" to TabListData.getTabList(),
            "scoreboard" to ScoreboardData.sidebarLinesFormatted,
        )
    }

    fun getPlayersOnCurrentServer(): Int {
        var amount = 0
        val playerPatternList = mutableListOf(
            playerAmountPattern,
            playerAmountCoopPattern,
            playerAmountGuestingPattern,
        )
        if (DungeonAPI.inDungeon()) {
            playerPatternList.add(dungeonPartyAmountPattern)
        }

        out@ for (pattern in playerPatternList) {
            for (line in TabListData.getTabList()) {
                pattern.matchMatcher(line) {
                    amount += group("amount").toInt()
                    continue@out
                }
            }
        }
        amount += TabListData.getTabList().count { soloProfileAmountPattern.matches(it) }

        return amount
    }

    fun getMaxPlayersForCurrentServer(): Int {
        ScoreboardData.sidebarLinesFormatted.matchFirst(scoreboardVisitingAmoutPattern) {
            return group("maxamount").toInt()
        }

        return when (skyBlockIsland) {
            IslandType.MINESHAFT -> 4
            IslandType.CATACOMBS -> 5
            IslandType.CRYSTAL_HOLLOWS -> 24
            IslandType.CRIMSON_ISLE -> 24
            else -> if (serverId?.startsWith("mega") == true) 80 else 26
        }
    }

    // This code is modified from NEU, and depends on NEU (or another mod) sending /locraw.
    private val jsonBracketPattern = "^\\{.+}".toPattern()

    //todo convert to proper json object
    fun checkForLocraw(message: String) {
        jsonBracketPattern.matchMatcher(message.removeColor()) {
            try {
                val obj: JsonObject = gson.fromJson(group(), JsonObject::class.java)
                if (obj.has("server")) {
                    locrawData = obj
                    for (key in locraw.keys) {
                        locraw[key] = obj[key]?.asString ?: ""
                    }
                    inLimbo = locraw["server"] == "limbo"
                    inLobby = locraw["lobbyname"] != ""

                    if (inLobby) {
                        locraw["lobbyname"]?.let {
                            lobbyTypePattern.matchMatcher(it) {
                                locraw["lobbytype"] = group("lobbyType")
                            }
                        }
                    }
                }
            } catch (e: Exception) {
                ErrorManager.logErrorWithData(e, "Failed to parse locraw data")
            }
        }
    }

    private var loggerIslandChange = LorenzLogger("debug/island_change")

    @SubscribeEvent
    fun onWorldChange(event: LorenzWorldChangeEvent) {
        locrawData = null
        skyBlock = false
        inLimbo = false
        inLobby = false
        locraw.forEach { locraw[it.key] = "" }
        joinedWorld = SimpleTimeMark.now()
        serverId = null
        skyBlockArea = null
        skyBlockAreaWithSymbol = null
    }

    @HandleEvent
    fun onDisconnect(event: ClientDisconnectEvent) {
        hypixelLive = false
        hypixelAlpha = false
        skyBlock = false
        inLobby = false
        locraw.forEach { locraw[it.key] = "" }
        locrawData = null
        skyBlockArea = null
        skyBlockAreaWithSymbol = null
        hasScoreboardUpdated = false
    }

    @SubscribeEvent
    fun onScoreboardUpdate(event: ScoreboardUpdateEvent) {
        hasScoreboardUpdated = true
    }

    @SubscribeEvent
    fun onChat(event: LorenzChatEvent) {
        if (!LorenzUtils.onHypixel) return

        val message = event.message.removeColor().lowercase()
        if (message.startsWith("your profile was changed to:")) {
            val newProfile = message.replace("your profile was changed to:", "").replace("(co-op)", "").trim()
            if (profileName == newProfile) return
            profileName = newProfile
            ProfileJoinEvent(newProfile).postAndCatch()
        }
        if (message.startsWith("you are playing on profile:")) {
            val newProfile = message.replace("you are playing on profile:", "").replace("(co-op)", "").trim()
            if (profileName == newProfile) return
            profileName = newProfile
            ProfileJoinEvent(newProfile).postAndCatch()
        }
    }

    private fun checkProfile() {
        TabWidget.PROFILE.matchMatcherFirstLine {
            var newProfile = group("profile").lowercase()
            // Hypixel shows the profile name reversed while in the Rift
            if (RiftAPI.inRift()) newProfile = newProfile.reversed()
            if (profileName == newProfile) return
            profileName = newProfile
            ProfileJoinEvent(newProfile).postAndCatch()
        }
    }

    // TODO rewrite everything in here
    @SubscribeEvent
    fun onTick(event: LorenzTickEvent) {
        if (!LorenzUtils.inSkyBlock) {
            checkNEULocraw()
        }

        if (LorenzUtils.onHypixel && LorenzUtils.inSkyBlock) {
            loop@ for (line in ScoreboardData.sidebarLinesFormatted) {
                skyblockAreaPattern.matchMatcher(line) {
                    val originalLocation = group("area")
                    skyBlockArea = LocationFixData.fixLocation(skyBlockIsland) ?: originalLocation
                    skyBlockAreaWithSymbol = line.trim()
                    break@loop
                }
            }

            checkProfileName()
        }

        if (!LorenzUtils.onHypixel) {
            checkHypixel()
            if (LorenzUtils.onHypixel) {
                HypixelJoinEvent().postAndCatch()
                SkyHanniMod.repo.displayRepoStatus(true)
            }
        }
        if (!LorenzUtils.onHypixel) return

        if (!event.isMod(5)) return

        val inSkyBlock = checkScoreboard()
        if (inSkyBlock) {
            checkSidebar()
            checkCurrentServerId()
        }

        if (inSkyBlock == skyBlock) return
        skyBlock = inSkyBlock
    }

    // Modified from NEU.
    // NEU does not send locraw when not in SkyBlock.
    // So, as requested by Hannibal, use locraw from
    // NEU and have NEU send it.
    // Remove this when NEU dependency is removed
    private fun checkNEULocraw() {
        if (LorenzUtils.onHypixel && locrawData == null && lastLocRaw.passedSince() > 15.seconds) {
            lastLocRaw = SimpleTimeMark.now()
            thread(start = true) {
                Thread.sleep(1000)
                NotEnoughUpdates.INSTANCE.sendChatMessage("/locraw")
            }
        }
    }

    @SubscribeEvent
    fun onTabListUpdate(event: WidgetUpdateEvent) {
        when (event.widget) {
            TabWidget.AREA -> checkIsland(event)
            TabWidget.PROFILE -> checkProfile()
            else -> Unit
        }
    }

    private fun checkProfileName() {
        if (profileName.isNotEmpty()) return

        TabListData.getTabList().matchFirst(UtilsPatterns.tabListProfilePattern) {
            profileName = group("profile").lowercase()
            ProfileJoinEvent(profileName).postAndCatch()
        }
    }

    private fun checkHypixel() {
        if (!hasScoreboardUpdated) return
        val mc = Minecraft.getMinecraft()
        val player = mc.thePlayer ?: return

        var hypixel = false

        player.clientBrand?.let {
            if (it.contains("hypixel", ignoreCase = true)) {
                hypixel = true
            }
        }

        serverNameConnectionPattern.matchMatcher(mc.getCurrentServerData().serverIP) {
            hypixel = true
            if (group("prefix") == "alpha.") {
                hypixelAlpha = true
            }
        }

        for (line in ScoreboardData.sidebarLinesFormatted) {
            serverNameScoreboardPattern.matchMatcher(line) {
                hypixel = true
                if (group("prefix") == "alpha.") {
                    hypixelAlpha = true
                }
            }
        }

        hypixelLive = hypixel && !hypixelAlpha
    }

    private fun checkSidebar() {
        ironman = false
        stranded = false
        bingo = false

        for (line in ScoreboardData.sidebarLinesFormatted) {
            if (BingoAPI.getRankFromScoreboard(line) != null) {
                bingo = true
            }
            when (line) {
                " §7♲ §7Ironman" -> {
                    ironman = true
                }

                " §a☀ §aStranded" -> {
                    stranded = true
                }
            }
        }

        noTrade = ironman || stranded || bingo
    }

    private fun checkIsland(event: WidgetUpdateEvent) {
        val islandType: IslandType
        val foundIsland: String
        if (event.isClear()) {

            TabListData.fullyLoaded = false
            islandType = IslandType.NONE
            foundIsland = ""

        } else {
            TabListData.fullyLoaded = true
            // Can not use color coding, because of the color effect (§f§lSKYB§6§lL§e§lOCK§A§L GUEST)
            val guesting = guestPattern.matches(ScoreboardData.objectiveTitle.removeColor())
            foundIsland = TabWidget.AREA.matchMatcherFirstLine { group("island").removeColor() } ?: ""
            islandType = getIslandType(foundIsland, guesting)
        }

        // TODO dont send events when one of the arguments is none, at least when not on sb anymore
        if (skyBlockIsland != islandType) {
            IslandChangeEvent(islandType, skyBlockIsland).postAndCatch()
            if (islandType == IslandType.UNKNOWN) {
                ChatUtils.debug("Unknown island detected: '$foundIsland'")
                loggerIslandChange.log("Unknown: '$foundIsland'")
            } else {
                loggerIslandChange.log(islandType.name)
            }
            skyBlockIsland = islandType
            if (TabListData.fullyLoaded) {
                TabWidget.reSendEvents()
            }
        }
    }

    private fun getIslandType(name: String, guesting: Boolean): IslandType {
        val islandType = IslandType.getByNameOrUnknown(name)
        if (guesting) {
            if (islandType == IslandType.PRIVATE_ISLAND) return IslandType.PRIVATE_ISLAND_GUEST
            if (islandType == IslandType.GARDEN) return IslandType.GARDEN_GUEST
        }
        return islandType
    }

    private fun checkScoreboard(): Boolean {
        val minecraft = Minecraft.getMinecraft()
        val world = minecraft.theWorld ?: return false

        val objective = world.scoreboard.getObjectiveInDisplaySlot(1) ?: return false
        val displayName = objective.displayName
        val scoreboardTitle = displayName.removeColor()
        return scoreboardTitlePattern.matches(scoreboardTitle)
    }
}