feat: custom api id/hash/etc

This commit is contained in:
alina 🌸 2025-01-24 19:53:25 +03:00
parent 3f4dcf2c4f
commit ce33cfac9a
Signed by: teidesu
SSH key fingerprint: SHA256:uNeCpw6aTSU4aIObXLvHfLkDa82HWH9EiOj9AXOIRpI
8 changed files with 335 additions and 40 deletions

View file

@ -1,24 +1,26 @@
import type { DropdownMenuTriggerProps } from '@kobalte/core/dropdown-menu'
import type { TooltipTriggerProps } from '@kobalte/core/tooltip'
import type { TelegramAccount } from 'mtcute-repl-worker/client'
import type { CustomApiFields, TelegramAccount } from 'mtcute-repl-worker/client'
import type { LoginStep } from './login/Login.tsx'
import { timers, unknownToError } from '@fuman/utils'
import {
LucideBot,
LucideChevronDown,
LucideChevronRight,
LucideEllipsis,
LucideFlaskConical,
LucideFolderUp,
LucideLogIn,
LucidePlus,
LucideRefreshCw,
LucideSearch,
LucideServerCog,
LucideTrash,
LucideTriangleAlert,
LucideUser,
LucideX,
} from 'lucide-solid'
import { workerInvoke } from 'mtcute-repl-worker/client'
import { workerInvoke } from 'mtcute-repl-worker/client'
import { nanoid } from 'nanoid'
import { createEffect, createMemo, createSignal, For, on, onCleanup, Show } from 'solid-js'
import { toast } from 'solid-sonner'
@ -36,11 +38,13 @@ import { useStore } from '../../store/use-store.ts'
import { AccountAvatar } from '../AccountAvatar.tsx'
import { ImportDropdown } from './import/ImportDropdown.tsx'
import { StringSessionDefs } from './import/StringSessionImportDialog.tsx'
import { CustomApiDialog } from './login/CustomApiDialog.tsx'
import { LoginForm } from './login/Login.tsx'
function AddAccountDialog(props: {
show: boolean
testMode: boolean
apiOptions?: CustomApiFields
onClose: () => void
}) {
const [accountId, setAccountId] = createSignal<string | undefined>(undefined)
@ -81,6 +85,7 @@ function AddAccountDialog(props: {
await workerInvoke('telegram', 'createClient', {
accountId: accountId()!,
testMode: props.testMode,
apiOptions: props.apiOptions,
})
}))
@ -281,17 +286,71 @@ function AccountRow(props: {
)
}
type AddAccountMode = 'test' | 'custom-api' | 'normal'
function LoginButton(props: {
size: 'xs' | 'sm'
onAddAccount: (mode: AddAccountMode) => void
}) {
const [showDropdown, setShowDropdown] = createSignal(false)
return (
<div class="flex flex-row items-center">
<Button
variant="outline"
size={props.size}
onClick={() => props.onAddAccount('normal')}
class="rounded-r-none"
>
Log in
</Button>
<DropdownMenu
open={showDropdown()}
onOpenChange={setShowDropdown}
>
<DropdownMenuTrigger>
<Button
variant="outline"
size={props.size}
class="w-6 rounded-l-none border-l-0"
>
<LucideChevronDown class="size-3 shrink-0" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem class="py-1 text-xs" onClick={() => props.onAddAccount('test')}>
<LucideFlaskConical class="mr-2 size-3.5 stroke-[1.5px]" />
Use test server
</DropdownMenuItem>
<DropdownMenuItem class="py-1 text-xs" onClick={() => props.onAddAccount('custom-api')}>
<LucideServerCog class="mr-2 size-3.5 stroke-[1.5px]" />
Use custom API
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
)
}
export function AccountsTab() {
const accounts = useStore($accounts)
const activeAccountId = useStore($activeAccountId)
const [showAddAccount, setShowAddAccount] = createSignal(false)
const [addAccountTestMode, setAddAccountTestMode] = createSignal(false)
const [addAccountOptions, setAddAccountOptions] = createSignal<CustomApiFields>()
const [searchQuery, setSearchQuery] = createSignal('')
function handleAddAccount(e: MouseEvent) {
const [showCustomApi, setShowCustomApi] = createSignal(false)
function handleAddAccount(mode: AddAccountMode) {
if (mode === 'custom-api') {
setShowCustomApi(true)
return
}
setShowAddAccount(true)
setAddAccountTestMode(e.ctrlKey || e.metaKey)
setAddAccountTestMode(mode === 'test')
setAddAccountOptions(undefined)
}
const filteredAccounts = createMemo(() => {
@ -329,14 +388,7 @@ export function AccountsTab() {
No accounts yet
<div class="flex flex-row gap-2">
<Button
variant="outline"
size="sm"
onClick={handleAddAccount}
>
<LucidePlus class="mr-2 size-4" />
Log in
</Button>
<LoginButton size="sm" onAddAccount={handleAddAccount} />
<ImportDropdown size="sm" />
</div>
</div>
@ -363,15 +415,7 @@ export function AccountsTab() {
</TextFieldFrame>
</TextFieldRoot>
<Button
variant="outline"
size="xs"
onClick={handleAddAccount}
>
<LucidePlus class="mr-2 size-3" />
Log in
</Button>
<LoginButton size="xs" onAddAccount={handleAddAccount} />
<ImportDropdown size="xs" />
</div>
<div class="flex max-w-full flex-col gap-1 overflow-hidden">
@ -391,8 +435,19 @@ export function AccountsTab() {
<AddAccountDialog
show={showAddAccount()}
testMode={addAccountTestMode()}
apiOptions={addAccountOptions()}
onClose={() => setShowAddAccount(false)}
/>
<CustomApiDialog
visible={showCustomApi()}
setVisible={setShowCustomApi}
onSubmit={(options) => {
setShowCustomApi(false)
setAddAccountOptions(options)
setShowAddAccount(true)
}}
/>
</>
)
}

View file

@ -0,0 +1,176 @@
import type { CustomApiFields } from 'mtcute-repl-worker/client'
import type { SetStoreFunction } from 'solid-js/store'
import { createSignal, Show } from 'solid-js'
import { createStore, unwrap } from 'solid-js/store'
import { Button } from '../../../lib/components/ui/button.tsx'
import { Checkbox, CheckboxControl, CheckboxLabel } from '../../../lib/components/ui/checkbox.tsx'
import { Dialog, DialogContent, DialogHeader } from '../../../lib/components/ui/dialog.tsx'
import { TextField, TextFieldFrame, TextFieldLabel, TextFieldRoot } from '../../../lib/components/ui/text-field.tsx'
export function useCustomApiFormState() {
// eslint-disable-next-line solid/reactivity
return createStore<CustomApiFields>({
apiId: '',
apiHash: '',
deviceModel: '',
systemVersion: '',
appVersion: '',
systemLangCode: '',
langPack: '',
langCode: '',
extraJson: '',
})
}
export function CustomApiForm(props: {
class?: string
state: CustomApiFields
setState: SetStoreFunction<CustomApiFields>
}) {
const [showAdvanced, setShowAdvanced] = createSignal(false)
return (
<div class="flex flex-col gap-2">
<TextFieldRoot>
<TextFieldLabel>API ID</TextFieldLabel>
<TextFieldFrame>
<TextField
placeholder="2040"
value={props.state.apiId}
onInput={e => props.setState('apiId', e.currentTarget.value.replace(/\D/g, ''))}
/>
</TextFieldFrame>
</TextFieldRoot>
<TextFieldRoot>
<TextFieldLabel>API Hash</TextFieldLabel>
<TextFieldFrame>
<TextField
placeholder="b18441..."
value={props.state.apiHash}
onInput={e => props.setState('apiHash', e.currentTarget.value)}
/>
</TextFieldFrame>
</TextFieldRoot>
<Checkbox
checked={showAdvanced()}
onChange={setShowAdvanced}
class="my-2 flex flex-row items-center gap-2 text-sm"
>
<CheckboxControl />
<CheckboxLabel>
Show advanced fields
</CheckboxLabel>
</Checkbox>
<Show when={showAdvanced()}>
<div class="flex w-full flex-row gap-2">
<TextFieldRoot class="w-full">
<TextFieldLabel>Device model</TextFieldLabel>
<TextFieldFrame>
<TextField
placeholder="iPhone14,5"
value={props.state.deviceModel}
onInput={e => props.setState('deviceModel', e.currentTarget.value)}
/>
</TextFieldFrame>
</TextFieldRoot>
<TextFieldRoot class="w-full">
<TextFieldLabel>Language pack</TextFieldLabel>
<TextFieldFrame>
<TextField
placeholder="ios"
value={props.state.langPack}
onInput={e => props.setState('langPack', e.currentTarget.value)}
/>
</TextFieldFrame>
</TextFieldRoot>
</div>
<div class="flex w-full flex-row gap-2">
<TextFieldRoot class="w-full">
<TextFieldLabel>System version</TextFieldLabel>
<TextFieldFrame>
<TextField
placeholder="15.4"
value={props.state.systemVersion}
onInput={e => props.setState('systemVersion', e.currentTarget.value)}
/>
</TextFieldFrame>
</TextFieldRoot>
<TextFieldRoot class="w-full">
<TextFieldLabel>App version</TextFieldLabel>
<TextFieldFrame>
<TextField
placeholder="4.0.1"
value={props.state.appVersion}
onInput={e => props.setState('appVersion', e.currentTarget.value)}
/>
</TextFieldFrame>
</TextFieldRoot>
</div>
<div class="flex w-full flex-row gap-2">
<TextFieldRoot class="w-full">
<TextFieldLabel>System language code</TextFieldLabel>
<TextFieldFrame>
<TextField
placeholder="en"
value={props.state.systemLangCode}
onInput={e => props.setState('systemLangCode', e.currentTarget.value)}
/>
</TextFieldFrame>
</TextFieldRoot>
<TextFieldRoot class="w-full">
<TextFieldLabel>Language code</TextFieldLabel>
<TextFieldFrame>
<TextField
placeholder="en"
value={props.state.langCode}
onInput={e => props.setState('langCode', e.currentTarget.value)}
/>
</TextFieldFrame>
</TextFieldRoot>
</div>
<TextFieldRoot class="w-full">
<TextFieldLabel>Extra options (JSON)</TextFieldLabel>
<TextFieldFrame class="h-auto">
<TextField
as="textarea"
class="h-20 resize-none font-mono"
placeholder={'{"tz_offset": 3600}'}
value={props.state.extraJson}
onInput={e => props.setState('extraJson', e.currentTarget.value)}
/>
</TextFieldFrame>
</TextFieldRoot>
</Show>
</div>
)
}
export function CustomApiDialog(props: {
visible: boolean
setVisible: (visible: boolean) => void
onSubmit: (options: CustomApiFields) => void
}) {
const [state, setState] = useCustomApiFormState()
return (
<Dialog open={props.visible} onOpenChange={props.setVisible}>
<DialogContent class="flex flex-col gap-2">
<DialogHeader class="font-medium">
Custom connection options
</DialogHeader>
<CustomApiForm state={state} setState={setState} />
<Button
size="sm"
disabled={!state.apiId || !state.apiHash}
onClick={() => props.onSubmit(unwrap(state))}
>
Submit
</Button>
</DialogContent>
</Dialog>
)
}

View file

@ -4,6 +4,7 @@ import { unknownToError } from '@fuman/utils'
import { LucideChevronRight, LucideLockKeyhole, MessageSquareMore } from 'lucide-solid'
import { workerInvoke, workerOn } from 'mtcute-repl-worker/client'
import { createSignal, For, Match, onCleanup, onMount, Show, Switch } from 'solid-js'
import { toast } from 'solid-sonner'
import { Button } from '../../../lib/components/ui/button.tsx'
import { OTPField, OTPFieldGroup, OTPFieldInput, OTPFieldSlot } from '../../../lib/components/ui/otp-field.tsx'
import { Spinner } from '../../../lib/components/ui/spinner.tsx'
@ -55,14 +56,18 @@ function QrLoginStep(props: StepProps<'qr'>) {
cleanup2()
})
const result = await workerInvoke('telegram', 'signInQr', {
accountId: props.accountId,
abortSignal: abortController.signal,
})
if (result === 'need_password') {
props.setStep('password')
} else {
props.setStep('done', { account: result })
try {
const result = await workerInvoke('telegram', 'signInQr', {
accountId: props.accountId,
abortSignal: abortController.signal,
})
if (result === 'need_password') {
props.setStep('password')
} else {
props.setStep('done', { account: result })
}
} catch (e) {
toast.error(unknownToError(e).message)
}
})
onCleanup(() => abortController.abort())

View file

@ -131,7 +131,7 @@ export function TextField<T extends ValidComponent = 'input'>(props: Polymorphic
return (
<TextFieldPrimitive.Input
class={cn('border-none outline-none placeholder:text-muted-foreground bg-transparent', local.class)}
class={cn('border-none outline-none placeholder:text-muted-foreground bg-transparent min-w-0 w-full', local.class)}
{...rest}
/>
)

View file

@ -3,7 +3,7 @@ import type { ReplWorker } from './worker/main.ts'
import type { ReplWorkerEvents } from './worker/utils.ts'
import { Deferred, unknownToError } from '@fuman/utils'
export type { TelegramAccount } from './store/accounts.ts'
export type { CustomApiFields, TelegramAccount } from './store/accounts.ts'
export type { StringSessionLibName } from './worker/telegram.ts'
// eslint-disable-next-line ts/no-namespace

View file

@ -9,6 +9,19 @@ export interface TelegramAccount {
testMode: boolean
telegramId: number
dcId: number
apiOptions?: CustomApiFields
}
export interface CustomApiFields {
apiId: string
apiHash: string
deviceModel: string
systemVersion: string
appVersion: string
systemLangCode: string
langPack: string
langCode: string
extraJson: string
}
const AccountSchema = v.object({
@ -19,6 +32,17 @@ const AccountSchema = v.object({
name: v.string(),
testMode: v.boolean(),
dcId: v.number(),
apiOptions: v.object({
apiId: v.string(),
apiHash: v.string(),
deviceModel: v.string(),
systemVersion: v.string(),
appVersion: v.string(),
systemLangCode: v.string(),
langPack: v.string(),
langCode: v.string(),
extraJson: v.string(),
}).optional(),
})
export const $accounts = persistentAtom<TelegramAccount[]>('repl:accounts', [], {

View file

@ -1,17 +1,49 @@
import type { InputStringSessionData } from '@mtcute/web/utils.js'
import type { TelegramAccount } from '../store/accounts.ts'
import type { tl } from '@mtcute/web'
import type { CustomApiFields, TelegramAccount } from '../store/accounts.ts'
import { asNonNull } from '@fuman/utils'
import { BaseTelegramClient, IdbStorage, TransportError } from '@mtcute/web'
import { getMe } from '@mtcute/web/methods.js'
import { type InputStringSessionData, jsonToTlJson } from '@mtcute/web/utils.js'
import { nanoid } from 'nanoid'
export function createInternalClient(accountId: string, testMode?: boolean) {
export function createInternalClient(
accountId: string,
testMode?: boolean,
apiOptions?: CustomApiFields,
) {
let initConnectionOptions: Partial<tl.RawInitConnectionRequest> | undefined
if (apiOptions) {
initConnectionOptions = {}
if (apiOptions.deviceModel) {
initConnectionOptions.deviceModel = apiOptions.deviceModel
}
if (apiOptions.systemVersion) {
initConnectionOptions.systemVersion = apiOptions.systemVersion
}
if (apiOptions.appVersion) {
initConnectionOptions.appVersion = apiOptions.appVersion
}
if (apiOptions.langCode) {
initConnectionOptions.langCode = apiOptions.langCode
}
if (apiOptions.langPack) {
initConnectionOptions.langPack = apiOptions.langPack
}
if (apiOptions.systemLangCode) {
initConnectionOptions.systemLangCode = apiOptions.systemLangCode
}
if (apiOptions.extraJson) {
initConnectionOptions.params = jsonToTlJson(JSON.parse(apiOptions.extraJson))
}
}
return new BaseTelegramClient({
apiId: Number(import.meta.env.VITE_API_ID),
apiHash: import.meta.env.VITE_API_HASH,
apiId: Number(apiOptions?.apiId ?? import.meta.env.VITE_API_ID),
apiHash: apiOptions?.apiHash ?? import.meta.env.VITE_API_HASH,
storage: new IdbStorage(`mtcute:${accountId}`),
testMode,
logLevel: import.meta.env.DEV ? 5 : 2,
initConnectionOptions,
})
}

View file

@ -1,6 +1,6 @@
import type { BaseTelegramClient, SentCode, User } from '@mtcute/web'
import type { StringSessionData } from '@mtcute/web/utils.js'
import type { TelegramAccount } from '../store/accounts.ts'
import type { CustomApiFields, TelegramAccount } from '../store/accounts.ts'
import { assert, hex } from '@fuman/utils'
import { DC_MAPPING_PROD, DC_MAPPING_TEST } from '@mtcute/convert'
import { tl } from '@mtcute/web'
@ -31,7 +31,9 @@ function getClient(accountId: string) {
function getTmpClient(accountId: string): [BaseTelegramClient, () => Promise<void>] {
const client = clients.get(accountId)
if (!client) {
const tmpClient = createInternalClient(accountId)
const accountInfo = $accounts.get().find(it => it.id === accountId)
if (!accountInfo) throw new Error('Account not found')
const tmpClient = createInternalClient(accountId, accountInfo.testMode, accountInfo.apiOptions)
return [tmpClient, () => tmpClient.close()]
} else {
return [client, () => Promise.resolve()]
@ -73,8 +75,9 @@ export class ReplWorkerTelegram {
async createClient(params: {
accountId: string
testMode?: boolean
apiOptions?: CustomApiFields
}) {
const client = createInternalClient(params.accountId, params.testMode)
const client = createInternalClient(params.accountId, params.testMode, params.apiOptions)
clients.set(params.accountId, client)
}