Skip to content

Commit

Permalink
Merge branch 'main' into chore
Browse files Browse the repository at this point in the history
  • Loading branch information
hmbanan666 authored Jun 26, 2024
2 parents 69dafb3 + 47cd328 commit 576b7a9
Show file tree
Hide file tree
Showing 17 changed files with 161 additions and 58 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"howler": "^2.2.4",
"jsonwebtoken": "^9.0.2",
"lucide-svelte": "^0.396.0",
"pixi.js": "^8.2.0"
"pixi.js": "^8.2.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@antfu/eslint-config": "^2.21.1",
Expand Down
6 changes: 3 additions & 3 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { type Handle, redirect } from '@sveltejs/kit'
import jwt from 'jsonwebtoken'
import { sequence } from '@sveltejs/kit/hooks'
import { env as privateEnv } from '$env/dynamic/private'
import { env as publicEnv } from '$env/dynamic/public'
import type { Profile } from '$lib/types'
import { type Locale, defaultLocale, supportedLocales } from '$lib/translations'
import { env as privateEnv } from '$env/dynamic/private'
import { config } from '$lib/config'

const handleJWT: Handle = ({ event, resolve }) => {
const cookieKey = publicEnv.PUBLIC_COOKIE_KEY ?? ''
const cookieKey = config.cookieKey
const jwtSecret = privateEnv.PRIVATE_JWT_SECRET_KEY

const token = event.cookies.get(cookieKey)
Expand Down
15 changes: 5 additions & 10 deletions src/lib/components/Footer.svelte
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
<script>
import {
DISCORD_SERVER_INVITE_URL,
DONATE_URL,
GITHUB_REPO_URL,
TWITCH_URL,
} from '$lib/config'
import { config } from '$lib/config'
</script>

<footer>
<ul>
<li>
<a href={GITHUB_REPO_URL} target='_blank'>Код на GitHub</a>
<a href={config.githubRepoUrl} target='_blank'>Код на GitHub</a>
</li>
<li>
<a href={DISCORD_SERVER_INVITE_URL} target='_blank'>Discord</a>
<a href={config.discordServerInviteUrl} target='_blank'>Discord</a>
</li>
<li>
<a href={TWITCH_URL} target='_blank'>Twitch</a>
<a href={config.twitch.url} target='_blank'>Twitch</a>
</li>
<li>
<a href={DONATE_URL} target='_blank'>Донат</a>
<a href={config.donateUrl} target='_blank'>Донат</a>
</li>
</ul>

Expand Down
6 changes: 3 additions & 3 deletions src/lib/components/Profile.svelte
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<script>
import { page } from '$app/stores'
import { env } from '$env/dynamic/public'
import twitchIcon from '$lib/assets/website/icons/twitch/112.png'
import { config } from '$lib/config'
const url = new URL('https://id.twitch.tv/oauth2/authorize')
url.searchParams.set('client_id', env.PUBLIC_TWITCH_CLIENT_ID ?? '')
url.searchParams.set('redirect_uri', env.PUBLIC_SIGNIN_REDIRECT_URL ?? '')
url.searchParams.set('client_id', config.twitch.clientId)
url.searchParams.set('redirect_uri', config.signInRedirectUrl)
url.searchParams.set('response_type', 'token')
url.searchParams.set('scope', 'chat:read channel:read:redemptions')
Expand Down
62 changes: 50 additions & 12 deletions src/lib/config.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,50 @@
export const DONATE_URL = 'https://www.donationalerts.com/r/hmbanan666'
export const DISCORD_SERVER_INVITE_URL = 'https://discord.gg/B6etUajrGZ'
export const TWITCH_URL = 'https://www.twitch.tv/hmbanan666'
export const GITHUB_REPO_URL = 'https://github.com/hmbanan666/chat-game'

export const TWITCH_CHANNEL_REWARDS = {
add150ViewerPointsId: 'd8237822-c943-434f-9d7e-87a9f549f4c4',
villainStealFuelId: 'd5956de4-54ff-49e4-afbe-ee4e62718eee',
addNewIdea: '289457e8-18c2-4b68-8564-fc61dd60b2a2',
}

export const ADMIN_PLAYER_ID = 'svhjz9p5467wne9ybasf1bwy'
import { z } from 'zod'
import { env as publicEnv } from '$env/dynamic/public'

/**
* Здесь объявляется схема конфигурации приложения.
* Содержит только публичные переменные окружения.
*
* Приватные переменные окружения хранятся в '$env/dynamic/private'
* По политике безопасности они не должны быть доступны на клиенте.
* И каждое использование приватной переменной окружения должно в ручном режиме.
*/

const allEnv = z.object({
PUBLIC_COOKIE_KEY: z.string().default(''),
PUBLIC_SIGNIN_REDIRECT_URL: z.string().default(''),
PUBLIC_WEBSOCKET_URL: z.string().default(''),
PUBLIC_DONATE_URL: z.string().default('https://www.donationalerts.com/r/hmbanan666'),
PUBLIC_GITHUB_REPO_URL: z.string().default('https://github.com/hmbanan666/chat-game'),
PUBLIC_DISCORD_SERVER_INVITE_URL: z.string().default('https://discord.gg/B6etUajrGZ'),
PUBLIC_GAME_ADMIN_PLAYER_ID: z.string().default('svhjz9p5467wne9ybasf1bwy'),
PUBLIC_TWITCH_CLIENT_ID: z.string().default(''),
PUBLIC_TWITCH_URL: z.string().default('https://www.twitch.tv/hmbanan666'),
PUBLIC_TWITCH_CHANNEL_REWARDS: z.string().default(JSON.stringify({
add150ViewerPointsId: 'd8237822-c943-434f-9d7e-87a9f549f4c4',
villainStealFuelId: 'd5956de4-54ff-49e4-afbe-ee4e62718eee',
addNewIdea: '289457e8-18c2-4b68-8564-fc61dd60b2a2',
})),
})

const ConfigSchema = allEnv.transform((value) => {
return {
cookieKey: value.PUBLIC_COOKIE_KEY,
signInRedirectUrl: value.PUBLIC_SIGNIN_REDIRECT_URL,
websocketUrl: value.PUBLIC_WEBSOCKET_URL,
donateUrl: value.PUBLIC_DONATE_URL,
githubRepoUrl: value.PUBLIC_GITHUB_REPO_URL,
discordServerInviteUrl: value.PUBLIC_DISCORD_SERVER_INVITE_URL,
game: {
adminPlayerId: value.PUBLIC_GAME_ADMIN_PLAYER_ID,
},
twitch: {
clientId: value.PUBLIC_TWITCH_CLIENT_ID,
url: value.PUBLIC_TWITCH_URL,
rewards: JSON.parse(value.PUBLIC_TWITCH_CHANNEL_REWARDS),
},
}
})

export type Config = z.infer<typeof ConfigSchema>
export const config: Config = ConfigSchema.parse(publicEnv)
12 changes: 12 additions & 0 deletions src/lib/game/baseGame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ import { PlayerService } from '$lib/game/services/player/playerService'
import { Raider } from '$lib/game/objects/units/raider'
import { QuestService } from '$lib/game/services/quest/questService'
import type { Wagon } from '$lib/game/services/wagon/interface'
import type { Broker } from '$lib/game/services/broker/interface'
import { BrokerService } from '$lib/game/services/broker/brokerService'

interface BaseGameOptions {
isSocketOn?: boolean
Expand All @@ -52,6 +54,7 @@ export class BaseGame extends Container implements Game {
tick: Game['tick'] = 0
group: Group

brokerService: Broker
actionService: ActionService
eventService: EventService
tradeService: TradeService
Expand Down Expand Up @@ -82,6 +85,7 @@ export class BaseGame extends Container implements Game {
this.bg = new BackgroundGenerator(this.app)
this.group = new Group()

this.brokerService = new BrokerService()
this.actionService = new ActionService(this)
this.eventService = new EventService(this)
this.tradeService = new TradeService(this)
Expand Down Expand Up @@ -236,6 +240,14 @@ export class BaseGame extends Container implements Game {
this.removeChild(...this.children)
}

subscribe(event: string, callback: Function) {
return this.brokerService.register(event, callback)
}

dispatch<T>(event: string, arg?: T) {
this.brokerService.dispatch(event, arg)
}

#updateObjects() {
for (const object of this.children) {
object.animate()
Expand Down
19 changes: 7 additions & 12 deletions src/lib/game/services/action/actionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,7 @@ import type {
IGameActionResponse,
IGameSceneAction, ItemType,
} from '$lib/game/types'
import {
ADMIN_PLAYER_ID,
DISCORD_SERVER_INVITE_URL,
DONATE_URL,
GITHUB_REPO_URL,
} from '$lib/config'
import { config } from '$lib/config'
import type { GameAction } from '$lib/game/actions/interface'
import { TreeObject } from '$lib/game/objects/treeObject'
import { Route } from '$lib/game/services/route/route'
Expand Down Expand Up @@ -138,21 +133,21 @@ export class ActionService implements GameActionService {
}
if (action === 'START_CHANGING_SCENE') {
// Admin only
if (player.id !== ADMIN_PLAYER_ID) {
if (player.id !== config.game.adminPlayerId) {
return ANSWER.ERROR
}
return this.startChangingSceneAction(player, params)
}
if (action === 'START_GROUP_BUILD') {
// Admin only
if (player.id !== ADMIN_PLAYER_ID) {
if (player.id !== config.game.adminPlayerId) {
return ANSWER.ERROR
}
return this.startGroupBuildAction(player, params)
}
if (action === 'DISBAND_GROUP') {
// Admin only
if (player.id !== ADMIN_PLAYER_ID) {
if (player.id !== config.game.adminPlayerId) {
return ANSWER.ERROR
}
return this.disbandGroupAction()
Expand Down Expand Up @@ -546,7 +541,7 @@ export class ActionService implements GameActionService {

return {
ok: true,
message: `${player.name}, this is an interactive chat game that any viewer can participate in! Basic commands: !chop, !mine. The remaining commands appear in events (on the right of the screen). Join our community: ${DISCORD_SERVER_INVITE_URL}`,
message: `${player.name}, this is an interactive chat game that any viewer can participate in! Basic commands: !chop, !mine. The remaining commands appear in events (on the right of the screen). Join our community: ${config.discordServerInviteUrl}`,
}
}

Expand All @@ -557,7 +552,7 @@ export class ActionService implements GameActionService {

return {
ok: true,
message: `${player.name}, the game code is in the repository: ${GITHUB_REPO_URL}`,
message: `${player.name}, the game code is in the repository: ${config.githubRepoUrl}`,
}
}

Expand All @@ -567,7 +562,7 @@ export class ActionService implements GameActionService {
}
return {
ok: true,
message: `${player.name}, support the game: ${DONATE_URL}`,
message: `${player.name}, support the game: ${config.donateUrl}`,
}
}

Expand Down
42 changes: 42 additions & 0 deletions src/lib/game/services/broker/brokerService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { Broker, Registry, Subscriber } from './interface'

export class BrokerService implements Broker {
private subscribers: Subscriber
private static nextId = 0

constructor() {
this.subscribers = {}
}

public dispatch<T>(event: string, arg?: T): void {
const subscriber = this.subscribers[event]

if (subscriber === undefined) {
return
}

Object.keys(subscriber).forEach((key) => subscriber[key](arg))
}

public register(event: string, callback: Function): Registry {
const id = this.getNextId()
if (!this.subscribers[event]) {
this.subscribers[event] = {}
}

this.subscribers[event][id] = callback

return {
unregister: () => {
delete this.subscribers[event][id]
if (Object.keys(this.subscribers[event]).length === 0) {
delete this.subscribers[event]
}
},
}
}

private getNextId(): number {
return BrokerService.nextId++
}
}
16 changes: 16 additions & 0 deletions src/lib/game/services/broker/interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export interface Registry {
unregister: () => void
}

export interface Callable {
[key: string]: Function
}

export interface Subscriber {
[key: string]: Callable
}

export interface Broker {
dispatch: <T>(event: string, arg?: T) => void
register: (event: string, callback: Function) => Registry
}
4 changes: 2 additions & 2 deletions src/lib/game/services/socket/webSocketService.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { WebSocketMessage } from '@hmbanan666/chat-game-api'
import type { Game } from '$lib/game/types'
import type { GameWebSocketService } from '$lib/game/services/socket/interface'
import { env } from '$env/dynamic/public'
import { browser } from '$app/environment'
import { config } from '$lib/config'

export class WebSocketService implements GameWebSocketService {
socket!: WebSocket
Expand Down Expand Up @@ -47,7 +47,7 @@ export class WebSocketService implements GameWebSocketService {
}

#init() {
this.socket = new WebSocket(env.PUBLIC_WEBSOCKET_URL ?? '', [this.game.id])
this.socket = new WebSocket(config.websocketUrl ?? '', [this.game.id])

this.#setMessagesPerSecondHandler()

Expand Down
4 changes: 2 additions & 2 deletions src/lib/server/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChatGameAPI } from '@hmbanan666/chat-game-api'
import { env } from '$env/dynamic/private'
import { env as privateEnv } from '$env/dynamic/private'

export const api = new ChatGameAPI(env.PRIVATE_WEBSITE_BEARER ?? '')
export const api = new ChatGameAPI(privateEnv.PRIVATE_WEBSITE_BEARER ?? '')
6 changes: 2 additions & 4 deletions src/routes/[lang]/(game)/play/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { env } from '$env/dynamic/public'
import { config } from '$lib/config'

export async function load({ cookies }) {
const cookieKey = env.PUBLIC_COOKIE_KEY ?? ''

return {
gameProfileJWT: cookies.get(cookieKey),
gameProfileJWT: cookies.get(config.cookieKey),
}
}
3 changes: 2 additions & 1 deletion src/routes/[lang]/(game)/play/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
<script lang='ts'>
import { onMount } from 'svelte'
import { onMount, setContext } from 'svelte'
import GameInterface from './GameInterface.svelte'
import { BaseGame } from '$lib/game/baseGame'
import { page } from '$app/stores'
const game = new BaseGame({ isSocketOn: true, profileJWT: $page.data.gameProfileJWT })
setContext('game', game)
let gameElement: HTMLElement
const handleVisibilityChange = () => {
Expand Down
4 changes: 2 additions & 2 deletions src/routes/[lang]/(website)/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang='ts'>
import { onMount } from 'svelte'
import { TWITCH_URL } from '$lib/config'
import { config } from '$lib/config'
import { BaseGame } from '$lib/game/baseGame'
import { pluralizationRu } from '$lib/utils/locale'
Expand Down Expand Up @@ -75,7 +75,7 @@
перерыв, пока зрители развлекаются или...</p>
<p class='mt-2'>За все время
создано {profileCount} {profileDesc}. Присоединяйся <a
href={TWITCH_URL} target='_blank'
href={config.twitch.url} target='_blank'
class='twitch-link'>на активном
стриме</a>!</p>
</section>
Expand Down
4 changes: 2 additions & 2 deletions src/routes/auth/profile/+server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type RequestHandler, error, json } from '@sveltejs/kit'
import { env } from '$env/dynamic/public'
import { config } from '$lib/config'

export const GET: RequestHandler = async ({ locals }) => {
if (!locals.profile) {
Expand All @@ -10,7 +10,7 @@ export const GET: RequestHandler = async ({ locals }) => {
}

export const DELETE: RequestHandler = async ({ cookies }) => {
const cookieKey = env.PUBLIC_COOKIE_KEY
const cookieKey = config.cookieKey
if (!cookieKey) {
error(500, 'Config problem')
}
Expand Down
Loading

0 comments on commit 576b7a9

Please sign in to comment.