Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,5 @@ lerna-debug.log*

# env
.env

/file-storage
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,15 @@
"@nestjs/config": "^2.2.0",
"@nestjs/core": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"ellipsize": "^0.5.1",
"eslint-import-resolver-typescript": "^3.2.5",
"joi": "^17.6.0",
"lodash": "^4.17.21",
"markdown-escape": "^1.1.0",
"nestjs-telegraf": "^2.5.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rss-parser": "^3.12.0",
"rxjs": "^7.2.0",
"telegraf": "^4.8.5"
},
Expand All @@ -43,13 +46,15 @@
"@nestjs/testing": "^9.0.0",
"@types/express": "^4.17.13",
"@types/jest": "28.1.4",
"@types/lodash": "^4.14.182",
"@types/node": "^16.0.0",
"@types/supertest": "^2.0.11",
"eslint-import-resolver-typescript": "^3.2.5",
"@types/ellipsize": "^0.1.1",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-import-resolver-typescript": "^3.2.5",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-prettier": "^4.0.0",
"husky": "^8.0.0",
Expand Down
3 changes: 1 addition & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import { Module } from '@nestjs/common';
import { BotModule } from './bot/bot.module';
import { ChannelModule } from './channel/channel.module';
import { CoreModule } from './core/core.module';
import { RssModule } from './rss/rss.module';

@Module({
imports: [CoreModule, ChannelModule, BotModule, RssModule],
imports: [CoreModule, ChannelModule, BotModule],
controllers: [],
providers: [],
})
Expand Down
156 changes: 77 additions & 79 deletions src/bot/bot.update.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { Command, Ctx, Start, Update } from 'nestjs-telegraf';
import { Ctx, Start, Update } from 'nestjs-telegraf';
import { Context } from 'telegraf';

import { RssManagerService } from './../rss/rss-manager.service';

@Update()
export class BotUpdate {
constructor(private rssManager: RssManagerService) {}
// constructor() {}

@Start()
async start(@Ctx() ctx: Context) {
Expand All @@ -17,79 +15,79 @@ export class BotUpdate {
);
}

@Command('add')
async add(@Ctx() ctx: Context) {
if (!('text' in ctx.message)) {
await ctx.reply('Cannot find text in ctx');
return;
}

const [name, href, ...rest] = ctx.message.text.split(' ').slice(1);

if (!name || !href || rest.length) {
await ctx.reply('Incorrect command');
return;
}

const rssList = this.rssManager.list();

if (Object.keys(rssList).includes(name)) {
await ctx.reply('Name already exists. Choose another one');
return;
}

if (Object.values(rssList).includes(href)) {
await ctx.reply('This rss link already exists.');
return;
}

try {
await this.rssManager.add(name, href);
await ctx.reply(`Added ${name} - ${href}`);
} catch (error) {
await ctx.reply("Error occured, can't add rss link");
}
}

@Command('remove')
async remove(@Ctx() ctx: Context) {
if (!('text' in ctx.message)) {
await ctx.reply('Cannot find text in ctx');
return;
}

const [name, ...rest] = ctx.message.text.split(' ').slice(1);

if (!name || rest.length) {
await ctx.reply('Incorrect command');
return;
}

const rssList = this.rssManager.list();

if (!Object.keys(rssList).includes(name)) {
await ctx.reply("Rss link with such name doesn't exist");
return;
}

this.rssManager.remove(name);
await ctx.reply(`Removed ${name}`);
}

@Command('list')
async list(@Ctx() ctx: Context) {
const rssList = this.rssManager.list();

if (!Object.keys(rssList).length) {
await ctx.reply('Empty list');
return;
}

let formattedMessage = 'List:\n';
for (const name in rssList) {
formattedMessage += `${name}: ${rssList[name]}\n`;
}

await ctx.reply(formattedMessage);
}
// @Command('add')
// async add(@Ctx() ctx: Context) {
// if (!('text' in ctx.message)) {
// await ctx.reply('Cannot find text in ctx');
// return;
// }

// const [name, href, ...rest] = ctx.message.text.split(' ').slice(1);

// if (!name || !href || rest.length) {
// await ctx.reply('Incorrect command');
// return;
// }

// const rssList = this.rssManager.list();

// if (Object.keys(rssList).includes(name)) {
// await ctx.reply('Name already exists. Choose another one');
// return;
// }

// if (Object.values(rssList).includes(href)) {
// await ctx.reply('This rss link already exists.');
// return;
// }

// try {
// await this.rssManager.add(name, href);
// await ctx.reply(`Added ${name} - ${href}`);
// } catch (error) {
// await ctx.reply("Error occured, can't add rss link");
// }
// }

// @Command('remove')
// async remove(@Ctx() ctx: Context) {
// if (!('text' in ctx.message)) {
// await ctx.reply('Cannot find text in ctx');
// return;
// }

// const [name, ...rest] = ctx.message.text.split(' ').slice(1);

// if (!name || rest.length) {
// await ctx.reply('Incorrect command');
// return;
// }

// const rssList = this.rssManager.list();

// if (!Object.keys(rssList).includes(name)) {
// await ctx.reply("Rss link with such name doesn't exist");
// return;
// }

// this.rssManager.remove(name);
// await ctx.reply(`Removed ${name}`);
// }

// @Command('list')
// async list(@Ctx() ctx: Context) {
// const rssList = this.rssManager.list();

// if (!Object.keys(rssList).length) {
// await ctx.reply('Empty list');
// return;
// }

// let formattedMessage = 'List:\n';
// for (const name in rssList) {
// formattedMessage += `${name}: ${rssList[name]}\n`;
// }

// await ctx.reply(formattedMessage);
// }
}
2 changes: 2 additions & 0 deletions src/channel/channel.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Module } from '@nestjs/common';

import { RssModule } from 'src/rss/rss.module';
import { ChannelService } from './channel.service';

@Module({
imports: [RssModule],
providers: [ChannelService],
exports: [ChannelService],
})
Expand Down
31 changes: 26 additions & 5 deletions src/channel/channel.service.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,40 @@
import { Inject, Injectable } from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import mdEscape from 'markdown-escape';
import ellipsize from 'ellipsize';
import { InjectBot } from 'nestjs-telegraf';
import { concatMap, ignoreElements, startWith, timer } from 'rxjs';
import { Context, Telegraf } from 'telegraf';

import telegramConfig from 'src/config/telegram.config';
import { RssService } from './../rss/rss.service';
import { PostMessage } from './models/post-message.model';

@Injectable()
export class ChannelService {
private readonly MESSAGE_DELAY = 3500;

constructor(
@InjectBot() private bot: Telegraf<Context>,
@Inject(telegramConfig.KEY)
private tgConfig: ConfigType<typeof telegramConfig>,
) {}
private rssService: RssService,
) {
this.rssService.posts$
.pipe(
concatMap((value) =>
timer(this.MESSAGE_DELAY).pipe(ignoreElements(), startWith(value)),
),
)
.subscribe((post) => {
this.postMessage({
title: post.title,
text: ellipsize(post.contentSnippet, 500),
author: post.creator,
date: new Date(post.pubDate),
href: post.link,
});
});
}

async postMessage(post: PostMessage) {
await this.bot.telegram.sendMessage(
Expand All @@ -25,9 +46,9 @@ export class ChannelService {

private formatMessage({ title, text, author, date, href }: PostMessage) {
return (
`*${mdEscape(title)}*\n` +
`${mdEscape(text)}\n` +
`_${mdEscape(author)} - ${mdEscape(date.toUTCString())}_\n\n` +
`*${title}*\n` +
`${text}\n` +
`_${author} - ${date.toUTCString()}_\n\n` +
`${href}`
);
}
Expand Down
6 changes: 5 additions & 1 deletion src/core/core.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { Module } from '@nestjs/common';
import { Global, Module } from '@nestjs/common';
import { ConfigModule, ConfigType } from '@nestjs/config';
import * as Joi from 'joi';
import { TelegrafModule } from 'nestjs-telegraf';

import telegramConfig, {
telegramValidationSchema,
} from 'src/config/telegram.config';
import { FileStorageService } from './file-storage.service';

@Global()
@Module({
imports: [
ConfigModule.forRoot({
Expand All @@ -23,5 +25,7 @@ import telegramConfig, {
}),
}),
],
providers: [FileStorageService],
exports: [FileStorageService],
})
export class CoreModule {}
38 changes: 38 additions & 0 deletions src/core/file-storage.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import fs from 'fs';
import path from 'path';

import { Injectable } from '@nestjs/common';

@Injectable()
export class FileStorageService {
private readonly STORAGE_PATH = './file-storage';

constructor() {
if (!fs.existsSync(this.STORAGE_PATH)) {
fs.mkdirSync(this.STORAGE_PATH);
}
}

async get<T>(fileName: string): Promise<T | null> {
const pathname = path.join(this.STORAGE_PATH, `${fileName}.json`);

if (!fs.existsSync(pathname)) {
return null;
}

const fileData = await fs.promises.readFile(pathname, { encoding: 'utf8' });

return JSON.parse(fileData) as T;
}

async save<T>(fileName: string, data: T) {
const pathname = path.join(this.STORAGE_PATH, `${fileName}.json`);
const json = JSON.stringify(data);

try {
await fs.promises.writeFile(pathname, json);
} catch {
console.error(`File with "${pathname}" name wasn't saved`);
}
}
}
18 changes: 0 additions & 18 deletions src/rss/rss-manager.service.ts

This file was deleted.

6 changes: 3 additions & 3 deletions src/rss/rss.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Module } from '@nestjs/common';

import { RssManagerService } from './rss-manager.service';
import { RssService } from './rss.service';

@Module({
providers: [RssManagerService],
exports: [RssManagerService],
providers: [RssService],
exports: [RssService],
})
export class RssModule {}
Loading