Skip to content

Commit 8265d84

Browse files
committed
refactor: optimize mutable collections and improve string interpolation across services
1 parent 0dde76c commit 8265d84

6 files changed

Lines changed: 88 additions & 132 deletions

File tree

src/main/kotlin/dev/robothanzo/werewolf/security/GlobalWebSocketHandler.kt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import org.springframework.web.socket.TextMessage
88
import org.springframework.web.socket.WebSocketSession
99
import org.springframework.web.socket.handler.TextWebSocketHandler
1010
import java.io.IOException
11+
import java.util.concurrent.ConcurrentHashMap
1112
import java.util.stream.Stream
1213

1314
@Component
@@ -17,7 +18,7 @@ class GlobalWebSocketHandler : TextWebSocketHandler() {
1718
// In a real app with auth, you might map userId -> Session or guildId ->
1819
// List<Session>
1920
// Map guild ID -> Set of Sessions
20-
private val guildSessions = java.util.concurrent.ConcurrentHashMap<String, MutableSet<WebSocketSession>>()
21+
private val guildSessions = ConcurrentHashMap<String, MutableSet<WebSocketSession>>()
2122

2223
@Throws(Exception::class)
2324
override fun afterConnectionEstablished(session: WebSocketSession) {
@@ -62,7 +63,7 @@ class GlobalWebSocketHandler : TextWebSocketHandler() {
6263
return
6364
}
6465

65-
guildSessions.computeIfAbsent(requestedGuildId) { java.util.concurrent.ConcurrentHashMap.newKeySet() }
66+
guildSessions.computeIfAbsent(requestedGuildId) { ConcurrentHashMap.newKeySet() }
6667
.add(session)
6768

6869
log.info(

src/main/kotlin/dev/robothanzo/werewolf/service/impl/GameSessionServiceImpl.kt

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -112,22 +112,18 @@ class GameSessionServiceImpl(
112112

113113
val candidatesList = mutableListOf<Map<String, Any>>()
114114
for (c in policeSession.candidates.values) {
115-
val candidateJson: MutableMap<String, Any> = LinkedHashMap()
115+
val candidateJson = mutableMapOf<String, Any>()
116116
candidateJson["id"] = c.player!!.id.toString()
117117
candidateJson["quit"] = c.quit
118-
val voters = mutableListOf<String>()
119-
for (voterId in c.electors) {
120-
voters.add(voterId.toString())
121-
}
122-
candidateJson["voters"] = voters
118+
candidateJson["voters"] = c.electors.map { it.toString() }
123119
candidatesList.add(candidateJson)
124120
}
125121
policeJson["candidates"] = candidatesList
126122
} else {
127123
policeJson["state"] = "NONE"
128124
policeJson["allowEnroll"] = false
129125
policeJson["allowUnEnroll"] = false
130-
policeJson["candidates"] = Collections.emptyList<Any>()
126+
policeJson["candidates"] = emptyList<Any>()
131127
}
132128
json["police"] = policeJson
133129

@@ -138,19 +134,15 @@ class GameSessionServiceImpl(
138134
if (Poll.expelCandidates.containsKey(gid)) {
139135
val expelCandidatesList = mutableListOf<Map<String, Any>>()
140136
for (c in Poll.expelCandidates[gid]!!.values) {
141-
val candidateJson: MutableMap<String, Any> = LinkedHashMap()
137+
val candidateJson = mutableMapOf<String, Any>()
142138
candidateJson["id"] = c.player!!.id.toString()
143-
val voters: MutableList<String> = ArrayList()
144-
for (voterId in c.electors) {
145-
voters.add(voterId.toString())
146-
}
147-
candidateJson["voters"] = voters
139+
candidateJson["voters"] = c.electors.map { it.toString() }
148140
expelCandidatesList.add(candidateJson)
149141
}
150142
expelJson["candidates"] = expelCandidatesList
151143
expelJson["voting"] = true
152144
} else {
153-
expelJson["candidates"] = Collections.emptyList<Any>()
145+
expelJson["candidates"] = emptyList<Any>()
154146
expelJson["voting"] = false
155147
}
156148
json["expel"] = expelJson
@@ -166,15 +158,12 @@ class GameSessionServiceImpl(
166158
val logsJson = mutableListOf<Map<String, Any>>()
167159
if (session.logs != null) {
168160
for (log in session.logs) {
169-
val logJson: MutableMap<String, Any> = LinkedHashMap()
161+
val logJson = mutableMapOf<String, Any>()
170162
logJson["id"] = log.id ?: ""
171163
logJson["timestamp"] = formatTimestamp(log.timestamp)
172164
logJson["type"] = log.type?.getSeverity() ?: "INFO"
173165
logJson["message"] = log.message ?: ""
174-
val metadata = log.metadata
175-
if (metadata != null && metadata.isNotEmpty()) {
176-
logJson["metadata"] = metadata
177-
}
166+
log.metadata?.let { if (it.isNotEmpty()) logJson["metadata"] = it }
178167
logsJson.add(logJson)
179168
}
180169
}
@@ -296,7 +285,7 @@ class GameSessionServiceImpl(
296285
if (member.user.isBot)
297286
continue
298287

299-
val memberMap: MutableMap<String, Any> = LinkedHashMap()
288+
val memberMap = mutableMapOf<String, Any>()
300289
memberMap["userId"] = member.id
301290
memberMap["username"] = member.user.name
302291
memberMap["name"] = member.effectiveName
@@ -320,7 +309,7 @@ class GameSessionServiceImpl(
320309
val judgeA = a["isJudge"] as Boolean
321310
val judgeB = b["isJudge"] as Boolean
322311
if (judgeA != judgeB)
323-
if (judgeB) 1 else -1;
312+
if (judgeB) 1 else -1
324313
else
325314
(a["name"] as String).compareTo((b["name"] as String))
326315
}

src/main/kotlin/dev/robothanzo/werewolf/service/impl/PlayerServiceImpl.kt

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import net.dv8tion.jda.api.entities.Role
1313
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel
1414
import org.slf4j.LoggerFactory
1515
import org.springframework.stereotype.Service
16-
import java.util.*
1716
import java.util.concurrent.ConcurrentHashMap
1817

1918
@Service
@@ -49,12 +48,12 @@ class PlayerServiceImpl(
4948
onProgress("開始同步 Discord 狀態...")
5049

5150
val players = session.players
52-
val deleteTasks: MutableList<ActionTask> = ArrayList()
53-
val createRoleTasks: MutableList<ActionTask> = ArrayList()
54-
val createChannelTasks: MutableList<ActionTask> = ArrayList()
51+
val deleteTasks = mutableListOf<ActionTask>()
52+
val createRoleTasks = mutableListOf<ActionTask>()
53+
val createChannelTasks = mutableListOf<ActionTask>()
5554

5655
// Phase 1: Identify deletions
57-
val existingPlayerIds = LinkedList(players.keys)
56+
val existingPlayerIds = players.keys.toMutableList()
5857
for (idStr in existingPlayerIds) {
5958
val pid = idStr.toInt()
6059
if (pid > count) {
@@ -64,7 +63,7 @@ class PlayerServiceImpl(
6463
deleteTasks.add(
6564
ActionTask(
6665
role.delete(),
67-
"刪除身分組: " + role.name
66+
"刪除身分組: ${role.name}"
6867
)
6968
)
7069
}
@@ -73,7 +72,7 @@ class PlayerServiceImpl(
7372
deleteTasks.add(
7473
ActionTask(
7574
channel.delete(),
76-
"刪除頻道: " + channel.name
75+
"刪除頻道: ${channel.name}"
7776
)
7877
)
7978
}
@@ -164,7 +163,7 @@ class PlayerServiceImpl(
164163
.orElseThrow { RuntimeException("Session not found") }
165164
val player = session.players[playerId] ?: throw Exception("Player not found")
166165

167-
val finalRoles = ArrayList(roles)
166+
val finalRoles = roles.toMutableList()
168167
val isDuplicated = roles.contains("複製人")
169168
player.duplicated = isDuplicated
170169
if (isDuplicated && finalRoles.size == 2) {
@@ -187,8 +186,7 @@ class PlayerServiceImpl(
187186
val guild = jda.getGuildById(guildId)
188187
if (guild != null) {
189188
val channel = guild.getTextChannelById(player.channelId)
190-
channel?.sendMessage("法官已將你的身份更改為: " + roles.joinToString(", ")) // Converting List to varargs or just string join? String.join takes Iterable in Java 8+ but Kotlin standard library has joinToString.
191-
// Java String.join is static method.
189+
channel?.sendMessage("法官已將你的身份更改為: ${roles.joinToString(", ")}")
192190
?.queue()
193191
}
194192
}
@@ -213,15 +211,19 @@ class PlayerServiceImpl(
213211
if (roles == null || roles.size < 2)
214212
throw Exception("Not enough roles to switch")
215213

216-
Collections.swap(roles, 0, 1)
214+
roles.let {
215+
val first = it[0]
216+
it[0] = it[1]
217+
it[1] = first
218+
}
217219
sessionRepository.save(session)
218220

219221
val jda = discordService.jda
220222
if (jda != null && player.channelId != 0L) {
221223
val guild = jda.getGuildById(guildId)
222224
if (guild != null) {
223225
val channel = guild.getTextChannelById(player.channelId)
224-
channel?.sendMessage("你已交換了角色順序,現在主要角色為: " + roles[0])?.queue()
226+
channel?.sendMessage("你已交換了角色順序,現在主要角色為: ${roles[0]}")?.queue()
225227
}
226228
}
227229
gameSessionService.broadcastUpdate(guildId)

src/main/kotlin/dev/robothanzo/werewolf/service/impl/PoliceServiceImpl.kt

Lines changed: 29 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent
2121
import net.dv8tion.jda.api.events.interaction.component.EntitySelectInteractionEvent
2222
import org.slf4j.LoggerFactory
2323
import org.springframework.stereotype.Service
24-
import java.util.*
2524
import java.util.concurrent.ConcurrentHashMap
2625

2726
@Service
@@ -81,12 +80,12 @@ class PoliceServiceImpl(
8180
event.guild!!.getTextChannelById(session.courtTextChannelId)
8281
?.sendMessage(event.user.asMention + " 已取消參選")?.queue()
8382

84-
val metadata: MutableMap<String, Any> = HashMap()
83+
val metadata = mutableMapOf<String, Any>()
8584
metadata["playerId"] = candidate.value.player!!.id
8685
metadata["playerName"] = candidate.value.player!!.nickname
8786
session.addLog(
8887
LogType.POLICE_UNENROLLED,
89-
candidate.value.player!!.nickname + " 已取消參選警長", metadata
88+
"${candidate.value.player!!.nickname} 已取消參選警長", metadata
9089
)
9190
gameSessionService.broadcastSessionUpdate(session)
9291
} else {
@@ -106,12 +105,12 @@ class PoliceServiceImpl(
106105
policeSession.candidates[player.id] = Candidate(player = player)
107106
event.hook.editOriginal(":white_check_mark: 已參選").queue()
108107

109-
val metadata: MutableMap<String, Any> = HashMap()
108+
val metadata = mutableMapOf<String, Any>()
110109
metadata["playerId"] = player.id
111110
metadata["playerName"] = player.nickname
112111
session.addLog(
113112
LogType.POLICE_ENROLLED,
114-
player.nickname + " 已參選警長", metadata
113+
"${player.nickname} 已參選警長", metadata
115114
)
116115

117116
gameSessionService.broadcastSessionUpdate(session)
@@ -177,12 +176,10 @@ class PoliceServiceImpl(
177176
return
178177
}
179178

180-
val candidateMentions: MutableList<String> = LinkedList()
181-
for (candidate in policeSession.candidates.values.stream()
182-
.sorted(Candidate.getComparator())
183-
.toList()) {
184-
candidateMentions.add("<@!" + candidate.player!!.userId + ">")
185-
}
179+
val candidateMentions = policeSession.candidates.values.asSequence()
180+
.sortedWith(Candidate.getComparator())
181+
.map { "<@!${it.player!!.userId}>" }
182+
.toMutableList()
186183

187184
if (policeSession.candidates.size == 1) {
188185
if (policeSession.message != null)
@@ -196,10 +193,7 @@ class PoliceServiceImpl(
196193
policeSession.message!!.replyEmbeds(
197194
EmbedBuilder().setTitle("參選警長結束")
198195
.setDescription(
199-
"參選的有: " + java.lang.String.join(
200-
"",
201-
candidateMentions
202-
) + "\n備註:你可隨時再按一次按鈕以取消參選"
196+
"參選的有: ${candidateMentions.joinToString("")}\n備註:你可隨時再按一次按鈕以取消參選"
203197
)
204198
.setColor(MsgUtils.randomColor).build()
205199
).queue()
@@ -273,20 +267,21 @@ class PoliceServiceImpl(
273267
.setDescription("30秒後立刻計票,請加快手速!\n若要改票可直接按下要改成的對象\n若要改為棄票需按下原本投給的使用者")
274268
.setColor(MsgUtils.randomColor)
275269

276-
val buttons: MutableList<Button> = LinkedList()
277-
for (player in policeSession.candidates.values.stream().sorted(Candidate.getComparator()).toList()) {
278-
if (player.quit)
279-
continue
280-
val user = channel.guild.getMemberById(player.player!!.userId!!)
281-
if (user != null) {
282-
buttons.add(
283-
Button.primary(
284-
"votePolice" + player.player!!.id,
285-
player.player!!.nickname + " (" + user.user.name + ")"
270+
val buttons = mutableListOf<Button>()
271+
policeSession.candidates.values.asSequence()
272+
.sortedWith(Candidate.getComparator())
273+
.filter { !it.quit }
274+
.forEach { player ->
275+
val user = channel.guild.getMemberById(player.player!!.userId!!)
276+
if (user != null) {
277+
buttons.add(
278+
Button.primary(
279+
"votePolice${player.player!!.id}",
280+
"${player.player!!.nickname} (${user.user.name})"
281+
)
286282
)
287-
)
283+
}
288284
}
289-
}
290285

291286
channel.sendMessageEmbeds(embedBuilder.build())
292287
.setComponents(MsgUtils.spreadButtonsAcrossActionRows(buttons))
@@ -320,7 +315,7 @@ class PoliceServiceImpl(
320315
val resultEmbed = EmbedBuilder().setTitle("警長投票").setColor(MsgUtils.randomColor)
321316
.setDescription("獲勝玩家: <@!" + winner.player!!.userId + ">")
322317

323-
val wrapper: MutableMap<Long, Map<Int, Candidate>> = HashMap()
318+
val wrapper = mutableMapOf<Long, Map<Int, Candidate>>()
324319
wrapper[channel.guild.idLong] = policeSession.candidates
325320
Poll.sendVoteResult(
326321
policeSession.session!!, channel, policeSession.message!!, resultEmbed, wrapper,
@@ -334,7 +329,7 @@ class PoliceServiceImpl(
334329
val resultEmbed = EmbedBuilder().setTitle("警長投票")
335330
.setColor(MsgUtils.randomColor)
336331
.setDescription("發生平票")
337-
val wrapper: MutableMap<Long, Map<Int, Candidate>> = HashMap()
332+
val wrapper = mutableMapOf<Long, Map<Int, Candidate>>()
338333
wrapper[channel.guild.idLong] = policeSession.candidates
339334
Poll.sendVoteResult(
340335
policeSession.session!!, channel, policeSession.message!!, resultEmbed,
@@ -348,7 +343,7 @@ class PoliceServiceImpl(
348343
.setDescription("平票第二次,警徽撕毀")
349344
if (policeSession.message != null)
350345
policeSession.message!!.reply("平票第二次,警徽撕毀").queue()
351-
val wrapper: MutableMap<Long, Map<Int, Candidate>> = HashMap()
346+
val wrapper = mutableMapOf<Long, Map<Int, Candidate>>()
352347
wrapper[channel.guild.idLong] = policeSession.candidates
353348
Poll.sendVoteResult(
354349
policeSession.session!!, channel, policeSession.message!!, resultEmbed,
@@ -395,12 +390,12 @@ class PoliceServiceImpl(
395390
}
396391
sessionRepository.save(session)
397392

398-
val metadata: MutableMap<String, Any> = HashMap()
393+
val metadata = mutableMapOf<String, Any>()
399394
metadata["playerId"] = winner.player!!.id
400395
metadata["playerName"] = winner.player!!.nickname
401396
session.addLog(
402397
LogType.POLICE_ELECTED,
403-
winner.player!!.nickname + " 當選警長", metadata
398+
"${winner.player!!.nickname} 當當選警長", metadata
404399
)
405400

406401
gameSessionService.broadcastSessionUpdate(session)
@@ -431,7 +426,7 @@ class PoliceServiceImpl(
431426
.setMaxValues(1)
432427

433428
for (p in session.fetchAlivePlayers().values) {
434-
if (Objects.equals(p.userId, player.userId)) continue
429+
if (p.userId == player.userId) continue
435430
val user = discordService.jda!!.getUserById(p.userId!!) // Assuming user cached or available
436431
if (user != null) {
437432
transferSession.possibleRecipientIds.add(p.userId!!)
@@ -476,7 +471,7 @@ class PoliceServiceImpl(
476471
if (session.senderId == event.user.idLong) {
477472
val guildSession = sessionRepository.findByGuildId(event.guild!!.idLong).orElse(null) ?: return
478473
for (player in guildSession.players.values) {
479-
if (Objects.equals(player.userId, target.idLong)) {
474+
if (player.userId == target.idLong) {
480475
session.recipientId = player.id
481476
event.reply(":white_check_mark: 請按下移交來完成移交動作").setEphemeral(true).queue()
482477
break

0 commit comments

Comments
 (0)