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
|
package moe.nea.ledger
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import moe.nea.ledger.database.DBItemEntry
import moe.nea.ledger.database.DBLogEntry
import moe.nea.ledger.database.Database
import moe.nea.ledger.events.ChatReceived
import moe.nea.ledger.utils.Inject
import net.minecraft.client.Minecraft
import net.minecraft.util.ChatComponentText
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent
import java.io.File
import java.text.SimpleDateFormat
import java.time.Instant
import java.util.Date
import java.util.UUID
class LedgerLogger {
fun printOut(text: String) {
Minecraft.getMinecraft().ingameGUI?.chatGUI?.printChatMessage(ChatComponentText(text))
}
val profileIdPattern =
"Profile ID: (?<profile>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})".toPattern()
var currentProfile: UUID? = null
var shouldLog by Ledger.managedConfig.instance.debug::logEntries
@Inject
lateinit var database: Database
@SubscribeEvent
fun onProfileSwitch(event: ChatReceived) {
profileIdPattern.useMatcher(event.message) {
currentProfile = UUID.fromString(group("profile"))
}
}
fun printToChat(entry: LedgerEntry) {
val items = entry.items.joinToString("\n§e") { " - ${it.direction} ${it.count}x ${it.itemId}" }
printOut(
"""
§e================= TRANSACTION START
§eTYPE: §a${entry.transactionType}
§eTIMESTAMP: §a${entry.timestamp}
§e%s
§ePROFILE: §a${currentProfile}
§e================= TRANSACTION END
""".trimIndent().replace("%s", items)
)
}
val entries = JsonArray()
var hasRecentlyMerged = false
var lastMergeTime = System.currentTimeMillis()
fun doMerge() {
val allFiles = folder.listFiles()?.toList() ?: emptyList()
val mergedJson = allFiles
.filter { it.name != "merged.json" && it.extension == "json" }
.sortedDescending()
.map { it.readText().trim().removePrefix("[").removeSuffix("]") }
.joinToString(",", "[", "]")
folder.resolve("merged.json").writeText(mergedJson)
hasRecentlyMerged = true
}
init {
Runtime.getRuntime().addShutdownHook(Thread { doMerge() })
}
@SubscribeEvent
fun onTick(event: ClientTickEvent) {
if (!hasRecentlyMerged && (System.currentTimeMillis() - lastMergeTime) > 60_000L) {
lastMergeTime = System.currentTimeMillis()
doMerge()
}
}
fun logEntry(entry: LedgerEntry) {
if (shouldLog)
printToChat(entry)
Ledger.logger.info("Logging entry of type ${entry.transactionType}")
val transactionId = UUIDUtil.createULIDAt(entry.timestamp)
DBLogEntry.insert(database.connection) {
it[DBLogEntry.profileId] = currentProfile ?: UUIDUtil.NIL_UUID
it[DBLogEntry.playerId] = UUIDUtil.getPlayerUUID()
it[DBLogEntry.type] = entry.transactionType
it[DBLogEntry.transactionId] = transactionId
}
entry.items.forEach { change ->
DBItemEntry.insert(database.connection) {
it[DBItemEntry.transactionId] = transactionId
it[DBItemEntry.mode] = change.direction
it[DBItemEntry.size] = change.count
it[DBItemEntry.itemId] = change.itemId
}
}
entries.add(entry.intoJson(currentProfile))
commit()
}
fun commit() {
try {
hasRecentlyMerged = false
file.writeText(gson.toJson(entries))
} catch (ex: Exception) {
Ledger.logger.error("Could not save file", ex)
}
}
val gson = Gson()
val folder = Ledger.dataFolder
val file: File = run {
val date = SimpleDateFormat("yyyy.MM.dd").format(Date())
generateSequence(0) { it + 1 }
.map {
if (it == 0)
folder.resolve("$date.json")
else
folder.resolve("$date-$it.json")
}
.filter { !it.exists() }
.first()
}
}
enum class TransactionType {
AUCTION_BOUGHT,
AUCTION_SOLD,
AUTOMERCHANT_PROFIT_COLLECT,
BANK_DEPOSIT,
BANK_WITHDRAW,
BAZAAR_BUY_INSTANT,
BAZAAR_BUY_ORDER,
BAZAAR_SELL_INSTANT,
BAZAAR_SELL_ORDER,
BITS_PURSE_STATUS,
BOOSTER_COOKIE_ATE,
COMMUNITY_SHOP_BUY,
DUNGEON_CHEST_OPEN,
KISMET_REROLL,
NPC_BUY,
NPC_SELL,
}
@JvmInline
value class ItemId(
val string: String
) {
companion object {
val COINS = ItemId("SKYBLOCK_COIN")
val BITS = ItemId("SKYBLOCK_BIT")
val NIL = ItemId("SKYBLOCK_NIL")
val DUNGEON_CHEST_KEY = ItemId("DUNGEON_CHEST_KEY")
val BOOSTER_COOKIE = ItemId("BOOSTER_COOKIE")
val KISMET_FEATHER = ItemId("KISMET_FEATHER")
}
}
data class ItemChange(
val itemId: ItemId,
val count: Double,
val direction: ChangeDirection,
) {
enum class ChangeDirection {
GAINED,
TRANSFORM,
SYNC,
CATALYST,
LOST;
}
companion object {
fun gainCoins(number: Double): ItemChange {
return gain(ItemId.COINS, number)
}
fun gain(itemId: ItemId, amount: Number): ItemChange {
return ItemChange(itemId, amount.toDouble(), ChangeDirection.GAINED)
}
fun lose(itemId: ItemId, amount: Number): ItemChange {
return ItemChange(itemId, amount.toDouble(), ChangeDirection.LOST)
}
fun loseCoins(number: Double): ItemChange {
return lose(ItemId.COINS, number)
}
}
}
data class LedgerEntry(
val transactionType: TransactionType,
val timestamp: Instant,
val items: List<ItemChange>,
) {
fun intoJson(profileId: UUID?): JsonObject {
val coinAmount = items.find { it.itemId == ItemId.COINS || it.itemId == ItemId.BITS }?.count
val nonCoins = items.find { it.itemId != ItemId.COINS && it.itemId != ItemId.BITS }
return JsonObject().apply {
addProperty("transactionType", transactionType.name)
addProperty("timestamp", timestamp.toEpochMilli().toString())
addProperty("totalTransactionValue", coinAmount)
addProperty("itemId", nonCoins?.itemId?.string ?: "")
addProperty("itemAmount", nonCoins?.count ?: 0.0)
addProperty("profileId", profileId.toString())
addProperty(
"playerId",
UUIDUtil.getPlayerUUID().toString()
)
}
}
}
|