Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
uzairname committed Oct 21, 2024
1 parent 240035e commit a01c71b
Show file tree
Hide file tree
Showing 81 changed files with 1,216 additions and 1,262 deletions.
6 changes: 4 additions & 2 deletions src/discord-framework/interactions/deploy_commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ export async function overwriteDiscordCommandsWithViews(

sentry.addBreadcrumb({
category: 'discord',
message: 'Overwrote commands in discord',
message:
`Successfully overwrote application commands` +
(guild_id ? ` in guild ${guild_id}` : ' globally'),
level: 'info',
data: {
commands,
commands: commands.map(c => c.options.name),
guild_id,
},
})
Expand Down
3 changes: 1 addition & 2 deletions src/discord-framework/interactions/respond.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ export async function respondToInteraction(

if (direct_response) {
sentry.addBreadcrumb({
category: 'response',
message: 'Sending direct interaction response',
category: 'Interaction response',
level: 'info',
data: { response: JSON.stringify(response) },
})
Expand Down
8 changes: 4 additions & 4 deletions src/discord-framework/interactions/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as D from 'discord-api-types/v10'
import type { MessageData } from '../rest/objects'
import type { ViewState } from './view_state'
import { AppCommand, MessageView, View } from './views'
import { AppCommand, BaseView, MessageView } from './views'

export type AppCommandInteraction<CommandType extends D.ApplicationCommandType> =
CommandType extends D.ApplicationCommandType.ChatInput
Expand Down Expand Up @@ -35,19 +35,19 @@ type InteractionResponse<InteractionType extends ChatInteraction> =
? ChatInteractionResponse
: never

export type AnyView = View<any>
export type AnyView = BaseView<any>

export type AnyAppCommand = AppCommand<any, D.ApplicationCommandType>

export type ChatInputAppCommand = AppCommand<any, D.ApplicationCommandType.ChatInput>
export type AnyChatInputAppCommand = AppCommand<any, D.ApplicationCommandType.ChatInput>

export type AnyMessageView = MessageView<any, any>

export function viewIsAppCommand(view: AnyView): view is AnyAppCommand {
return view instanceof AppCommand
}

export function viewIsChatInputAppCommand(view: AnyView): view is ChatInputAppCommand {
export function viewIsChatInputAppCommand(view: AnyView): view is AnyChatInputAppCommand {
return viewIsAppCommand(view) && view.options.type === D.ApplicationCommandType.ChatInput
}

Expand Down
8 changes: 4 additions & 4 deletions src/discord-framework/interactions/view_state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { sentry } from '../../logging'
import { StringData, StringDataSchema } from '../../utils/string_data'
import { ViewErrors } from './errors'
import { findView } from './find_view'
import { AnyView, FindViewCallback } from './types'
import { View } from './views'
import { AnyView } from './types'
import { BaseView } from './views'

export class ViewState<TSchema extends StringDataSchema> extends StringData<TSchema> {
set = {} as {
Expand Down Expand Up @@ -35,13 +35,13 @@ export class ViewState<TSchema extends StringDataSchema> extends StringData<TSch
}
}

static fromView<T extends StringDataSchema>(view: View<T>): ViewState<T> {
static fromView<T extends StringDataSchema>(view: BaseView<T>): ViewState<T> {
return new ViewState(view.state_schema, view.options.custom_id_prefix)
}

static fromCustomId(
custom_id: string,
findViewCallback: FindViewCallback,
findViewCallback: any,
): { view: AnyView; state: ViewState<StringDataSchema> } {
let decompressed_custom_id = decompressFromUTF16(custom_id)

Expand Down
6 changes: 3 additions & 3 deletions src/discord-framework/interactions/views.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import type {
} from './types'
import { ViewState } from './view_state'

export abstract class View<TSchema extends StringDataSchema> {
export abstract class BaseView<TSchema extends StringDataSchema> {
name: string
protected constructor(
public options: {
Expand Down Expand Up @@ -156,7 +156,7 @@ export abstract class View<TSchema extends StringDataSchema> {
export class AppCommand<
TSchema extends StringDataSchema,
CommandType extends D.ApplicationCommandType,
> extends View<TSchema> {
> extends BaseView<TSchema> {
constructor(
public options: (CommandType extends D.ApplicationCommandType.ChatInput
? D.RESTPostAPIChatInputApplicationCommandsJSONBody
Expand Down Expand Up @@ -220,7 +220,7 @@ export class AppCommand<
}
}

export class MessageView<TSchema extends StringDataSchema, Params> extends View<TSchema> {
export class MessageView<TSchema extends StringDataSchema, Params> extends BaseView<TSchema> {
constructor(
public readonly options: {
name?: string
Expand Down
4 changes: 2 additions & 2 deletions src/discord-framework/rest/client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DiscordAPIError, InternalRequest, REST, RequestData, RequestMethod } from '@discordjs/rest'
import * as D from 'discord-api-types/v10'
import { sentry } from '../../logging'
import { truncateString } from '../../main/bot/messages/message_pieces'
import { truncateString } from '../../main/bot/utils/converters'
import { cache } from '../../main/cache'
import { DiscordCache } from './cache'
import { DiscordAPIUtils } from './client_helpers'
Expand Down Expand Up @@ -464,10 +464,10 @@ export class DiscordAPIClient extends REST {
level: error ? 'error' : 'info',
data: {
route: `Route: ${method?.toString()} ${route}`,
'time taken': `${Date.now() - start_time}ms`,
options: JSON.stringify(options),
response: truncateString(JSON.stringify(response) ?? '', 1500),
error: JSON.stringify(error),
'time taken': `${Date.now() - start_time}ms`,
},
})
}
Expand Down
23 changes: 8 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
import { Router } from 'itty-router'
import { respondToInteraction } from './discord-framework'
import { initSentry, sentry } from './logging'
import { apiRouter } from './main/api/api_router'
import { authorize } from './main/api/authorize'
import { oauthRouter } from './main/api/oauth'
import { apiRouter } from './main/api/router'
import { initRouter as updateRouter } from './main/api/update_app'
import { App } from './main/app-context/app-context'
import { getFindViewCallback } from './main/bot/view_manager/manage_views'
import { onViewError } from './main/bot/view_manager/on_view_error'
import { updateRouter } from './main/api/update_app'
import { App } from './main/context/app_context'
import { runTests } from './main/test/test'
import { handleInteractionRequest } from './main/bot/manage-views/manage_views'

export default {
fetch(request: Request, env: Env, execution_context: ExecutionContext) {
initSentry(request, env, execution_context)

const app = new App(env)

console.log('app', app)

const router = Router()
.post('/interactions', request =>
respondToInteraction(app.bot, request, getFindViewCallback(app), onViewError(app)),
)
.post('/interactions', request => handleInteractionRequest(app, request))

.get(`/oauth/*`, request => oauthRouter(app).handle(request))

Expand All @@ -35,9 +34,3 @@ export default {
return sentry.withLogging(router.handle)
},
}

export const authorize = (env: Env) => (request: Request) => {
if (request.headers.get('Authorization') !== env.APP_KEY) {
return new Response('Unauthorized', { status: 401 })
}
}
1 change: 1 addition & 0 deletions src/logging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export class Logger extends Toucan {

addBreadcrumb(breadcrumb: object): void {
console.log(JSON.stringify(breadcrumb))
super.addBreadcrumb(breadcrumb)
}

async withLogging(handler: (request: Request) => Promise<Response>): Promise<Response> {
Expand Down
6 changes: 3 additions & 3 deletions src/main/api/router.ts → src/main/api/api_router.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { json, Router } from 'itty-router'
import { App } from '../app-context/app-context'
import { getAllCommandSignatures } from '../bot/view_manager/manage_views'
import views from '../bot/manage-views/all_views'
import { App } from '../context/app_context'

export const apiRouter = (app: App) =>
Router({ base: '/api' })
Expand All @@ -9,7 +9,7 @@ export const apiRouter = (app: App) =>
})
.get('/commands', async request => {
const result = {
'defined global commands': getAllCommandSignatures(app, undefined),
'defined global commands': views.getAllCommandSignatures(app),
}
return json(result)
})
Expand Down
5 changes: 5 additions & 0 deletions src/main/api/authorize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const authorize = (env: Env) => (request: Request) => {
if (request.headers.get('Authorization') !== env.APP_KEY) {
return new Response('Unauthorized', { status: 401 })
}
}
5 changes: 2 additions & 3 deletions src/main/api/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import * as D from 'discord-api-types/v10'
import { Router } from 'itty-router'
import { DiscordAPIClient } from '../../discord-framework'
import { nonNullable } from '../../utils/utils'
import { App } from '../app-context/app-context'
import { App } from '../context/app_context'
import { AccessToken } from '../database/models/models/access_tokens'
import { AppErrors } from '../errors'

export const oauthRouter = (app: App) =>
Router({ base: `/oauth` })
Expand Down Expand Up @@ -83,7 +82,7 @@ export async function saveUserAccessToken(app: App, token: D.RESTPostOAuth2Acces
expires_at: new Date(Date.now() + token.expires_in * 1000),
})
} else {
throw new AppErrors.MissingIdentifyScope()
throw new Error("Can't save oauth token: No identify scope")
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/main/api/update_app.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Router } from 'itty-router'
import { App } from '../app-context/app-context'
import { getAppRoleConnectionsMetadata } from '../bot/modules/linked_roles'
import { syncDiscordCommands } from '../bot/view_manager/manage_views'
import { syncDiscordCommands } from '../bot/manage-views/manage_views'
import { App } from '../context/app_context'

export const initRouter = (app: App) =>
export const updateRouter = (app: App) =>
Router({ base: '/update' })
.post('/', async () => {
await Promise.all([
Expand Down
88 changes: 0 additions & 88 deletions src/main/bot/components/command_helpers.ts

This file was deleted.

24 changes: 24 additions & 0 deletions src/main/bot/manage-views/all_views.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import settings_command from '../modules/admin/views/commands/settings'
import test_module from '../modules/experimental/views/commands/test_command'
import help_command from '../modules/help_command'
import leaderboard_command from '../modules/leaderboard/commands/leaderboard'
import match_history_module from '../modules/matches/logging/views'
import matchmaking_module from '../modules/matches/matchmaking/views'
import record_match_command from '../modules/matches/recording/views/commands/record_match_command'
import stats_command from '../modules/players/views/commands/stats'
import rankings_module from '../modules/rankings/views'
import util_views from '../modules/utils/views'
import { ViewModule } from '../utils/view_module'

export default new ViewModule([
rankings_module,
match_history_module,
matchmaking_module,
util_views,
help_command,
stats_command,
leaderboard_command,
settings_command,
test_module,
record_match_command,
])
16 changes: 16 additions & 0 deletions src/main/bot/manage-views/manage_views.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { overwriteDiscordCommandsWithViews, respondToInteraction } from '../../../discord-framework'
import type { App } from '../../context/app_context'
import views from './all_views'
import { onViewError } from './on_view_error'

export async function handleInteractionRequest(app: App, request: Request) {
return respondToInteraction(app.bot, request, views.getFindViewCallback(app), onViewError(app))
}

export async function syncDiscordCommands(app: App, guild_id?: string) {
await overwriteDiscordCommandsWithViews(
app.bot,
await views.getAllCommandSignatures(app, guild_id),
guild_id,
)
}
Loading

0 comments on commit a01c71b

Please sign in to comment.