diff --git a/src/commands/search.ts b/src/commands/search.ts index d52d402..4f52756 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -5,31 +5,100 @@ import { SlashCommandBuilder, } from "discord.js" import client from "lib/prisma.ts" +import { type Destination } from "prisma-client/client.ts" import { type CommandV2 } from "interfaces/command.ts" -import { getSeriesByImdbId, getSeriesByName } from "lib/tvdb.ts" +import { + getSeriesByImdbId, + getSeriesByTvdbId, + getSeriesCandidates, + type SeriesCandidate, +} from "lib/tvdb.ts" import { buildShowEmbed } from "lib/messages.ts" import { showSearchAutocomplete } from "lib/autocomplete.ts" +import { parseIMDBIds } from "lib/util.ts" +import { type CarouselPage, sendCarousel } from "lib/carousel.ts" +import { type SeriesExtendedRecord } from "interfaces/tvdb.generated.ts" + +/** Channels a show is linked to, or none if the show isn't tracked. */ +async function getDestinations(imdbId: string): Promise { + const show = await client.show.findUnique({ + where: { imdbId }, + select: { destinations: true }, + }) + return show?.destinations ?? [] +} + +/** + * Builds the page shown for a show, with the channels it is linked to + * @param fallbackYear year to use if the show record doesn't have one + */ +async function buildSeriesPage( + imdbId: string, + series: SeriesExtendedRecord, + fallbackYear?: string, +): Promise { + const year = [series.year, series.firstAired?.slice(0, 4), fallbackYear] + .find((y) => y != null && y !== "") + + // some TVDB names already end in a year, like "The Count of Monte Cristo (1965)" + const nameHasYear = /\(\d{4}\)\s*$/.test(series.name) + const title = year != null && !nameHasYear + ? `${series.name} (${year})` + : series.name + const embed = buildShowEmbed(imdbId, series, await getDestinations(imdbId)) + + return { + label: title, + // tells apart shows with the same name and year + description: series.latestNetwork?.name, + // the year is only added here so /link and /post embeds stay as they are + embed: { ...embed, title }, + } +} + +/** + * Builds the carousel page for one name search match + * @returns the page, or undefined if the show can't be loaded or has no IMDB id + */ +async function buildCandidatePage( + candidate: SeriesCandidate, +): Promise { + const series = await getSeriesByTvdbId(parseInt(candidate.tvdb_id)) + if (series == null) return undefined + + const imdbId = series.remoteIds?.find((r) => r.type === 2)?.id + if (imdbId == null) return undefined + + return await buildSeriesPage(imdbId, series, candidate.year) +} export const command: CommandV2 = { slashCommand: { main: new SlashCommandBuilder() .setName("search") - .setDescription("Link a show to a channel for notifications.") + .setDescription("Look up a show and see its details and linked channels.") .setContexts(InteractionContextType.Guild) .addStringOption((option) => option.setName("query") .setDescription( - "Query to search for. Can be an IMDB ID or a show name", + "Query to search for. Can be an IMDB ID, an IMDB link or a show name", ) .setMinLength(1) .setAutocomplete(true) .setRequired(true) + ) + .addIntegerOption((option) => + option.setName("year") + .setDescription("Only show matches first aired in this year") + .setMinValue(1900) + .setMaxValue(2100) ), }, async executeCommand(interaction: ChatInputCommandInteraction) { - const query = interaction.options.getString("query", true) + const query = interaction.options.getString("query", true).trim() - let imdbId = query.toLowerCase().startsWith("tt") ? query : undefined + // the query may be an IMDB ID or an IMDB link; anything else is a show name + const imdbId: string | undefined = parseIMDBIds(query.toLowerCase())[0] if (imdbId !== undefined) { const series = await getSeriesByImdbId(imdbId) @@ -40,31 +109,29 @@ export const command: CommandV2 = { ) } - const show = await client.show.findUnique({ - where: { - imdbId, - }, - select: { - destinations: true, - }, - }) - - return await interaction.editReply({ - embeds: [buildShowEmbed(imdbId, series, show?.destinations ?? [])], - }) + return await sendCarousel(interaction, [ + await buildSeriesPage(imdbId, series), + ]) } - const series = await getSeriesByName(query) + // an IMDB id or link already points at one show, so the year only narrows name searches + const year = interaction.options.getInteger("year") ?? undefined + const candidates = await getSeriesCandidates(query, year) - if (series == null) return await interaction.editReply("Show not found") + if (candidates.length === 0) { + return await interaction.editReply("Show not found") + } - imdbId = series.remoteIds.find((r) => r.type === 2)?.id + // the search results don't reliably say which shows have an IMDB id, so + // load every match now and drop the ones without, keeping the page count right + const pages = (await Promise.all(candidates.map(buildCandidatePage))) + .filter((page) => page != null) - if (imdbId == null) return await interaction.editReply("Show not found") + if (pages.length === 0) { + return await interaction.editReply("Show not found") + } - return await interaction.editReply({ - embeds: [buildShowEmbed(imdbId, series, [])], - }) + return await sendCarousel(interaction, pages) }, async executeAutoComplete(interaction: AutocompleteInteraction) { await showSearchAutocomplete(interaction) diff --git a/src/lib/autocomplete.ts b/src/lib/autocomplete.ts index b84b202..60bffa6 100644 --- a/src/lib/autocomplete.ts +++ b/src/lib/autocomplete.ts @@ -4,6 +4,7 @@ import { type AutocompleteInteraction, } from "discord.js" import client from "lib/prisma.ts" +import { parseIMDBIds } from "lib/util.ts" export async function showSearchAutocomplete( interaction: AutocompleteInteraction, @@ -12,20 +13,22 @@ export async function showSearchAutocomplete( if (focusedValue === undefined) return - const where: Prisma.ShowWhereInput = - focusedValue.toLocaleLowerCase().startsWith("tt") - ? { - imdbId: { - startsWith: focusedValue, - mode: "insensitive", - }, - } - : { - name: { - startsWith: focusedValue, - mode: "insensitive", - }, - } + // the input may be a (partial) IMDB ID or IMDB link; otherwise match by name + const [parsedId] = parseIMDBIds(focusedValue.trim().toLowerCase()) + + const where: Prisma.ShowWhereInput = parsedId != null && parsedId !== "" + ? { + imdbId: { + startsWith: parsedId, + mode: "insensitive", + }, + } + : { + name: { + startsWith: focusedValue, + mode: "insensitive", + }, + } const data = await client.show.findMany({ where, @@ -42,7 +45,11 @@ export async function showSearchAutocomplete( const choices = data.map( (item): ApplicationCommandOptionChoiceData => { const { name, imdbId } = item - return ({ name: `${name} - (${name})`, value: imdbId }) + return ({ + // Discord caps choice names at 100 characters + name: `${name} (${imdbId})`.slice(0, 100), + value: imdbId, + }) }, ) diff --git a/src/lib/carousel.ts b/src/lib/carousel.ts new file mode 100644 index 0000000..6be20cd --- /dev/null +++ b/src/lib/carousel.ts @@ -0,0 +1,281 @@ +import { + ActionRowBuilder, + type APIEmbed, + ButtonBuilder, + ButtonStyle, + type ChatInputCommandInteraction, + ContainerBuilder, + type Message, + MessageFlags, + SectionBuilder, + SeparatorBuilder, + SeparatorSpacingSize, + StringSelectMenuBuilder, + StringSelectMenuOptionBuilder, + TextDisplayBuilder, + ThumbnailBuilder, +} from "discord.js" + +const PREVIOUS_ID = "carousel_previous" +const NEXT_ID = "carousel_next" +const SELECT_ID = "carousel_select" +const SEND_ID = "carousel_send" + +/** why the collector stopped when a result was sent */ +const SENT_REASON = "sent" + +/** how long the controls keep working after the reply is sent */ +const TIMEOUT_MS = 10 * 60 * 1000 + +/** discord allows at most 25 options in a select menu */ +const MAX_PAGES = 25 + +/** discord allows 4000 characters of text per message, this leaves room for the rest */ +const MAX_DESCRIPTION_LENGTH = 2000 + +export interface CarouselPage { + /** shown in the dropdown, discord limits this to 100 characters */ + label: string + /** shown under the label in the dropdown, discord limits this to 100 characters */ + description?: string + embed: APIEmbed +} + +function buildSelect( + pages: CarouselPage[], + index: number, + disabled: boolean, +): ActionRowBuilder { + return new ActionRowBuilder().addComponents( + new StringSelectMenuBuilder() + .setCustomId(SELECT_ID) + .setPlaceholder("Choose a result") + .setDisabled(disabled) + .addOptions( + pages.map((page, i) => { + const option = new StringSelectMenuOptionBuilder() + .setLabel(page.label.slice(0, 100)) + .setValue(String(i)) + // the selected option is what the dropdown displays + .setDefault(i === index) + if (page.description != null && page.description !== "") { + option.setDescription(page.description.slice(0, 100)) + } + return option + }), + ), + ) +} + +function buildButtons( + index: number, + count: number, + disabled: boolean, +): ActionRowBuilder { + const send = new ButtonBuilder() + .setCustomId(SEND_ID) + .setLabel("Send") + .setStyle(ButtonStyle.Success) + .setDisabled(disabled) + + // there is nothing to browse with a single page + if (count === 1) { + return new ActionRowBuilder().addComponents(send) + } + + return new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(PREVIOUS_ID) + .setLabel("◀ Previous") + .setStyle(ButtonStyle.Secondary) + .setDisabled(disabled), + // not clickable, only shows the position + new ButtonBuilder() + .setCustomId("carousel_position") + .setLabel(`${index + 1} / ${count}`) + .setStyle(ButtonStyle.Secondary) + .setDisabled(true), + new ButtonBuilder() + .setCustomId(NEXT_ID) + .setLabel("Next ▶") + .setStyle(ButtonStyle.Secondary) + .setDisabled(disabled), + send, + ) +} + +/** + * Lays an embed out as a container, with the dropdown above it where the title was + * Embeds can't be combined with the layout components needed to put the dropdown on top + * The embed title is dropped, the dropdown shows it instead + */ +function buildContainer( + pages: CarouselPage[], + index: number, + disabled: boolean, +): ContainerBuilder { + const { embed } = pages[index] + const container = new ContainerBuilder() + + if (embed.color != null) container.setAccentColor(embed.color) + + if (pages.length > 1) { + container.addActionRowComponents(buildSelect(pages, index, disabled)) + } else { + // with one page the title isn't in a dropdown, so show it as a heading + const { label } = pages[index] + container.addTextDisplayComponents( + new TextDisplayBuilder().setContent( + `## ${embed.url != null ? `[${label}](${embed.url})` : label}`, + ), + ) + } + + if (embed.description != null && embed.description !== "") { + const description = embed.description.length > MAX_DESCRIPTION_LENGTH + ? embed.description.slice(0, MAX_DESCRIPTION_LENGTH - 1) + "…" + : embed.description + const text = new TextDisplayBuilder().setContent(description) + + if (embed.thumbnail?.url != null) { + container.addSectionComponents( + new SectionBuilder() + .addTextDisplayComponents(text) + .setThumbnailAccessory( + new ThumbnailBuilder().setURL(embed.thumbnail.url), + ), + ) + } else { + container.addTextDisplayComponents(text) + } + } + + if (embed.fields != null && embed.fields.length > 0) { + container + .addSeparatorComponents( + new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small), + ) + .addTextDisplayComponents( + new TextDisplayBuilder().setContent( + embed.fields + .map((f) => `**${f.name}**: ${f.value.replaceAll("\n", " • ")}`) + .join("\n"), + ), + ) + } + + container + .addSeparatorComponents( + new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small), + ) + .addActionRowComponents(buildButtons(index, pages.length, disabled)) + + if (embed.footer?.text != null) { + container.addTextDisplayComponents( + // small text, like an embed footer + new TextDisplayBuilder().setContent(`-# ${embed.footer.text}`), + ) + } + + return container +} + +/** + * Replies to a deferred command with a private card: one show at a time + * with a dropdown above it to jump to any page, and previous and next buttons + * that wrap around at either end + * A single page has just its title and the Send button + * The Send button posts the current page's embed publicly to the channel + * then deletes the carousel reply + * The controls stop working after TIMEOUT_MS or when the bot restarts + * @param interaction deferred command interaction to reply to + * @param allPages the pages in order, only the first MAX_PAGES are used + */ +export async function sendCarousel( + interaction: ChatInputCommandInteraction, + allPages: CarouselPage[], +): Promise { + const pages = allPages.slice(0, MAX_PAGES) + const count = pages.length + + let index = 0 + + // a message with layout components can't have embeds or content + const buildPage = (disabled = false) => ({ + components: [buildContainer(pages, index, disabled)], + flags: MessageFlags.IsComponentsV2 as const, + }) + + const message = await interaction.editReply(buildPage()) + + const collector = message.createMessageComponentCollector({ + time: TIMEOUT_MS, + filter: (i) => i.user.id === interaction.user.id, + }) + + collector.on("collect", async (componentInteraction) => { + try { + if (componentInteraction.customId === SEND_ID) { + await componentInteraction.deferUpdate() + + // the embed is sent as built, with its title, columns and footer logo + // the user is shown as a name but not pinged + const publicMessage = { + content: + `-# <@${interaction.user.id}> used ${interaction.commandName}`, + embeds: [pages[index].embed], + allowedMentions: { parse: [] }, + } + try { + const channel = componentInteraction.channel + if (channel?.isSendable()) { + await channel.send(publicMessage) + } else { + await componentInteraction.followUp(publicMessage) + } + } catch (error) { + console.error("Error sending carousel page to the channel:", error) + await componentInteraction.followUp({ + content: "Couldn't send that to the channel.", + flags: MessageFlags.Ephemeral, + }) + return + } + + // only remove the carousel once the result has been sent + collector.stop(SENT_REASON) + await interaction.deleteReply() + return + } + + if (componentInteraction.isStringSelectMenu()) { + const selected = Number(componentInteraction.values[0]) + if (Number.isInteger(selected) && selected >= 0 && selected < count) { + index = selected + } + } else if (componentInteraction.customId === NEXT_ID) { + index = (index + 1) % count + } else if (componentInteraction.customId === PREVIOUS_ID) { + index = (index - 1 + count) % count + } + + await componentInteraction.update(buildPage()) + } catch (error) { + console.error("Error changing carousel page:", error) + } + }) + + collector.on("end", async (_collected, reason) => { + // the reply was deleted, so there are no controls left to disable + if (reason === SENT_REASON) return + + try { + await interaction.editReply(buildPage(true)) + } catch (error) { + // the reply may have been dismissed or the interaction token expired + console.debug("Could not disable carousel controls:", error) + } + }) + + return message +} diff --git a/src/lib/tvdb.ts b/src/lib/tvdb.ts index dc1f829..0888fcd 100644 --- a/src/lib/tvdb.ts +++ b/src/lib/tvdb.ts @@ -58,6 +58,13 @@ export async function getSeriesByImdbId( series = await getSeries(data?.season?.seriesId) } + return withEnglishTranslation(series) +} + +/** Swaps in the English name/overview for shows not originally in English. */ +function withEnglishTranslation( + series: SeriesExtendedRecord | undefined, +): SeriesExtendedRecord | undefined { if ( series?.originalLanguage == null || series.originalLanguage === "eng" ) return series @@ -158,6 +165,7 @@ async function searchSeriesByImdbId( async function searchSeriesByName( query: string, + year?: number, ): Promise { try { const params = new URLSearchParams({ @@ -165,6 +173,7 @@ async function searchSeriesByName( limit: "10", q: query, }) + if (year != null) params.set("year", String(year)) const response = await fetch( `${baseURL}/search?${params}`, { @@ -183,9 +192,8 @@ async function searchSeriesByName( const data: { data: SearchResult[] } = await response.json() const searchResult = data?.data - if (searchResult == null || searchResult[0].tvdb_id == null) { - return undefined - } + // an unknown show gives an empty array + if (searchResult == null || searchResult.length === 0) return undefined return searchResult } catch (error) { console.error(`Unexpected Error Searching Series:`, error) @@ -193,11 +201,30 @@ async function searchSeriesByName( return undefined } -export async function getSeriesByName( +export type SeriesCandidate = SearchResult & { tvdb_id: string } + +/** + * Searches TVDB for series matching a name + * Results without a TVDB id, or known to have no IMDB id, are left out + * The search results don't always list IMDB ids, so callers should still + * check the full record from getSeriesByTvdbId + * @param year only return series first aired in this year + * @returns matching series, best match first + */ +export async function getSeriesCandidates( query: string, + year?: number, +): Promise { + const results = await searchSeriesByName(query, year) + + return (results ?? []).filter((r): r is SeriesCandidate => + r.tvdb_id != null && + (r.remote_ids == null || r.remote_ids.some((id) => id.type === 2)) + ) +} + +export async function getSeriesByTvdbId( + tvdbId: number, ): Promise { - const searchResult = await searchSeriesByName(query) - if (searchResult == null || searchResult[0].tvdb_id == null) return undefined - const series = await getSeries(parseInt(searchResult[0].tvdb_id)) - return series + return withEnglishTranslation(await getSeries(tvdbId)) }