Skip to content

Commit

Permalink
chore: tidying up classes with new init
Browse files Browse the repository at this point in the history
  • Loading branch information
Keyrxng committed Sep 7, 2024
1 parent 80db604 commit 3ea8747
Show file tree
Hide file tree
Showing 10 changed files with 226 additions and 205 deletions.
2 changes: 1 addition & 1 deletion src/types/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const env = T.Object({
BOT_ADMINS: T.Transform(T.Unknown()).Decode((str) => Array.isArray(str) ? str.map(Number) : [Number(str)]).Encode((arr) => arr.toString()),
ALLOWED_UPDATES: T.Optional(T.Array(T.KeyOf(allowedUpdates))),
SUPABASE_URL: T.String(),
SUPABASE_KEY: T.String(),
SUPABASE_SERVICE_KEY: T.String(),
TELEGRAM_APP_ID: T.Transform(T.Unknown()).Decode((str) => Number(str)).Encode((num) => num.toString()),
TELEGRAM_API_HASH: T.String(),
APP_ID: T.Transform(T.Unknown()).Decode((str) => Number(str)).Encode((num) => num.toString()),
Expand Down
109 changes: 0 additions & 109 deletions src/workflow-functions/bot/auth-handler.ts

This file was deleted.

79 changes: 0 additions & 79 deletions src/workflow-functions/bot/mtproto-single.ts

This file was deleted.

46 changes: 46 additions & 0 deletions src/workflow-functions/bot/mtproto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Context } from '#root/types/context.js';
import dotenv from "dotenv";
import { BaseMtProto } from './scripts/sms-auth/base-mtproto';
import { SupabaseSession } from './session';
import { createClient, SupabaseClient } from '@supabase/supabase-js';
dotenv.config();

export class MtProto extends BaseMtProto {
private supabase: SupabaseClient | null = null;
private context: Context;
_session: SupabaseSession;

constructor(context: Context) {
super();

const key = context.env.SUPABASE_SERVICE_KEY;
const url = context.env.SUPABASE_URL;

if (!key || !url) {
throw new Error("Missing required environment variables for Supabase")
}

this.supabase = createClient(url, key);
this.context = context;
this._session = new SupabaseSession(this.supabase, this.context);
}

async initialize() {
const session = await this._session.getSession();
await super.initialize(this.context.env, session);
}

async saveSession() {
await this._session.saveSession();
}

async deleteSession() {
await this._session.deleteSession();
}

async loadSession() {
await this._session.loadSession();
}
}


66 changes: 66 additions & 0 deletions src/workflow-functions/bot/scripts/sms-auth/auth-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// @ts-expect-error no types for this package
import input from 'input';
import dotenv from "dotenv";
import { createClient, SupabaseClient } from '@supabase/supabase-js';
import { BaseMtProto } from './base-mtproto';
dotenv.config();

/**
* The account holder must run this script (to my knowledge only once) to login,
* this will give us the necessary session information to login in the future.
*/

export class AuthHandler {
private supabase: SupabaseClient | null = null;
private env = {
TELEGRAM_API_HASH: "",
TELEGRAM_APP_ID: 0,
BOT_TOKEN: "",
}

constructor() {
const key = process.env.SUPABASE_SERVICE_KEY;
const url = process.env.SUPABASE_URL;
if (!key || !url) {
throw new Error("Missing required environment variables for Supabase")
}
this.supabase = createClient(url, key);

const hash = process.env.TELEGRAM_API_HASH
const tgAppId = process.env.TELEGRAM_APP_ID
const botToken = process.env.BOT_TOKEN

if (!hash || !tgAppId || !botToken) {
throw new Error("Missing required environment variables for Telegram API")
}

this.env = {
TELEGRAM_API_HASH: hash,
TELEGRAM_APP_ID: Number(tgAppId),
BOT_TOKEN: botToken
}
}

/**
* This method will handle the SMS login process.
*/
async smsLogin() {
const mtProto = new BaseMtProto();
await mtProto.initialize(this.env, "");
try {
// Start the login process
await mtProto.client?.start({
phoneNumber: async () => await input.text('Enter your phone number:'),
password: async () => await input.text('Enter your password if required:'),
phoneCode: async () => await input.text('Enter the code you received:'),
onError: (err: unknown) => console.error('Error during login:', err),
});

await this.supabase?.from('tg-bot-sessions').insert([
{ session_data: mtProto.session?.save() },
]);
} catch (error) {
console.error('Failed to log in:', error);
}
}
}
56 changes: 56 additions & 0 deletions src/workflow-functions/bot/scripts/sms-auth/base-mtproto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { TelegramClient } from 'telegram';
import { Api } from 'telegram/tl';
import { TelegramClientParams } from 'telegram/client/telegramBaseClient';
import dotenv from "dotenv";
import { StringSession } from 'telegram/sessions';
dotenv.config();

type Env = {
TELEGRAM_API_HASH: string;
TELEGRAM_APP_ID: number;
BOT_TOKEN: string;
}

export class BaseMtProto {
// @ts-expect-error properties not defined in constructor, not required in baseclass
_client: TelegramClient; _api: typeof Api;
_session: StringSession | null = null;

async initialize(env: Env, session: string) {
this._api = Api;
this._session = new StringSession(session)
this._client = await this.mtProtoInit(env, this._session);
}

get api() {
return this._api;
}

get client() {
return this._client;
}

get session() {
return this._session;
}

private async mtProtoInit(env: Env, session: StringSession) {
const { TELEGRAM_API_HASH, TELEGRAM_APP_ID, BOT_TOKEN } = env

if (!TELEGRAM_API_HASH || !TELEGRAM_APP_ID || !BOT_TOKEN) {
throw new Error("Missing required environment variables for Telegram API")
}
const clientParams: TelegramClientParams = {
connectionRetries: 5,
}
const client = new TelegramClient(
session,
TELEGRAM_APP_ID,
TELEGRAM_API_HASH,
clientParams
);
await client.connect();
return client;
}
}

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AuthHandler } from "../auth-handler";
import { AuthHandler } from "./auth-handler";
import dotenv from "dotenv";
dotenv.config();

Expand Down
8 changes: 0 additions & 8 deletions src/workflow-functions/bot/scripts/user-auth.ts

This file was deleted.

Loading

0 comments on commit 3ea8747

Please sign in to comment.