Skip to content
Snippets Groups Projects
telegram.service.ts 7.73 KiB
Newer Older
  • Learn to ignore specific revisions
  • Pascal Kosak's avatar
    Pascal Kosak committed
    import { Injectable } from '@nestjs/common';
    import { Message, Metadata } from 'node-telegram-bot-api';
    import * as TelegramBot from 'node-telegram-bot-api';
    import { PrismaService } from '../prisma/prisma.service';
    import * as fs from 'fs';
    import * as path from 'path';
    import { v4 as uuid } from 'uuid';
    
    import { Entry } from '@prisma/client';
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
    @Injectable()
    export class TelegramService {
    
    Pascal Kosak's avatar
    Pascal Kosak committed
        private telegram: TelegramBot;
    
    
        private messageCache = new Map<number, Partial<Entry>>();
    
    
    Pascal Kosak's avatar
    Pascal Kosak committed
        constructor(private prismaService: PrismaService) {
            this.telegram = new TelegramBot(process.env.BOT_TOKEN, {
                polling: true,
            });
    
            this.telegram.onText(/^\/register (.+)/, this.register.bind(this));
            this.telegram.onText(/^\/unregister/, this.unregister.bind(this));
            this.telegram.onText(/^\/state/, this.state.bind(this));
            this.telegram.onText(/^\/start/, this.start.bind(this));
    
    
            this.telegram.onText(/^\/private/, this.private.bind(this));
            this.telegram.onText(/^\/public/, this.public.bind(this));
            this.telegram.onText(/^\/clear/, this.clear.bind(this));
    
    
    Pascal Kosak's avatar
    Pascal Kosak committed
            this.telegram.on('message', this.supplyValue.bind(this));
        }
    
        private lower = parseInt('aaaaaaa', 36);
        private upper = parseInt('zzzzzzzz', 36);
    
        private generateSlug() {
            return Math.floor(
                Math.random() * (this.upper - this.lower) + this.lower,
            ).toString(36);
        }
    
    
        async private(msg: Message, match: RegExpMatchArray) {
            this.commitMessage(msg.from.id, true, msg);
        }
    
        async public(msg: Message, match: RegExpMatchArray) {
            this.commitMessage(msg.from.id, false, msg);
        }
    
    
        async clear(msg: Message, match: RegExpMatchArray) {
            this.messageCache.delete(msg.from.id);
    
            return void (await this.telegram.sendMessage(
    
    Pascal Kosak's avatar
    Pascal Kosak committed
                msg.chat.id,
    
    Pascal Kosak's avatar
    Pascal Kosak committed
        }
    
    
        async commitMessage(id: number, isPrivate: boolean, msg: Message) {
            if (!(await this.isRegistered(msg.from.id)))
    
    Pascal Kosak's avatar
    Pascal Kosak committed
                return void (await this.telegram.sendMessage(
                    msg.chat.id,
    
    Pascal Kosak's avatar
    Pascal Kosak committed
                ));
    
    
            if (!this.messageCache.has(id))
    
    Pascal Kosak's avatar
    Pascal Kosak committed
                return void (await this.telegram.sendMessage(
                    msg.chat.id,
    
    Pascal Kosak's avatar
    Pascal Kosak committed
                ));
    
    
            const entry = this.messageCache.get(msg.from.id);
    
            entry.private = isPrivate;
    
            this.messageCache.delete(msg.from.id);
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
            await this.prismaService.entry.create({
    
    Pascal Kosak's avatar
    Pascal Kosak committed
            });
    
    
            // TODO: Send a notification to subscriptions
        }
    
        async start(msg: Message, match: RegExpMatchArray) {
            await this.telegram.sendMessage(
                msg.chat.id,
                `/register [Name]\n/state\n/unregister`,
            );
    
    Pascal Kosak's avatar
    Pascal Kosak committed
        }
    
        async register(msg: Message, match: RegExpMatchArray) {
            if (!match[1])
                return void (await this.telegram.sendMessage(
                    msg.chat.id,
                    'Invalid name format',
                ));
    
            if (await this.isRegistered(msg.from.id))
                return void (await this.telegram.sendMessage(
                    msg.chat.id,
                    'Already registered',
                ));
    
            const agent = await this.prismaService.agent.create({
                data: {
                    uid: String(msg.from.id),
                    name: match[1],
                    slug: this.generateSlug(),
                },
            });
    
            await this.telegram.sendMessage(
                msg.chat.id,
                `Id: ${agent.id}\nName: ${agent.name}\nCode: ${agent.slug}`,
            );
        }
    
        async unregister(msg: Message, match: RegExpMatchArray) {
            if (!(await this.isRegistered(msg.from.id)))
                return void (await this.telegram.sendMessage(
                    msg.chat.id,
                    'Not registered!',
                ));
    
            const agent = await this.prismaService.agent.findFirst({
                where: { uid: String(msg.from.id) },
            });
    
            await this.prismaService.entry.deleteMany({
                where: { agentId: agent.id },
            });
    
    
            await this.prismaService.entry.deleteMany({
    
    Pascal Kosak's avatar
    Pascal Kosak committed
                where: { agentId: agent.id },
            });
    
            await this.prismaService.agent.delete({
                where: { id: agent.id },
            });
    
            await this.telegram.sendMessage(
                msg.chat.id,
                'Successfully deleted all Entries',
            );
        }
    
        async state(msg: Message, match: RegExpMatchArray) {
            if (!(await this.isRegistered(msg.from.id)))
                return void (await this.telegram.sendMessage(
                    msg.chat.id,
                    'Not registered!',
                ));
    
            const agent = await this.prismaService.agent.findFirst({
                where: { uid: String(msg.from.id) },
            });
    
    
            const publicEntries = await this.prismaService.entry.count({
                where: { agentId: agent.id, private: false },
    
    Pascal Kosak's avatar
    Pascal Kosak committed
            });
    
    
            const privateEntries = await this.prismaService.entry.count({
                where: { agentId: agent.id, private: true },
    
    Pascal Kosak's avatar
    Pascal Kosak committed
            });
    
            await this.telegram.sendMessage(
                msg.chat.id,
    
                `Id: ${agent.id}\nName: ${agent.name}\nCode: ${agent.slug}\nPublic Entries: ${publicEntries}\nPrivate Entries: ${privateEntries}`,
    
        async receiveImage(msg: Message): Promise<Partial<Entry>> {
            let file;
            let size = -1;
    
            for (const p of msg.photo) {
                if (p.width > size) {
                    size = p.width;
                    file = p.file_id;
                }
            }
    
            const id = uuid();
    
            const dest = fs.createWriteStream(
                path.join(process.cwd(), 'photos', `${id}.jpg`),
            );
            const pipe = this.telegram.getFileStream(file).pipe(dest);
    
            await new Promise((resolve) => pipe.on('finish', resolve));
    
            return {
                image: `${id}.jpg`,
            };
        }
    
    
    Pascal Kosak's avatar
    Pascal Kosak committed
        async supplyValue(msg: Message, metadata: Metadata) {
            if (metadata.type === 'text' && msg.text.startsWith('/')) return;
    
            if (!(await this.isRegistered(msg.from.id))) return;
    
            const agent = await this.prismaService.agent.findFirst({
                where: { uid: String(msg.from.id) },
            });
    
    
            let entry: Partial<Entry> = {};
            if (this.messageCache.has(msg.from.id))
                entry = this.messageCache.get(msg.from.id);
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
    
            if (metadata.type === 'photo') {
                const imageEntry = await this.receiveImage(msg);
                
                if (entry.image)
                    await this.telegram.sendMessage(
                        msg.chat.id,
                        'Overwriting previous image',
                    );
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
    
                entry.image = imageEntry.image;
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
    
                await this.telegram.sendMessage(
    
    Pascal Kosak's avatar
    Pascal Kosak committed
                    msg.chat.id,
    
    Pascal Kosak's avatar
    Pascal Kosak committed
            } else if (metadata.type === 'text') {
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
    
                await this.telegram.sendMessage(
    
    Pascal Kosak's avatar
    Pascal Kosak committed
                    msg.chat.id,
    
    Pascal Kosak's avatar
    Pascal Kosak committed
            } else if (metadata.type === 'location') {
    
                entry.lat = msg.location.latitude.toString();
                entry.lon = msg.location.longitude.toString();
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
    
                await this.telegram.sendMessage(
    
    Pascal Kosak's avatar
    Pascal Kosak committed
                    msg.chat.id,
    
    Pascal Kosak's avatar
    Pascal Kosak committed
            } else {
                return void (await this.telegram.sendMessage(
                    msg.chat.id,
                    'Unsupported DataType',
                ));
    
    Pascal Kosak's avatar
    Pascal Kosak committed
            }
    
    
            this.messageCache.set(msg.from.id, entry);
    
    Pascal Kosak's avatar
    Pascal Kosak committed
        }
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    
        private async isRegistered(uid: string | number): Promise<boolean> {
            return (
                (await this.prismaService.agent.count({
                    where: { uid: String(uid) },
                })) > 0
            );
        }
    
    Pascal Kosak's avatar
    Pascal Kosak committed
    }