feat: autodetect instance software, close #665 (#686)

This commit is contained in:
xylight authored and GitHub committed 2025-11-16 23:45:02 +00:00
1 parent e0e9ca77cd
commit 26540cec82
6 files changed
+171 -80

No files matched your search

+34
View File
@@ -26,6 +26,40 @@ export abstract class BaseClient {
} }
} }
static async fetchInfo(
base: string,
): Promise<{ type: ClientType; version: string } | null> {
try {
const res = await fetch(new URL('/nodeinfo/2.1', base))
if (!res.ok) return null
const software: { name: string; version: string } = (await res.json())
.software
// should probably extract this into not a static function but its ok
switch (software.name) {
case 'lemmy': {
return {
type: { baseUrl: '/api/v3', name: 'lemmy' },
version: software.version,
}
}
case 'piefed': {
return {
type: { baseUrl: '/api/alpha', name: 'piefed' },
version: software.version,
}
}
default:
return null
}
} catch (err) {
console.error(err)
return null
}
}
abstract getSite(): Promise<types.GetSiteResponse> abstract getSite(): Promise<types.GetSiteResponse>
abstract editSite(form: types.EditSite): Promise<types.SiteResponse> abstract editSite(form: types.EditSite): Promise<types.SiteResponse>
abstract generateTotpSecret(): Promise<types.GenerateTotpSecretResponse> abstract generateTotpSecret(): Promise<types.GenerateTotpSecretResponse>
+2 -1
View File
@@ -953,7 +953,8 @@
"not_an_admin": "You are not an admin of this server.", "not_an_admin": "You are not an admin of this server.",
"rate_limit_error": "You are performing that action too fast.", "rate_limit_error": "You are performing that action too fast.",
"unimplemented": "That function of your account's server software is not yet supported by Photon.", "unimplemented": "That function of your account's server software is not yet supported by Photon.",
"unsupported": "That function is not supported by your account's server software." "unsupported": "That function is not supported by your account's server software.",
"not_live_supported": "That server is not running supported software, or is offline."
}, },
"aria": { "aria": {
"pagination": { "pagination": {
+4 -3
View File
@@ -65,9 +65,10 @@
<Label <Label
for={id} for={id}
text={label} text={label}
class="peer-invalid:text-red-500 {required class={[
? "after:content-['*'] after:text-red-500 after:ml-1" 'peer-invalid:text-red-500 relative',
: ''}" required && "after:content-['*'] after:text-red-500 after:ml-1",
]}
> >
{@render passedCustomLabel?.()} {@render passedCustomLabel?.()}
</Label> </Label>
+1 -1
View File
@@ -27,7 +27,7 @@
{#if children} {#if children}
{@render children?.()} {@render children?.()}
{:else if content} {:else if content}
<p> <p class="text-left justify-self-start">
{content} {content}
</p> </p>
{/if} {/if}
+72 -47
View File
@@ -1,7 +1,11 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation' import { goto } from '$app/navigation'
import { page } from '$app/state' import { page } from '$app/state'
import { type ClientType, DEFAULT_CLIENT_TYPE } from '$lib/api/base' import {
BaseClient,
type ClientType,
DEFAULT_CLIENT_TYPE,
} from '$lib/api/base'
import { client } from '$lib/api/client.svelte' import { client } from '$lib/api/client.svelte'
import { LemmyClient } from '$lib/api/lemmy/adapter' import { LemmyClient } from '$lib/api/lemmy/adapter'
import { PiefedClient } from '$lib/api/piefed/adapter' import { PiefedClient } from '$lib/api/piefed/adapter'
@@ -12,19 +16,22 @@
DEFAULT_INSTANCE_URL, DEFAULT_INSTANCE_URL,
LINKED_INSTANCE_URL, LINKED_INSTANCE_URL,
} from '$lib/app/instance.svelte' } from '$lib/app/instance.svelte'
import { DOMAIN_REGEX_FORMS } from '$lib/app/util.svelte' import { DOMAIN_REGEX_FORMS, instanceToURL } from '$lib/app/util.svelte'
import ErrorContainer, { import ErrorContainer, {
clearErrorScope, clearErrorScope,
pushError, pushError,
} from '$lib/ui/info/ErrorContainer.svelte' } from '$lib/ui/info/ErrorContainer.svelte'
import { Header } from '$lib/ui/layout' import { Header } from '$lib/ui/layout'
import { Button, Note, Option, Select, TextInput, toast } from 'mono-svelte' import { Button, Note, Spinner, TextInput, toast } from 'mono-svelte'
import { debounce } from 'mono-svelte/util/time'
import { import {
Icon, Icon,
Identification, Identification,
QuestionMarkCircle, QuestionMarkCircle,
UserCircle, UserCircle,
} from 'svelte-hero-icons/dist' } from 'svelte-hero-icons/dist'
import { expoOut } from 'svelte/easing'
import { fly } from 'svelte/transition'
interface Props { interface Props {
ref?: string ref?: string
@@ -34,7 +41,7 @@
let { ref = page.url.searchParams.get('redirect') ?? '/', children }: Props = let { ref = page.url.searchParams.get('redirect') ?? '/', children }: Props =
$props() $props()
let data = $state<{ let form = $state<{
instance: string instance: string
username: string username: string
password: string password: string
@@ -52,29 +59,37 @@
client: DEFAULT_CLIENT_TYPE, client: DEFAULT_CLIENT_TYPE,
}) })
async function checkInstance() {
const type = await BaseClient.fetchInfo(instanceToURL(form.instance))
if (type == null) throw Error('not_live_supported')
form.client = type?.type
}
async function logIn() { async function logIn() {
data.loading = true form.loading = true
clearErrorScope(page.route.id) clearErrorScope(page.route.id)
try { try {
// leading HTTPS is redundant // leading HTTPS is redundant
data.instance = data.instance.trim().replace(/^https:\/\//, '') form.instance = form.instance.trim().replace(/^https:\/\//, '')
await checkInstance()
const response = await client({ const response = await client({
instanceURL: data.instance, instanceURL: form.instance,
clientType: data.client, clientType: form.client,
auth: '', auth: '',
}).login({ }).login({
username_or_email: data.username.trim(), username_or_email: form.username.trim(),
password: data.password, password: form.password,
totp_2fa_token: data.totp, totp_2fa_token: form.totp,
}) })
if (response?.jwt) { if (response?.jwt) {
const result = await profile.add( const result = await profile.add(
response.jwt, response.jwt,
data.instance, form.instance,
data.client, form.client,
) )
if (result) { if (result) {
@@ -92,17 +107,35 @@
'incorrect_login' 'incorrect_login'
? errorMessage( ? errorMessage(
'incorrect_login' + 'incorrect_login' +
(data.attempts == 0 || data.attempts >= 12 (form.attempts == 0 || form.attempts >= 12
? '' ? ''
: `_${data.attempts + 1}`), : `_${form.attempts + 1}`),
) )
: errorMessage(error), : errorMessage(error),
scope: page.route.id!, scope: page.route.id!,
}) })
data.attempts++ form.attempts++
} }
data.loading = false form.loading = false
} }
let detectedClient = $state<string | null | undefined>()
const checkDebounce = debounce(async () => {
const startingText = form.instance
try {
detectedClient = null
await checkInstance()
// so that debounce desync thing doesnt happen
if (startingText == form.instance) detectedClient = form.client.name
} catch {
if (startingText == form.instance) detectedClient = undefined
}
}, 500)
$effect(() => {
if (form.instance) checkDebounce()
})
</script> </script>
<svelte:head> <svelte:head>
@@ -122,7 +155,7 @@
<Header>{$t('account.login')}</Header> <Header>{$t('account.login')}</Header>
<ErrorContainer class="pt-2" scope={page.route.id} /> <ErrorContainer class="pt-2" scope={page.route.id} />
</div> </div>
{#if data.client.name == 'piefed'} {#if form.client.name == 'piefed'}
<Note> <Note>
{$t('account.piefedGate')} {$t('account.piefedGate')}
</Note> </Note>
@@ -130,7 +163,7 @@
<div class="flex flex-row w-full items-center gap-2"> <div class="flex flex-row w-full items-center gap-2">
<TextInput <TextInput
id="username" id="username"
bind:value={data.username} bind:value={form.username}
label={$t('form.username')} label={$t('form.username')}
class="flex-1" class="flex-1"
required required
@@ -138,37 +171,29 @@
{#if !LINKED_INSTANCE_URL} {#if !LINKED_INSTANCE_URL}
<TextInput <TextInput
id="instance_url" id="instance_url"
label={$t('form.instance')}
placeholder={DEFAULT_INSTANCE_URL} placeholder={DEFAULT_INSTANCE_URL}
disabled={LINKED_INSTANCE_URL != undefined} disabled={LINKED_INSTANCE_URL != undefined}
bind:value={data.instance} bind:value={form.instance}
class="flex-1 overflow-hidden" class="flex-1 overflow-hidden"
required required
pattern={DOMAIN_REGEX_FORMS} pattern={DOMAIN_REGEX_FORMS}
autocorrect="off" autocorrect="off"
autocapitalize="off" autocapitalize="off"
> >
{#snippet suffix()} {#snippet customLabel()}
<Select {$t('form.instance')}
bind:value={ <span class="absolute right-0">
() => { {#if detectedClient}
if (data.client.name == 'lemmy') return 'lemmyv3' <span
else return 'piefedvalpha' class="capitalize font-normal"
}, in:fly={{ duration: 300, y: 2, easing: expoOut }}
(v) => {
if (v == 'lemmyv3')
data.client = { name: 'lemmy', baseUrl: '/api/v3' }
else data.client = { name: 'piefed', baseUrl: '/api/alpha' }
}
}
class="border-y-0! border-r-0! rounded-none! border-l max-w-24"
> >
<Option data-label="true" value="placeholder" disabled> {detectedClient}
{$t('form.instanceType')} </span>
</Option> {:else if detectedClient === null}
<Option value="lemmyv3">Lemmy</Option> <Spinner />
<Option value="piefedvalpha">Piefed</Option> {/if}
</Select> </span>
{/snippet} {/snippet}
</TextInput> </TextInput>
{/if} {/if}
@@ -176,13 +201,13 @@
<div role="presentation" class="flex flex-row gap-2"> <div role="presentation" class="flex flex-row gap-2">
<TextInput <TextInput
id="password" id="password"
bind:value={data.password} bind:value={form.password}
label={$t('form.password')} label={$t('form.password')}
type="password" type="password"
minlength={data.client.name == 'piefed' minlength={form.client.name == 'piefed'
? PiefedClient.constants.password.minLength ? PiefedClient.constants.password.minLength
: LemmyClient.constants.password.minLength} : LemmyClient.constants.password.minLength}
maxlength={data.client.name == 'piefed' maxlength={form.client.name == 'piefed'
? PiefedClient.constants.password.maxLength ? PiefedClient.constants.password.maxLength
: LemmyClient.constants.password.maxLength} : LemmyClient.constants.password.maxLength}
required required
@@ -190,7 +215,7 @@
/> />
<TextInput <TextInput
id="totp" id="totp"
bind:value={data.totp} bind:value={form.totp}
label={$t('form.2fa')} label={$t('form.2fa')}
placeholder="123456" placeholder="123456"
pattern={'\\d{6}'} pattern={'\\d{6}'}
@@ -200,8 +225,8 @@
/> />
</div> </div>
<Button <Button
loading={data.loading} loading={form.loading}
disabled={data.loading} disabled={form.loading}
color="primary" color="primary"
size="lg" size="lg"
submit submit
+58 -28
View File
@@ -1,15 +1,22 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation' import { goto } from '$app/navigation'
import { page } from '$app/state' import { page } from '$app/state'
import { type ClientType, DEFAULT_CLIENT_TYPE } from '$lib/api/base' import {
import { validateInstance } from '$lib/api/client.svelte' BaseClient,
type ClientType,
DEFAULT_CLIENT_TYPE,
} from '$lib/api/base'
import { profile } from '$lib/app/auth.svelte' import { profile } from '$lib/app/auth.svelte'
import { errorMessage } from '$lib/app/error'
import { t } from '$lib/app/i18n' import { t } from '$lib/app/i18n'
import { LINKED_INSTANCE_URL } from '$lib/app/instance.svelte' import { LINKED_INSTANCE_URL } from '$lib/app/instance.svelte'
import { DOMAIN_REGEX_FORMS } from '$lib/app/util.svelte' import { DOMAIN_REGEX_FORMS, instanceToURL } from '$lib/app/util.svelte'
import { Header } from '$lib/ui/layout' import { Header } from '$lib/ui/layout'
import { Button, Option, Select, TextInput, toast } from 'mono-svelte' import { Button, Spinner, TextInput, toast } from 'mono-svelte'
import { debounce } from 'mono-svelte/util/time'
import { expoOut } from 'svelte/easing'
import { preventDefault } from 'svelte/legacy' import { preventDefault } from 'svelte/legacy'
import { fly } from 'svelte/transition'
interface Props { interface Props {
ref?: string ref?: string
@@ -31,14 +38,18 @@
client: DEFAULT_CLIENT_TYPE, client: DEFAULT_CLIENT_TYPE,
}) })
async function addGuest() { async function checkInstance() {
form.loading = true const type = await BaseClient.fetchInfo(instanceToURL(form.instance))
if (!(await validateInstance(form.instance, form.client))) { if (type == null) throw Error('not_live_supported')
toast({ content: $t('toast.failInstanceURL'), type: 'error' }) form.client = type?.type
form.loading = false
return
} }
async function addGuest() {
try {
form.loading = true
await checkInstance()
const id = Math.max(...profile.meta.profiles.map((i) => i.id)) + 1 const id = Math.max(...profile.meta.profiles.map((i) => i.id)) + 1
profile.meta.profiles.push({ profile.meta.profiles.push({
id: id, id: id,
@@ -51,9 +62,33 @@
toast({ content: $t('toast.addAccount'), type: 'success' }) toast({ content: $t('toast.addAccount'), type: 'success' })
goto(ref) goto(ref)
} catch (err) {
toast({
content: errorMessage(err as string),
type: 'error',
})
form.loading = false form.loading = false
} }
}
let detectedClient = $state<string | null | undefined>()
const checkDebounce = debounce(async () => {
const startingText = form.instance
try {
detectedClient = null
await checkInstance()
// so that debounce desync thing doesnt happen
if (startingText == form.instance) detectedClient = form.client.name
} catch {
if (startingText == form.instance) detectedClient = undefined
}
}, 500)
$effect(() => {
if (form.instance && !LINKED_INSTANCE_URL) checkDebounce()
})
</script> </script>
<div class="max-w-xl w-full mx-auto h-max my-auto"> <div class="max-w-xl w-full mx-auto h-max my-auto">
@@ -74,7 +109,6 @@
{#if !LINKED_INSTANCE_URL} {#if !LINKED_INSTANCE_URL}
<TextInput <TextInput
required required
label={$t('form.instance')}
bind:value={form.instance} bind:value={form.instance}
pattern={DOMAIN_REGEX_FORMS} pattern={DOMAIN_REGEX_FORMS}
placeholder="example.com" placeholder="example.com"
@@ -82,24 +116,20 @@
autocorrect="off" autocorrect="off"
autocapitalize="none" autocapitalize="none"
> >
{#snippet suffix()} {#snippet customLabel()}
<Select {$t('form.instance')}
bind:value={ <span class="absolute right-0">
() => { {#if detectedClient}
if (form.client.name == 'lemmy') return 'lemmyv3' <span
else return 'piefedvalpha' class="capitalize font-normal"
}, in:fly={{ duration: 300, y: 2, easing: expoOut }}
(v) => {
if (v == 'lemmyv3')
form.client = { name: 'lemmy', baseUrl: '/api/v3' }
else form.client = { name: 'piefed', baseUrl: '/api/alpha' }
}
}
class="border-y-0! border-r-0! rounded-none! border-l"
> >
<Option value="lemmyv3">Lemmy</Option> {detectedClient}
<Option value="piefedvalpha">Piefed</Option> </span>
</Select> {:else if detectedClient === null}
<Spinner />
{/if}
</span>
{/snippet} {/snippet}
</TextInput> </TextInput>
{/if} {/if}