Moved bot api files
This commit is contained in:
@@ -9,8 +9,7 @@ use serenity::model::application::interaction::application_command::ApplicationC
|
|||||||
use siren::ServiceError;
|
use siren::ServiceError;
|
||||||
use songbird::{EventHandler, Songbird};
|
use songbird::{EventHandler, Songbird};
|
||||||
|
|
||||||
use crate::bot::commands::audio::{leave, add_song, get_songbird};
|
use crate::bot::{guilds::QueryGuild, commands::audio::{leave, add_song, get_songbird}};
|
||||||
use crate::storage::guilds::QueryGuild;
|
|
||||||
|
|
||||||
use super::{create_response, edit_response, join_by_user};
|
use super::{create_response, edit_response, join_by_user};
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use serenity::builder::CreateApplicationCommand;
|
|||||||
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
|
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
|
||||||
use songbird::Songbird;
|
use songbird::Songbird;
|
||||||
|
|
||||||
use crate::storage::guilds::InsertGuild;
|
use crate::bot::guilds::InsertGuild;
|
||||||
|
|
||||||
use super::{get_songbird, create_response, edit_response};
|
use super::{get_songbird, create_response, edit_response};
|
||||||
|
|
||||||
|
|||||||
@@ -1,18 +1,16 @@
|
|||||||
use std::{sync::Arc, pin::Pin};
|
use std::{sync::Arc, pin::Pin};
|
||||||
|
|
||||||
use actix_web::{get, post, web, HttpResponse, ResponseError};
|
use actix_web::{get, post, web, HttpResponse, ResponseError};
|
||||||
use log::warn;
|
|
||||||
use serde::{Serialize, Deserialize};
|
use serde::{Serialize, Deserialize};
|
||||||
use serenity::model::prelude::{GuildChannel, ChannelType};
|
use serenity::model::prelude::{GuildChannel, ChannelType};
|
||||||
use siren::{ServiceError, Response};
|
use siren::{ServiceError, Response};
|
||||||
|
|
||||||
use crate::{AppState, bot::commands::audio::{play::play_track, join}, storage::guilds::QueryGuild, auth::{JwtAuth, verify_role}};
|
use crate::{AppState, bot::commands::audio::{play::play_track, join}, bot::guilds::QueryGuild, auth::{JwtAuth, verify_role}};
|
||||||
|
|
||||||
#[get("/guilds")]
|
#[get("/guilds")]
|
||||||
async fn get_guilds(data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
async fn get_guilds(data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let guild_results = &data.http.get_guilds(None, None).await;
|
let guild_results = &data.http.get_guilds(None, None).await;
|
||||||
let guilds = match guild_results {
|
let guilds = match guild_results {
|
||||||
@@ -30,9 +28,8 @@ async fn get_guilds(data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpRespon
|
|||||||
|
|
||||||
#[get("/{id}/text")]
|
#[get("/{id}/text")]
|
||||||
async fn get_text_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
async fn get_text_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await;
|
let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await;
|
||||||
let channels = match channel_results {
|
let channels = match channel_results {
|
||||||
@@ -50,9 +47,8 @@ async fn get_text_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>
|
|||||||
|
|
||||||
#[get("/{id}/voice")]
|
#[get("/{id}/voice")]
|
||||||
async fn get_voice_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
async fn get_voice_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await;
|
let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await;
|
||||||
let channels = match channel_results {
|
let channels = match channel_results {
|
||||||
@@ -75,9 +71,8 @@ struct ChannelMessage {
|
|||||||
|
|
||||||
#[post("/{guild_id}/text/{channel_id}/message")]
|
#[post("/{guild_id}/text/{channel_id}/message")]
|
||||||
async fn send_message(path: web::Path<(String, String)>, text: web::Json<ChannelMessage>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
async fn send_message(path: web::Path<(String, String)>, text: web::Json<ChannelMessage>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let (guild_id, channel_id) = path.into_inner();
|
let (guild_id, channel_id) = path.into_inner();
|
||||||
let guild_id = match guild_id.parse::<u64>() {
|
let guild_id = match guild_id.parse::<u64>() {
|
||||||
@@ -136,9 +131,8 @@ struct PlayRequest {
|
|||||||
|
|
||||||
#[post("/{guild_id}/voice/{channel_id}/play")]
|
#[post("/{guild_id}/voice/{channel_id}/play")]
|
||||||
async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayRequest>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayRequest>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let (guild_id, channel_id) = path.into_inner();
|
let (guild_id, channel_id) = path.into_inner();
|
||||||
let guild_id = match guild_id.parse::<u64>() {
|
let guild_id = match guild_id.parse::<u64>() {
|
||||||
@@ -186,9 +180,8 @@ async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayReq
|
|||||||
|
|
||||||
#[post("/{guild_id}/voice/stop")]
|
#[post("/{guild_id}/voice/stop")]
|
||||||
async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let guild_id = path.into_inner();
|
let guild_id = path.into_inner();
|
||||||
let guild_id = match guild_id.parse::<u64>() {
|
let guild_id = match guild_id.parse::<u64>() {
|
||||||
@@ -211,9 +204,8 @@ async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: Jwt
|
|||||||
|
|
||||||
#[post("/{guild_id}/voice/resume")]
|
#[post("/{guild_id}/voice/resume")]
|
||||||
async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let guild_id = path.into_inner();
|
let guild_id = path.into_inner();
|
||||||
let guild_id = match guild_id.parse::<u64>() {
|
let guild_id = match guild_id.parse::<u64>() {
|
||||||
@@ -241,9 +233,8 @@ async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: J
|
|||||||
|
|
||||||
#[post("/{guild_id}/voice/pause")]
|
#[post("/{guild_id}/voice/pause")]
|
||||||
async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let guild_id = path.into_inner();
|
let guild_id = path.into_inner();
|
||||||
let guild_id = match guild_id.parse::<u64>() {
|
let guild_id = match guild_id.parse::<u64>() {
|
||||||
@@ -276,9 +267,8 @@ struct SetVolume {
|
|||||||
|
|
||||||
#[get("/{guild_id}/voice/volume")]
|
#[get("/{guild_id}/voice/volume")]
|
||||||
async fn get_volume(path: web::Path<String>, auth: JwtAuth) -> HttpResponse {
|
async fn get_volume(path: web::Path<String>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let guild_id = path.into_inner();
|
let guild_id = path.into_inner();
|
||||||
let guild_id = match guild_id.parse::<u64>() {
|
let guild_id = match guild_id.parse::<u64>() {
|
||||||
@@ -306,9 +296,8 @@ async fn get_volume(path: web::Path<String>, auth: JwtAuth) -> HttpResponse {
|
|||||||
|
|
||||||
#[post("/{guild_id}/voice/volume")]
|
#[post("/{guild_id}/voice/volume")]
|
||||||
async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let guild_id = path.into_inner();
|
let guild_id = path.into_inner();
|
||||||
let guild_id = match guild_id.parse::<u64>() {
|
let guild_id = match guild_id.parse::<u64>() {
|
||||||
@@ -337,9 +326,8 @@ async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, dat
|
|||||||
|
|
||||||
#[post("/{guild_id}/voice/skip")]
|
#[post("/{guild_id}/voice/skip")]
|
||||||
async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
|
||||||
let _ = match verify_role(&auth, "admin") {
|
if let Err(err) = verify_role(&auth, "admin") {
|
||||||
Ok(_) => {},
|
return ResponseError::error_response(&err)
|
||||||
Err(err) => return ResponseError::error_response(&err)
|
|
||||||
};
|
};
|
||||||
let guild_id = path.into_inner();
|
let guild_id = path.into_inner();
|
||||||
let guild_id = match guild_id.parse::<u64>() {
|
let guild_id = match guild_id.parse::<u64>() {
|
||||||
@@ -5,7 +5,7 @@ use serenity::model::gateway::Ready;
|
|||||||
use serenity::model::channel::Message;
|
use serenity::model::channel::Message;
|
||||||
use serenity::prelude::*;
|
use serenity::prelude::*;
|
||||||
|
|
||||||
use crate::storage::guilds::InsertGuild;
|
use crate::bot::guilds::InsertGuild;
|
||||||
|
|
||||||
use super::commands;
|
use super::commands;
|
||||||
use super::commands::audio::create_response;
|
use super::commands::audio::create_response;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use log::error;
|
|||||||
use serde::{Serialize, Deserialize};
|
use serde::{Serialize, Deserialize};
|
||||||
use siren::{Response, Metadata, ServiceError};
|
use siren::{Response, Metadata, ServiceError};
|
||||||
|
|
||||||
use crate::{storage::messages::{QueryMessage, QueryFilters, InsertMessage}, auth::{JwtAuth, verify_role}};
|
use crate::{bot::messages::{QueryMessage, QueryFilters, InsertMessage}, auth::{JwtAuth, verify_role}};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
struct GetAllParams {
|
struct GetAllParams {
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
pub mod api;
|
|
||||||
pub mod commands;
|
pub mod commands;
|
||||||
|
pub mod guilds;
|
||||||
pub mod handler;
|
pub mod handler;
|
||||||
|
pub mod messages;
|
||||||
|
|||||||
@@ -122,11 +122,11 @@ async fn main() -> std::io::Result<()> {
|
|||||||
App::new()
|
App::new()
|
||||||
.wrap(cors)
|
.wrap(cors)
|
||||||
.app_data(web::Data::new(Arc::clone(&app_data)))
|
.app_data(web::Data::new(Arc::clone(&app_data)))
|
||||||
.configure(crate::storage::messages::init_routes)
|
|
||||||
.configure(crate::auth::init_routes)
|
.configure(crate::auth::init_routes)
|
||||||
.configure(crate::users::init_routes)
|
.configure(crate::users::init_routes)
|
||||||
.configure(crate::dnd::spells::init_routes)
|
.configure(crate::dnd::spells::init_routes)
|
||||||
.configure(crate::bot::api::init_routes)
|
.configure(crate::bot::guilds::init_routes)
|
||||||
|
.configure(crate::bot::messages::init_routes)
|
||||||
})
|
})
|
||||||
.bind(format!("{}:{}", host, port)) {
|
.bind(format!("{}:{}", host, port)) {
|
||||||
Ok(b) => {
|
Ok(b) => {
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
mod model;
|
|
||||||
|
|
||||||
pub use model::*;
|
|
||||||
@@ -8,8 +8,6 @@ use log::{error, info};
|
|||||||
use r2d2;
|
use r2d2;
|
||||||
use std::env;
|
use std::env;
|
||||||
|
|
||||||
pub mod guilds;
|
|
||||||
pub mod messages;
|
|
||||||
pub mod schema;
|
pub mod schema;
|
||||||
|
|
||||||
type DbPool = r2d2::Pool<DieselConnectionManager<PgConnection>>;
|
type DbPool = r2d2::Pool<DieselConnectionManager<PgConnection>>;
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import Cookies from 'js-cookie';
|
import Cookies from 'js-cookie';
|
||||||
import { get, post } from '.';
|
import { getRequest, postRequest } from '.';
|
||||||
import { RegisterUser, ResponseAuth } from './auth.types';
|
import { RegisterUser, ResponseAuth } from './auth.types';
|
||||||
|
|
||||||
export async function login(email: string, password: string): Promise<ResponseAuth | undefined> {
|
export async function login(email: string, password: string): Promise<ResponseAuth | undefined> {
|
||||||
const response = await post('auth/login', { email, password });
|
const response = await postRequest('auth/login', { email, password });
|
||||||
if (response?.status === 200) {
|
if (response?.status === 200) {
|
||||||
return response.json();
|
return response.json();
|
||||||
} else {
|
} else {
|
||||||
@@ -12,7 +12,7 @@ export async function login(email: string, password: string): Promise<ResponseAu
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function register(user: RegisterUser): Promise<boolean> {
|
export async function register(user: RegisterUser): Promise<boolean> {
|
||||||
const response = await post('auth/register', user);
|
const response = await postRequest('auth/register', user);
|
||||||
if (response?.status === 201) {
|
if (response?.status === 201) {
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
@@ -21,11 +21,11 @@ export async function register(user: RegisterUser): Promise<boolean> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function logout() {
|
export async function logout() {
|
||||||
return await post('auth/logout', {});
|
return await postRequest('auth/logout', {});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function refresh(refresh_token_rotation?: boolean): Promise<ResponseAuth | undefined> {
|
export async function refresh(refresh_token_rotation?: boolean): Promise<ResponseAuth | undefined> {
|
||||||
const response = await get('auth/refresh', { refresh_token_rotation });
|
const response = await getRequest('auth/refresh', { refresh_token_rotation });
|
||||||
if (response?.status === 200) {
|
if (response?.status === 200) {
|
||||||
return response.json();
|
return response.json();
|
||||||
} else {
|
} else {
|
||||||
@@ -34,7 +34,7 @@ export async function refresh(refresh_token_rotation?: boolean): Promise<Respons
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function me(): Promise<ResponseAuth | undefined> {
|
export async function me(): Promise<ResponseAuth | undefined> {
|
||||||
const response = await get('auth/me');
|
const response = await getRequest('auth/me');
|
||||||
if (response?.status === 200) {
|
if (response?.status === 200) {
|
||||||
return response.json();
|
return response.json();
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,54 +1,54 @@
|
|||||||
import { APIResponse, get, post } from '.';
|
import { APIResponse, getRequest, postRequest } from '.';
|
||||||
import { GuildChannel, GuildInfo } from './guilds.types';
|
import { GuildChannel, GuildInfo } from './guilds.types';
|
||||||
|
|
||||||
export async function getGuilds(): Promise<GuildInfo[]> {
|
export async function getGuilds(): Promise<GuildInfo[]> {
|
||||||
const response = await get('guilds');
|
const response = await getRequest('guilds');
|
||||||
const guilds: APIResponse<GuildInfo[]> = await response?.json();
|
const guilds: APIResponse<GuildInfo[]> = await response?.json();
|
||||||
return guilds.data || [];
|
return guilds?.data || [];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getTextChannels(guildId: number): Promise<GuildChannel[]> {
|
export async function getTextChannels(guildId: number): Promise<GuildChannel[]> {
|
||||||
const response = await get(`guilds/${guildId}/text`);
|
const response = await getRequest(`guilds/${guildId}/text`);
|
||||||
const channels: APIResponse<GuildChannel[]> = await response?.json();
|
const channels: APIResponse<GuildChannel[]> = await response?.json();
|
||||||
return channels.data || [];
|
return channels.data || [];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function sendMessage(guildId: number, channelId: number, message: string): Promise<void> {
|
export async function sendMessage(guildId: number, channelId: number, message: string): Promise<void> {
|
||||||
await post(`guilds/${guildId}/text/${channelId}/message`, { message });
|
await postRequest(`guilds/${guildId}/text/${channelId}/message`, { message });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getVoiceChannels(guildId: number): Promise<GuildChannel[]> {
|
export async function getVoiceChannels(guildId: number): Promise<GuildChannel[]> {
|
||||||
const response = await get(`guilds/${guildId}/voice`);
|
const response = await getRequest(`guilds/${guildId}/voice`);
|
||||||
const channels: APIResponse<GuildChannel[]> = await response?.json();
|
const channels: APIResponse<GuildChannel[]> = await response?.json();
|
||||||
return channels.data || [];
|
return channels.data || [];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function playTrack(guildId: number, channelId: number, track: string): Promise<void> {
|
export async function playTrack(guildId: number, channelId: number, track: string): Promise<void> {
|
||||||
await post(`guilds/${guildId}/voice/${channelId}/play`, { track_url: track });
|
await postRequest(`guilds/${guildId}/voice/${channelId}/play`, { track_url: track });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function stopTrack(guildId: number): Promise<void> {
|
export async function stopTrack(guildId: number): Promise<void> {
|
||||||
await post(`guilds/${guildId}/voice/stop`, {});
|
await postRequest(`guilds/${guildId}/voice/stop`, {});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function pauseTrack(guildId: number): Promise<void> {
|
export async function pauseTrack(guildId: number): Promise<void> {
|
||||||
await post(`guilds/${guildId}/voice/pause`, {});
|
await postRequest(`guilds/${guildId}/voice/pause`, {});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function resumeTrack(guildId: number): Promise<void> {
|
export async function resumeTrack(guildId: number): Promise<void> {
|
||||||
await post(`guilds/${guildId}/voice/resume`, {});
|
await postRequest(`guilds/${guildId}/voice/resume`, {});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setVolume(guildId: number, volume: number): Promise<void> {
|
export async function setVolume(guildId: number, volume: number): Promise<void> {
|
||||||
await post(`guilds/${guildId}/voice/volume`, { volume: `${volume}` });
|
await postRequest(`guilds/${guildId}/voice/volume`, { volume: `${volume}` });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function skipTrack(guildId: number): Promise<void> {
|
export async function skipTrack(guildId: number): Promise<void> {
|
||||||
await post(`guilds/${guildId}/voice/skip`, {});
|
await postRequest(`guilds/${guildId}/voice/skip`, {});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getVolume(guildId: number): Promise<number> {
|
export async function getVolume(guildId: number): Promise<number> {
|
||||||
const response = await get(`guilds/${guildId}/voice/volume`);
|
const response = await getRequest(`guilds/${guildId}/voice/volume`);
|
||||||
const volume: number = await response?.json();
|
const volume: number = await response?.json();
|
||||||
return volume || 0;
|
return volume || 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ const serviceHost = process.env.SERVICE_HOST || 'http://localhost';
|
|||||||
const servicePort = process.env.SERVICE_PORT || 5000;
|
const servicePort = process.env.SERVICE_PORT || 5000;
|
||||||
const baseURL = `${serviceHost}:${servicePort}`;
|
const baseURL = `${serviceHost}:${servicePort}`;
|
||||||
|
|
||||||
export async function get(endpoint: string, params: Record<string, any> = {}): Promise<Response> {
|
export async function getRequest(endpoint: string, params: Record<string, any> = {}): Promise<Response> {
|
||||||
// Remove undefined params
|
// Remove undefined params
|
||||||
Object.keys(params).forEach((key) => params[key] === undefined && delete params[key]);
|
Object.keys(params).forEach((key) => params[key] === undefined && delete params[key]);
|
||||||
const urlParams = new URLSearchParams(params);
|
const urlParams = new URLSearchParams(params);
|
||||||
@@ -19,10 +19,10 @@ interface PostOptions {
|
|||||||
type?: 'json' | 'form';
|
type?: 'json' | 'form';
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function post(endpoint: string, body: any, options?: PostOptions): Promise<Response> {
|
export async function postRequest(endpoint: string, body?: any, options?: PostOptions): Promise<Response> {
|
||||||
const url = `${baseURL}/${endpoint}`;
|
const url = `${baseURL}/${endpoint}`;
|
||||||
let response;
|
let response;
|
||||||
if (!options?.type || options.type === 'json') {
|
if (body && (!options?.type || options.type === 'json')) {
|
||||||
response = await fetch(url, {
|
response = await fetch(url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { get } from '.';
|
import { getRequest } from '.';
|
||||||
import { GetSpellsResponse } from './spells.types';
|
import { GetSpellsResponse } from './spells.types';
|
||||||
|
|
||||||
interface GetSpellsParams {
|
interface GetSpellsParams {
|
||||||
@@ -19,7 +19,7 @@ interface GetSpellsParams {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getSpells(params?: GetSpellsParams): Promise<GetSpellsResponse> {
|
export async function getSpells(params?: GetSpellsParams): Promise<GetSpellsResponse> {
|
||||||
const response = await get('dnd/spells', {
|
const response = await getRequest('dnd/spells', {
|
||||||
name: params?.name,
|
name: params?.name,
|
||||||
like_name: params?.like_name,
|
like_name: params?.like_name,
|
||||||
schools: params?.schools?.join(','),
|
schools: params?.schools?.join(','),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { get, post } from '.';
|
import { getRequest, postRequest } from '.';
|
||||||
|
|
||||||
export async function getPicture(): Promise<Blob | undefined> {
|
export async function getPicture(): Promise<Blob | undefined> {
|
||||||
const response = await get('users/picture');
|
const response = await getRequest('users/picture');
|
||||||
if (response?.status === 200) {
|
if (response?.status === 200) {
|
||||||
return response.blob();
|
return response.blob();
|
||||||
} else {
|
} else {
|
||||||
@@ -13,7 +13,7 @@ export async function setPicture(payload: File): Promise<boolean> {
|
|||||||
const data = new FormData();
|
const data = new FormData();
|
||||||
data.append('data', payload);
|
data.append('data', payload);
|
||||||
// TODO: Figure out why the form data object is empty
|
// TODO: Figure out why the form data object is empty
|
||||||
const response = await post('users/picture', data, {
|
const response = await postRequest('users/picture', data, {
|
||||||
type: 'form'
|
type: 'form'
|
||||||
});
|
});
|
||||||
if (response?.status === 200) {
|
if (response?.status === 200) {
|
||||||
|
|||||||
@@ -14,31 +14,33 @@ import {
|
|||||||
stopTrack
|
stopTrack
|
||||||
} from '@/api/guilds';
|
} from '@/api/guilds';
|
||||||
import { GuildChannel, GuildInfo } from '@/api/guilds.types';
|
import { GuildChannel, GuildInfo } from '@/api/guilds.types';
|
||||||
|
import { userState } from '@/state/auth';
|
||||||
import { Button, Card, Grid, Select, Slider, Tabs, TextInput, Textarea } from '@mantine/core';
|
import { Button, Card, Grid, Select, Slider, Tabs, TextInput, Textarea } from '@mantine/core';
|
||||||
import { useForm } from '@mantine/form';
|
import { useForm } from '@mantine/form';
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { useRecoilValue } from 'recoil';
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
|
const user = useRecoilValue(userState);
|
||||||
const [guilds, setGuilds] = useState<GuildInfo[]>([]);
|
const [guilds, setGuilds] = useState<GuildInfo[]>([]);
|
||||||
const [activeGuild, setActiveGuild] = useState<GuildInfo | null>(null);
|
const [activeGuild, setActiveGuild] = useState<GuildInfo | null>(null);
|
||||||
const [voiceChannels, setVoiceChannels] = useState<GuildChannel[]>([]);
|
const router = useRouter();
|
||||||
const [guildVolume, setGuildVolume] = useState<number>(50.0);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
getGuilds().then((g) => {
|
// Check if the user is logged in and an admin, otherwise redirect to the home page
|
||||||
setGuilds(g);
|
// if (!user || !user.roles.includes('admin')) {
|
||||||
if (g.length > 0) {
|
if (!user || user.role !== 'admin') {
|
||||||
setActiveGuild(g[0]);
|
router.push('/');
|
||||||
}
|
} else {
|
||||||
});
|
getGuilds().then((g) => {
|
||||||
}, []);
|
setGuilds(g);
|
||||||
|
if (g.length > 0) {
|
||||||
useEffect(() => {
|
setActiveGuild(g[0]);
|
||||||
if (activeGuild) {
|
}
|
||||||
getVoiceChannels(activeGuild.id).then((c) => setVoiceChannels(c));
|
});
|
||||||
getVolume(activeGuild.id).then((v) => setGuildVolume(v));
|
|
||||||
}
|
}
|
||||||
}, [activeGuild]);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Tabs orientation='vertical' defaultValue={activeGuild?.name}>
|
<Tabs orientation='vertical' defaultValue={activeGuild?.name}>
|
||||||
@@ -171,11 +173,9 @@ function VoiceChannelsCard({ guild }: { guild: GuildInfo | null }) {
|
|||||||
<Button type='submit'>Set Volume</Button>
|
<Button type='submit'>Set Volume</Button>
|
||||||
</form>
|
</form>
|
||||||
<form
|
<form
|
||||||
style={{ margin: '1em' }}
|
style={{ margin: '1em' }}
|
||||||
onSubmit={(e) => {
|
onSubmit={form.onSubmit((values) => playTrack(guild!.id, activeChannel.id, values.trackUrl))}
|
||||||
e.preventDefault();
|
>
|
||||||
}}
|
|
||||||
>
|
|
||||||
<TextInput placeholder='Youtube URL...' />
|
<TextInput placeholder='Youtube URL...' />
|
||||||
<Button type='submit'>Play Track</Button>
|
<Button type='submit'>Play Track</Button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
Reference in New Issue
Block a user