diff --git a/src/helpers/Questions.ts b/src/helpers/Questions.ts index 75afe04f..b435b099 100644 --- a/src/helpers/Questions.ts +++ b/src/helpers/Questions.ts @@ -1,12 +1,11 @@ import { authentication, QuickPickItem, QuickPickItemKind, window } from 'vscode'; -import { Backers } from '../commands'; import { Folders } from '../commands/Folders'; -import { SETTING_SEO_TITLE_LENGTH, SETTING_SPONSORS_AI_TITLE } from '../constants'; +import { SETTING_SPONSORS_AI_TITLE } from '../constants'; import { ContentType } from './ContentType'; import { Notifications } from './Notifications'; import { Settings } from './SettingsHelper'; import { Logger } from './Logger'; -import fetch from 'node-fetch'; +import { SponsorAi } from '../services/SponsorAI'; export class Questions { /** @@ -45,21 +44,9 @@ export class Questions { if (title) { try { - const response = await fetch(`https://frontmatter.codes/api/ai-title`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - accept: 'application/json' - }, - body: JSON.stringify({ - title: title, - username: githubAuth.account.label, - nrOfCharacters: Settings.get(SETTING_SEO_TITLE_LENGTH) || 60 - }) - }); - const data: string[] = await response.json(); + const aiTitles = await SponsorAi.getTitles(githubAuth.accessToken, title); - if (data && data.length > 0) { + if (aiTitles && aiTitles.length > 0) { const options: QuickPickItem[] = [ { label: `✏️ your title/description`, @@ -72,7 +59,7 @@ export class Questions { label: `🤖 AI generated title`, kind: QuickPickItemKind.Separator }, - ...data.map((d: string) => ({ + ...aiTitles.map((d: string) => ({ label: d })) ]; diff --git a/src/services/SponsorAI.ts b/src/services/SponsorAI.ts new file mode 100644 index 00000000..62d51bac --- /dev/null +++ b/src/services/SponsorAI.ts @@ -0,0 +1,38 @@ +import { SETTING_SEO_TITLE_LENGTH } from '../constants'; +import { Logger, Notifications, Settings } from '../helpers'; +import fetch from 'node-fetch'; + +export class SponsorAi { + public static async getTitles(token: string, title: string) { + try { + const controller = new AbortController(); + const timeout = setTimeout(() => { + Notifications.warning(`The AI title generation took too long. Please try again later.`); + controller.abort(); + }, 10000); + const signal = controller.signal; + + const response = await fetch(`https://frontmatter.codes/api/ai-title`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + accept: 'application/json' + }, + body: JSON.stringify({ + title: title, + token: token, + nrOfCharacters: Settings.get(SETTING_SEO_TITLE_LENGTH) || 60 + }), + signal: signal as any + }); + clearTimeout(timeout); + + const data: string[] = await response.json(); + + return data || []; + } catch (e) { + Logger.error(`Sponsor AI: ${(e as Error).message}`); + return undefined; + } + } +}