Skip to content

Commit

Permalink
Fix Search Pages
Browse files Browse the repository at this point in the history
  • Loading branch information
Kathund committed Sep 11, 2024
1 parent dfaa2a2 commit 2dc2f4c
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 13 deletions.
7 changes: 6 additions & 1 deletion src/Discord/Private/Embed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ class Embed {
this.author = data.author || null;
}
build(): EmbedBuilder {
return new EmbedBuilder().setColor(this.color).setTimestamp().setTitle(this.title).setDescription(this.description);
return new EmbedBuilder()
.setColor(this.color)
.setTimestamp()
.setTitle(this.title)
.setDescription(this.description)
.setAuthor(this.author ? { name: this.author } : null);
}
}

Expand Down
40 changes: 40 additions & 0 deletions src/Discord/handlers/InteractionHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,46 @@ class InteractionHandler {
const trackId = interaction.customId.split('.')[1];
await this.discord.Application.spotify.requestHandler.queueTrack(`spotify:track:${trackId}`);
await interaction.followUp({ content: 'Song added to queue.', ephemeral: true });
} else if (interaction.customId.startsWith('search.')) {
const action = interaction.customId.split('.')[1];
if (
!interaction.message.embeds[0] ||
!interaction.message.embeds[0].description ||
!interaction.message.embeds[0].title
) {
return;
}
const [search, pageIndex, maxPage] = [
interaction.message.embeds[0].title.split(': ')[1].trim(),
Number(interaction.message.embeds[0].description.split('Page ')[1].split('/')[0]) - 1,
Number(interaction.message.embeds[0].description.split('Page ')[1].split('/')[1]) - 1
];
switch (action) {
case 'Start': {
const res = await this.discord.Application.spotify.requestHandler.searchTracks(search);
await interaction.update({ embeds: [res.toEmbed()], components: [res.toButtons(), res.toSelectMenu()] });
break;
}
case 'Back': {
const res = await this.discord.Application.spotify.requestHandler.searchTracks(search, pageIndex - 1);
await interaction.update({ embeds: [res.toEmbed()], components: [res.toButtons(), res.toSelectMenu()] });
break;
}
case 'Forward': {
const res = await this.discord.Application.spotify.requestHandler.searchTracks(search, pageIndex + 1);
await interaction.update({ embeds: [res.toEmbed()], components: [res.toButtons(), res.toSelectMenu()] });
break;
}
case 'End': {
const res = await this.discord.Application.spotify.requestHandler.searchTracks(search, maxPage);
await interaction.update({ embeds: [res.toEmbed()], components: [res.toButtons(), res.toSelectMenu()] });
break;
}
default: {
await interaction.reply({ content: 'Can i click ur buttons?', ephemeral: true });
break;
}
}
} else {
const ids: string[] = ['previous', 'pause', 'play', 'skip', 'queue', 'shuffle'];
if (!ids.includes(interaction.customId)) {
Expand Down
7 changes: 5 additions & 2 deletions src/Private/RequestHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class RequestHandler {

async request(endpoint: string, options?: RequestOptions): Promise<RequestData> {
if (!this.Application.spotify.token) throw new Error(this.Application.errors.NOT_LOGGED_IN);
options = { raw: options?.raw ?? false, noCache: options?.noCache ?? false };
options = { raw: options?.raw ?? false, noCache: options?.noCache ?? false, method: options?.method ?? 'GET' };
if (this.Application.cacheHandler.has(endpoint)) {
const data = this.Application.cacheHandler.get(endpoint);
return new RequestData(data.data, data.headers, {
Expand All @@ -55,9 +55,12 @@ class RequestHandler {
});
}
const res = await fetch(BASE_URL + endpoint, {
method: options.method || 'GET',
method: options.method,
headers: { Authorization: `Bearer ${this.Application.spotify.token.key}` }
});
if ('GET' !== options.method) {
return new RequestData({}, res.headers, { status: res.status, options, url: endpoint, cached: false });
}
const parsedRes = (await res.json()) as Record<string, any>;
if (401 === res.status || 403 === res.status) throw new Error(this.Application.errors.NOT_LOGGED_IN);
const requestData = new RequestData(parsedRes, res.headers, {
Expand Down
4 changes: 2 additions & 2 deletions src/Spotify/Private/API/Playback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class Playback {
this.smartShuffle = data.smart_shuffle || false;
this.repeatState = data.repeat_state || 'off';
this.timestamp = data.timestamp || Date.now();
this.item = data.track ? new Track(data.item) : null;
this.item = data.item ? new Track(data.item) : null;
this.progressMS = data.progress_ms ? data.progress_ms : 0;
this.progress = this.item ? this.progressMS / this.item.duration : 0;
this.playing = data.is_playing || false;
Expand Down Expand Up @@ -82,7 +82,7 @@ class Playback {
.setEmoji(this.playing ? emojis.pause : emojis.play)
.setStyle(this.playing ? ButtonStyle.Success : ButtonStyle.Danger)
.setCustomId(this.playing ? 'pause' : 'play'),
new ButtonBuilder().setEmoji(emojis.skip).setStyle(ButtonStyle.Secondary).setCustomId('skip'),
new ButtonBuilder().setEmoji(emojis.forward).setStyle(ButtonStyle.Secondary).setCustomId('skip'),

Check failure on line 85 in src/Spotify/Private/API/Playback.ts

View workflow job for this annotation

GitHub Actions / build

Property 'forward' does not exist on type '{ back: string; pause: string; play: string; skip: string; queue: string; spotify: string; refresh: string; shuffle: string; repeat: string; repeatOne: string; explicit: string; }'.
new ButtonBuilder()
.setEmoji('track' === this.repeatState ? emojis.repeatOne : emojis.repeat)
.setStyle('off' === this.repeatState ? ButtonStyle.Danger : ButtonStyle.Success)
Expand Down
9 changes: 5 additions & 4 deletions src/Spotify/Private/API/Search/Search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,15 @@ class Search {

toButtons(): ActionRowBuilder<ButtonBuilder> {
const buttons: ButtonBuilder[] = [
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId('searchStart').setEmoji(emojis.back),
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId('searchBack').setEmoji(emojis.back),
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId('search.Start').setEmoji(emojis.back),
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId('search.Back').setEmoji(emojis.backOne),

Check failure on line 36 in src/Spotify/Private/API/Search/Search.ts

View workflow job for this annotation

GitHub Actions / build

Property 'backOne' does not exist on type '{ back: string; pause: string; play: string; skip: string; queue: string; spotify: string; refresh: string; shuffle: string; repeat: string; repeatOne: string; explicit: string; }'.
new ButtonBuilder()
.setCustomId('MEOW')
.setStyle(ButtonStyle.Secondary)
.setLabel(`Page ${this.getPage()} / ${this.getPages()}`)
.setDisabled(true),
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId('searchForward').setEmoji(emojis.skip),
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId('searchEnd').setEmoji(emojis.skip)
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId('search.Forward').setEmoji(emojis.forwardOne),

Check failure on line 42 in src/Spotify/Private/API/Search/Search.ts

View workflow job for this annotation

GitHub Actions / build

Property 'forwardOne' does not exist on type '{ back: string; pause: string; play: string; skip: string; queue: string; spotify: string; refresh: string; shuffle: string; repeat: string; repeatOne: string; explicit: string; }'.
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId('search.End').setEmoji(emojis.forward)

Check failure on line 43 in src/Spotify/Private/API/Search/Search.ts

View workflow job for this annotation

GitHub Actions / build

Property 'forward' does not exist on type '{ back: string; pause: string; play: string; skip: string; queue: string; spotify: string; refresh: string; shuffle: string; repeat: string; repeatOne: string; explicit: string; }'.
];
if (1 === this.getPages() || 0 === this.getPages()) {
buttons[0].setDisabled(true);
Expand Down
6 changes: 3 additions & 3 deletions src/Spotify/Private/API/Search/Track.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ class TrackSearch {

toEmbed(): EmbedBuilder {
const embed = new Embed({
title: `Search Results for ${this.query}`,
description: `Found ${this.total} results`,
author: `Found ${this.total} results`
title: `Search: ${this.query}`,
description: `Page ${Math.floor(this.offset / this.limit) + 1}/${Math.ceil(this.total / this.limit)}`,
author: `Found ${this.total} Results`
}).build();
this.items.map((track) => {
embed.addFields({
Expand Down
2 changes: 1 addition & 1 deletion src/Spotify/Private/RequestHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class RequestHandler {
});
}

async searchTracks(query: string, page: number): Promise<Search> {
async searchTracks(query: string, page: number = 0): Promise<Search> {
const offset = page * 10;
const res = await this.spotify.Application.requestHandler.request(
`/search?type=track&limit=10&market=AU&q=${query.replaceAll('%20', '+')}&offset=${offset}`
Expand Down

0 comments on commit 2dc2f4c

Please sign in to comment.