Skip to content

Commit

Permalink
typecheck passes, yuhei
Browse files Browse the repository at this point in the history
  • Loading branch information
Entkenntnis committed Oct 28, 2024
1 parent e5d9378 commit c87562d
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 35 deletions.
16 changes: 11 additions & 5 deletions src/content/challenges-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ const orakelMsgEn = [
'You are speaking to the secretary.',
]

/**
* @param {import("../data/types.js").App} App
*/
export function setupChallengesServer(App) {
App.express.get('/chal/chal46', (req, res) => {
res.set('X-ANTWORT', secrets('chal_46'))
Expand Down Expand Up @@ -141,7 +144,9 @@ export function setupChallengesServer(App) {
}
}

const mazeMessages = req.lng === 'de' ? mazeMessagesDe : mazeMessagesEn
const mazeMessages = /** @type {{[key: string]: string}} */ (
req.lng === 'de' ? mazeMessagesDe : mazeMessagesEn
)
if (mazeMessages[key]) message = mazeMessages[key]

if (!message)
Expand Down Expand Up @@ -183,7 +188,7 @@ export function setupChallengesServer(App) {
})

App.express.get('/chal/maze/east', (req, res) => {
if (!req.session || !req.session.userId)
if (!req.session || !req.session.userId || !req.session.maze)
return res.send(req.lng === 'de' ? 'Bitte einloggen.' : 'Please log in.')
const pos = req.session.maze
if (pos && maze[pos.y][pos.x + 1] !== 'x') {
Expand All @@ -193,7 +198,7 @@ export function setupChallengesServer(App) {
})

App.express.get('/chal/maze/south', (req, res) => {
if (!req.session || !req.session.userId)
if (!req.session || !req.session.userId || !req.session.maze)
return res.send(req.lng === 'de' ? 'Bitte einloggen.' : 'Please log in.')
const pos = req.session.maze
if (pos && maze[pos.y + 1][pos.x] !== 'x') {
Expand All @@ -203,7 +208,7 @@ export function setupChallengesServer(App) {
})

App.express.get('/chal/maze/west', (req, res) => {
if (!req.session || !req.session.userId)
if (!req.session || !req.session.userId || !req.session.maze)
return res.send(req.lng === 'de' ? 'Bitte einloggen.' : 'Please log in.')
const pos = req.session.maze
if (pos && maze[pos.y][pos.x - 1] !== 'x') {
Expand All @@ -213,7 +218,7 @@ export function setupChallengesServer(App) {
})

App.express.get('/chal/maze/north', (req, res) => {
if (!req.session || !req.session.userId)
if (!req.session || !req.session.userId || !req.session.maze)
return res.send(req.lng === 'de' ? 'Bitte einloggen.' : 'Please log in.')
const pos = req.session.maze
if (pos && maze[pos.y - 1][pos.x] !== 'x') {
Expand Down Expand Up @@ -287,6 +292,7 @@ export function setupChallengesServer(App) {
if (!req.headers.authorization)
return res.status(401).send('No authorization header provided')
// Check if the authorization header is valid
/** @param {string} value */
function checkAuthorization(value) {
const parts = value.split(' ')
if (parts.length !== 2) return false
Expand Down
68 changes: 42 additions & 26 deletions src/content/mortal-coil.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import fs from 'node:fs'
import { Sequelize } from 'sequelize'
import { Sequelize, Op } from 'sequelize'
import { capitalizeFirstLetter, generateToken } from '../helper/helper.js'
import { renderPage } from '../helper/render-page.js'

const maxLevel = 200

Expand All @@ -13,7 +14,7 @@ const levels = JSON.parse(
export function setupMortalCoil(App) {
App.express.get('/mortal-coil/submit', async (req, res) => {
try {
const level = parseInt(req.query.level)
const level = parseInt(req.query.level?.toString() ?? '-1')
const token = typeof req.query.token === 'string' ? req.query.token : ''

if (!token) {
Expand All @@ -40,7 +41,7 @@ export function setupMortalCoil(App) {
const isEditor = req.user && App.config.editors.includes(req.user.name)

const storageKey = `mortalcoil_${userid}`
const fromDB = parseInt(await App.storage.getItem(storageKey)) // should be fine
const fromDB = parseInt((await App.storage.getItem(storageKey)) ?? '-1') // should be fine
const playerLevel = isEditor
? maxLevel - 1
: isNaN(fromDB)
Expand All @@ -53,16 +54,16 @@ export function setupMortalCoil(App) {

let isCorrect = verifyLevel(
level,
parseInt(req.query.x),
parseInt(req.query.y),
req.query.path
parseInt(req.query.x?.toString() ?? '-1'),
parseInt(req.query.y?.toString() ?? '-1'),
req.query.path?.toString() ?? ''
)

if (isCorrect) {
const unlockedLevel = level + 1
if (unlockedLevel > playerLevel) {
const storageKey = `mortalcoil_${userid}`
await App.storage.setItem(storageKey, playerLevel + 1)
await App.storage.setItem(storageKey, (playerLevel + 1).toString())
}
return res.send('ok')
}
Expand All @@ -77,12 +78,12 @@ export function setupMortalCoil(App) {
return res.redirect('/')
}

const queryLevel = parseInt(req.query.level)
const queryLevel = parseInt(req.query.level?.toString() ?? '-1')

const isEditor = App.config.editors.includes(req.user.name)

const storageKey = `mortalcoil_${req.user.id}`
const fromDB = parseInt(await App.storage.getItem(storageKey)) // should be fine
const fromDB = parseInt((await App.storage.getItem(storageKey)) ?? '-1') // should be fine
const playerLevel = isEditor
? maxLevel - 1
: isNaN(fromDB)
Expand Down Expand Up @@ -127,7 +128,7 @@ export function setupMortalCoil(App) {

const levelData = levels[level]

res.renderPage({
renderPage(App, req, res, {
page: 'mortal-coil',
heading: 'Mortal Coil - Level ' + level,
backButton: false,
Expand Down Expand Up @@ -209,10 +210,10 @@ export function setupMortalCoil(App) {
const allUsers = await App.db.models.KVPair.findAll({
where: {
key: {
[Sequelize.Op.like]: 'mortalcoil_%',
[Op.like]: 'mortalcoil_%',
},
updatedAt: {
[Sequelize.Op.gte]: new Date(cutoff),
[Op.gte]: new Date(cutoff),
},
},
raw: true,
Expand All @@ -222,6 +223,7 @@ export function setupMortalCoil(App) {
return parseInt(entry.value)
})

/** @type {{[key: number]: number}} */
const count = {}

for (let i = 1; i <= maxLevel; i++) {
Expand All @@ -232,17 +234,21 @@ export function setupMortalCoil(App) {

const entries = Object.entries(count)

const lastActive = await App.db.models.KVPair.findAll({
where: {
key: {
[Sequelize.Op.like]: 'mortalcoil_%',
},
},
order: [['updatedAt', 'DESC']],
limit: 10,
raw: true,
})
const lastActive =
/** @type {(import('../data/types.js').KVPairModel & {id?: number})[]} */ (
await App.db.models.KVPair.findAll({
where: {
key: {
[Op.like]: 'mortalcoil_%',
},
},
order: [['updatedAt', 'DESC']],
limit: 10,
raw: true,
})
)

/** @type {number[]} */
const userIds = []

lastActive.forEach((entry) => {
Expand All @@ -258,7 +264,7 @@ export function setupMortalCoil(App) {
const userNameIndex = userNames.reduce((res, obj) => {
res[obj.id] = obj.name
return res
}, {})
}, /** @type {{[key: number]: string}} */ ({}))

const stringsDe = {
statistics: 'Statistik',
Expand All @@ -280,7 +286,7 @@ export function setupMortalCoil(App) {

const strings = req.lng == 'de' ? stringsDe : stringsEn

res.renderPage({
renderPage(App, req, res, {
page: 'decode-me-stats',
heading: 'Mortal Coil - ' + strings.statistics,
backButton: false,
Expand All @@ -293,7 +299,7 @@ export function setupMortalCoil(App) {
${lastActive
.map((entry) => {
return `<li>Level ${entry.value} ${strings.by} ${
userNameIndex[entry.id]
userNameIndex[entry.id ?? 0]
} ${App.moment(new Date(entry.updatedAt))
.locale(req.lng)
.fromNow()}</li>`
Expand Down Expand Up @@ -346,6 +352,12 @@ export function setupMortalCoil(App) {
})
}

/**
* @param {number} level
* @param {number} x
* @param {number} y
* @param {string} path
*/
function verifyLevel(level, x, y, path) {
const { height, width, boardStr } = levels[level]

Expand All @@ -357,7 +369,7 @@ function verifyLevel(level, x, y, path) {
for (let row = 0; row < height; ++row) {
board[row] = new Array(width)
for (let col = 0; col < width; ++col) {
isWall = boardStr.charAt(row * width + col) === 'X'
let isWall = boardStr.charAt(row * width + col) === 'X'
board[row][col] = { wall: isWall, visited: isWall }
}
}
Expand All @@ -383,6 +395,10 @@ function verifyLevel(level, x, y, path) {
}
}

/**
* @param {number} dx
* @param {number} dy
*/
function move(dx, dy) {
let x = cur.x + dx
let y = cur.y + dy
Expand Down
9 changes: 5 additions & 4 deletions src/data/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,11 @@ declare module 'express-session' {
loginFail: boolean
rates: { [key: string]: { count: number; lockedUntil: number } }
chal117?: DungeonData
chal303_ts: number
chal303_result: string
chal338_ts: number
chal338_result: string
chal303_ts?: number
chal303_result?: string
chal338_ts?: number
chal338_result?: string
maze?: { x: number; y: number }
}
}

Expand Down

0 comments on commit c87562d

Please sign in to comment.