-
Notifications
You must be signed in to change notification settings - Fork 0
/
amq-song-guess-rate.ts
77 lines (64 loc) · 2.36 KB
/
amq-song-guess-rate.ts
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
import { getDetailedSongInfo } from '../lib/amq/getDetailedSongInfo'
import { onReady } from '../lib/amq/onReady'
import { makeSha256HexDigest } from '../lib/makeSha256HexDigest'
import { GM_Value } from '../lib/tampermonkey/GM_Value'
import type { AnswerResultsEvent } from '../types/amq'
type GuessCount = {
correct: number
total: number
}
const increment = async (key: string, isCorrect: boolean) => {
const hashKey = await makeSha256HexDigest(key)
const value = new GM_Value<GuessCount>(hashKey, { correct: 0, total: 0 })
const count = value.get()
count.total++
if (isCorrect) {
count.correct++
}
value.set(count)
return count
}
// 互換性のため、ハッシュ化以前のカウンターを移行する
const migrate = async () => {
const regex = /^[\da-f]{64}$/
const oldKeys = GM_listValues().filter((k) => regex.exec(k) === null)
await Promise.all(
oldKeys.map(async (key) => {
const hashKey = await makeSha256HexDigest(key)
const value = new GM_Value<GuessCount>(hashKey, { correct: 0, total: 0 })
const count = value.get()
const oldValue = new GM_Value<GuessCount>(hashKey, { correct: 0, total: 0 }, false)
const oldCount = oldValue.get()
count.total += oldCount.total
count.correct += oldCount.correct
value.set(count)
oldValue.delete()
})
)
}
onReady(() => {
getDetailedSongInfo()
.then(({ register }) => {
register({
id: 'guess-rate-row',
title: 'Guess Rate',
async content(event: AnswerResultsEvent): Promise<string | null> {
const self = Object.values(unsafeWindow.quiz.players).find((p) => p.isSelf && p._inGame)
if (!self) {
return null
}
const isCorrect = event.players.find((p) => p.gamePlayerId === self.gamePlayerId)?.correct === true
const count = await increment(`${event.songInfo.songName}_${event.songInfo.artist}`, isCorrect)
return `${count.correct} / ${count.total} (${((count.correct / count.total) * 100).toFixed(1)} %)`
},
})
})
.catch(console.error)
migrate().catch(console.error)
AMQ_addScriptData({
name: 'Song Guess Rate',
author: 'SlashNephy <spica@starry.blue>',
description:
'Display guess rates per song in side panel of the song. (Requires AMQ Detailed Song Info plugin: version 0.3.0 or higher)',
})
})