From dc2ff172b0ee9f747af70189d322e01feb9d58a3 Mon Sep 17 00:00:00 2001 From: Benjamin Sherriff Date: Sat, 2 Dec 2023 13:52:01 -0500 Subject: [PATCH] Refactored and fixed api endpoints --- service/docker-compose.yml | 2 +- service/src/bot/api/routes.rs | 39 ++--- service/src/bot/commands/oai.rs | 6 +- service/src/dnd/spells/routes.rs | 6 +- service/src/lib.rs | 2 +- service/src/storage/messages/routes.rs | 4 +- ui/src/api/guilds.ts | 11 +- ui/src/api/index.ts | 5 + ui/src/app/admin/page.tsx | 201 +++++++++++++++++++++++++ ui/src/app/management/page.tsx | 140 ----------------- ui/src/components/Header/index.tsx | 4 +- 11 files changed, 238 insertions(+), 182 deletions(-) create mode 100644 ui/src/app/admin/page.tsx delete mode 100644 ui/src/app/management/page.tsx diff --git a/service/docker-compose.yml b/service/docker-compose.yml index 1997cd7..6550479 100644 --- a/service/docker-compose.yml +++ b/service/docker-compose.yml @@ -1,6 +1,6 @@ version: '3.8' -x-env_file_personifi: &env +x-env_file: &env - .env name: siren diff --git a/service/src/bot/api/routes.rs b/service/src/bot/api/routes.rs index 25c8be5..a75ff26 100644 --- a/service/src/bot/api/routes.rs +++ b/service/src/bot/api/routes.rs @@ -4,7 +4,7 @@ use actix_web::{get, post, web, HttpResponse, ResponseError}; use log::warn; use serde::{Serialize, Deserialize}; use serenity::model::prelude::{GuildChannel, ChannelType}; -use siren::ServiceError; +use siren::{ServiceError, Response}; use crate::{AppState, bot::commands::audio::{play::play_track, join}, storage::guilds::QueryGuild, auth::{JwtAuth, verify_role}}; @@ -22,7 +22,10 @@ async fn get_guilds(data: web::Data>, auth: JwtAuth) -> HttpRespon message: err.to_string() }) }; - HttpResponse::Ok().json(guilds) + HttpResponse::Ok().json(Response { + data: guilds, + metadata: None + }) } #[get("/{id}/text")] @@ -39,7 +42,10 @@ async fn get_text_channels(id: web::Path, data: web::Data> message: err.to_string() }) }; - HttpResponse::Ok().json(channels) + HttpResponse::Ok().json(Response { + data: channels, + metadata: None + }) } #[get("/{id}/voice")] @@ -56,7 +62,10 @@ async fn get_voice_channels(id: web::Path, data: web::Data message: err.to_string() }) }; - HttpResponse::Ok().json(channels) + HttpResponse::Ok().json(Response { + data: channels, + metadata: None + }) } #[derive(Serialize, Deserialize)] @@ -74,7 +83,6 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json() { Ok(id) => id, Err(err) => { - warn!("Could not parse guild id: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -84,7 +92,6 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json() { Ok(id) => id, Err(err) => { - warn!("Could not parse channel id: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -95,7 +102,6 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json channels, Err(err) => { - warn!("Could not get channels: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -106,7 +112,6 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json channel, None => { - warn!("Could not find channel with id {}", channel_id); return ResponseError::error_response(&ServiceError { status: 422, message: format!("Could not find channel with id {}", channel_id) @@ -115,7 +120,6 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json, play_request: web::Json() { Ok(id) => id, Err(err) => { - warn!("Could not parse guild id: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() }) } }; let channel_id = match channel_id.parse::() { Ok(id) => id, Err(err) => { - warn!("Could not parse channel id: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() }) } }; @@ -155,14 +157,12 @@ async fn play(path: web::Path<(String, String)>, play_request: web::Json guild, Err(err) => { - warn!("Could not get guild: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() }) } }; let channel = match http.get_channel(channel_id).await { Ok(channel) => channel, Err(err) => { - warn!("Could not get channel: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() }) } }; @@ -174,13 +174,11 @@ async fn play(path: web::Path<(String, String)>, play_request: web::Json HttpResponse::Ok().finish(), Err(err) => { - warn!("Could not play track: {:?}", err); return ResponseError::error_response(&err) } } }, Err(err) => { - warn!("Could not join channel: {:?}", err); return ResponseError::error_response(&ServiceError { status: 500, message: err.to_string() }) } } @@ -196,7 +194,6 @@ async fn stop(path: web::Path, data: web::Data>, auth: Jwt let guild_id = match guild_id.parse::() { Ok(id) => id, Err(err) => { - warn!("Could not parse guild id: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -222,7 +219,6 @@ async fn resume(path: web::Path, data: web::Data>, auth: J let guild_id = match guild_id.parse::() { Ok(id) => id, Err(err) => { - warn!("Could not parse guild id: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -233,7 +229,6 @@ async fn resume(path: web::Path, data: web::Data>, auth: J if let Some(handler_lock) = data.songbird.get(guild_id) { let handler = handler_lock.lock().await; if let Err(err) = handler.queue().resume() { - warn!("Could not resume track: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -254,7 +249,6 @@ async fn pause(path: web::Path, data: web::Data>, auth: Jw let guild_id = match guild_id.parse::() { Ok(id) => id, Err(err) => { - warn!("Could not parse guild id: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -265,7 +259,6 @@ async fn pause(path: web::Path, data: web::Data>, auth: Jw if let Some(handler_lock) = data.songbird.get(guild_id) { let handler = handler_lock.lock().await; if let Err(err) = handler.queue().pause() { - warn!("Could not pause track: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -291,7 +284,6 @@ async fn get_volume(path: web::Path, auth: JwtAuth) -> HttpResponse { let guild_id = match guild_id.parse::() { Ok(id) => id, Err(err) => { - warn!("Could not parse guild id: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -302,7 +294,6 @@ async fn get_volume(path: web::Path, auth: JwtAuth) -> HttpResponse { let volume = match QueryGuild::get(guild_id as i64) { Ok(guild) => guild.volume, Err(err) => { - warn!("Could not get volume: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -323,7 +314,6 @@ async fn set_volume(path: web::Path, volume: web::Json::, dat let guild_id = match guild_id.parse::() { Ok(id) => id, Err(err) => { - warn!("Could not parse guild id: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -337,7 +327,6 @@ async fn set_volume(path: web::Path, volume: web::Json::, dat let guild = match http.get_guild(guild_id).await { Ok(guild) => guild, Err(err) => { - warn!("Could not get guild: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() }) } }; @@ -356,7 +345,6 @@ async fn skip(path: web::Path, data: web::Data>, auth: Jwt let guild_id = match guild_id.parse::() { Ok(id) => id, Err(err) => { - warn!("Could not parse guild id: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() @@ -367,7 +355,6 @@ async fn skip(path: web::Path, data: web::Data>, auth: Jwt if let Some(handler_lock) = data.songbird.get(guild_id) { let handler = handler_lock.lock().await; if let Err(err) = handler.queue().skip() { - warn!("Could not skip track: {:?}", err); return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() diff --git a/service/src/bot/commands/oai.rs b/service/src/bot/commands/oai.rs index 2727f58..7a5cc44 100644 --- a/service/src/bot/commands/oai.rs +++ b/service/src/bot/commands/oai.rs @@ -6,7 +6,7 @@ use serenity::model::Permissions; use serenity::model::channel::Message; use serenity::model::prelude::{ChannelType, PermissionOverwrite, PermissionOverwriteType}; use serenity::prelude::*; -use siren::{GetResponse, ServiceError}; +use siren::{Response, ServiceError}; pub struct OAI { pub client: reqwest::Client, @@ -160,7 +160,7 @@ impl OAI { Ok(response) } - async fn get_messages(&self, guild_id: u64, channel_id: u64, author_id: u64) -> Result>, ServiceError> { + async fn get_messages(&self, guild_id: u64, channel_id: u64, author_id: u64) -> Result>, ServiceError> { let uri = format!("{}/messages?guild_id={}&channel_id={}&author_id={}&limit={}", self.service_url, guild_id, channel_id, author_id, self.max_context_questions); let value = self.client .get(&uri) @@ -169,7 +169,7 @@ impl OAI { .json::() .await?; - let response = serde_json::from_value::>>(value)?; + let response = serde_json::from_value::>>(value)?; Ok(response) } diff --git a/service/src/dnd/spells/routes.rs b/service/src/dnd/spells/routes.rs index 62f8eec..095028f 100644 --- a/service/src/dnd/spells/routes.rs +++ b/service/src/dnd/spells/routes.rs @@ -1,7 +1,7 @@ use actix_web::{get, post, put, delete, web, HttpResponse, HttpRequest, ResponseError}; use log::error; use serde::{Serialize, Deserialize}; -use siren::{GetResponse, Metadata, ServiceError}; +use siren::{Response, Metadata, ServiceError}; use crate::{dnd::spells::{QuerySpell, QueryFilters}, auth::{JwtAuth, verify_role}}; @@ -90,7 +90,7 @@ async fn get_all(req: HttpRequest) -> HttpResponse { spell.id = Some(id); response.push(spell); } - HttpResponse::Ok().json(GetResponse { + HttpResponse::Ok().json(Response { data: response, metadata: Some(Metadata { total: total_count as i32, @@ -121,7 +121,7 @@ async fn get_by_id(id: web::Path) -> HttpResponse { let id = query_spell.id; let mut spell = Spell::from(query_spell); spell.id = Some(id); - HttpResponse::Ok().json(GetResponse { + HttpResponse::Ok().json(Response { data: spell, metadata: None }) diff --git a/service/src/lib.rs b/service/src/lib.rs index d04808b..da781df 100644 --- a/service/src/lib.rs +++ b/service/src/lib.rs @@ -19,7 +19,7 @@ pub struct Message { } #[derive(Serialize, Deserialize)] -pub struct GetResponse { +pub struct Response { pub data: T, #[serde(skip_serializing_if = "Option::is_none")] pub metadata: Option diff --git a/service/src/storage/messages/routes.rs b/service/src/storage/messages/routes.rs index 82f284c..da2f560 100644 --- a/service/src/storage/messages/routes.rs +++ b/service/src/storage/messages/routes.rs @@ -1,7 +1,7 @@ use actix_web::{get, post, web, HttpResponse, HttpRequest, ResponseError}; use log::error; use serde::{Serialize, Deserialize}; -use siren::{GetResponse, Metadata, ServiceError}; +use siren::{Response, Metadata, ServiceError}; use crate::{storage::messages::{QueryMessage, QueryFilters, InsertMessage}, auth::{JwtAuth, verify_role}}; @@ -50,7 +50,7 @@ async fn get_all(req: HttpRequest, auth: JwtAuth) -> HttpResponse { match QueryMessage::get_all(&filters, limit, page) { Ok(messages) => { - HttpResponse::Ok().json(GetResponse { + HttpResponse::Ok().json(Response { data: messages, metadata: Some(Metadata { total: total_count as i32, diff --git a/ui/src/api/guilds.ts b/ui/src/api/guilds.ts index 0a3fd1d..900a247 100644 --- a/ui/src/api/guilds.ts +++ b/ui/src/api/guilds.ts @@ -1,14 +1,16 @@ -import { get, post } from '.'; +import { APIResponse, get, post } from '.'; import { GuildChannel, GuildInfo } from './guilds.types'; export async function getGuilds(): Promise { const response = await get('guilds'); - return response?.json() || { data: [] }; + const guilds: APIResponse = await response?.json(); + return guilds.data || []; } export async function getTextChannels(guildId: number): Promise { const response = await get(`guilds/${guildId}/text`); - return response?.json() || { data: [] }; + const channels: APIResponse = await response?.json(); + return channels.data || []; } export async function sendMessage(guildId: number, channelId: number, message: string): Promise { @@ -17,7 +19,8 @@ export async function sendMessage(guildId: number, channelId: number, message: s export async function getVoiceChannels(guildId: number): Promise { const response = await get(`guilds/${guildId}/voice`); - return response?.json() || { data: [] }; + const channels: APIResponse = await response?.json(); + return channels.data || []; } export async function playTrack(guildId: number, channelId: number, track: string): Promise { diff --git a/ui/src/api/index.ts b/ui/src/api/index.ts index 16f2132..572ad22 100644 --- a/ui/src/api/index.ts +++ b/ui/src/api/index.ts @@ -41,6 +41,11 @@ export async function post(endpoint: string, body: any, options?: PostOptions): return response; } +export interface APIResponse { + data: T; + metadata: Metadata; +} + export interface Metadata { limit: number; page: number; diff --git a/ui/src/app/admin/page.tsx b/ui/src/app/admin/page.tsx new file mode 100644 index 0000000..ea66e85 --- /dev/null +++ b/ui/src/app/admin/page.tsx @@ -0,0 +1,201 @@ +'use client'; + +import { + getGuilds, + getTextChannels, + getVoiceChannels, + getVolume, + pauseTrack, + playTrack, + resumeTrack, + sendMessage, + setVolume, + skipTrack, + stopTrack +} from '@/api/guilds'; +import { GuildChannel, GuildInfo } from '@/api/guilds.types'; +import { Button, Card, Grid, Select, Slider, Tabs, TextInput, Textarea } from '@mantine/core'; +import { useForm } from '@mantine/form'; +import React, { useEffect, useState } from 'react'; + +export default function Page() { + const [guilds, setGuilds] = useState([]); + const [activeGuild, setActiveGuild] = useState(null); + const [voiceChannels, setVoiceChannels] = useState([]); + const [guildVolume, setGuildVolume] = useState(50.0); + + useEffect(() => { + getGuilds().then((g) => { + setGuilds(g); + if (g.length > 0) { + setActiveGuild(g[0]); + } + }); + }, []); + + useEffect(() => { + if (activeGuild) { + getVoiceChannels(activeGuild.id).then((c) => setVoiceChannels(c)); + getVolume(activeGuild.id).then((v) => setGuildVolume(v)); + } + }, [activeGuild]); + + return ( + + + {guilds && guilds.map((guild) => ( + setActiveGuild(guild)}> + {guild.name} + + ))} + + {guilds && guilds.map((guild) => ( + +

{guild.name}

+ + + + + + + + +
+ ))} +
+ ); +} + +function TextChannelCard({ guild }: { guild: GuildInfo | null }) { + const [textChannels, setTextChannels] = useState([]); + const [activeChannel, setActiveChannel] = useState(null); + + const form = useForm({ + initialValues: { + message: '' + } + }); + + useEffect(() => { + if (guild) { + getTextChannels(guild.id).then((c) => setTextChannels(c)); + } + }, [guild]); + + return ( + + +

Text Channels

+