Update dependencies and other stuff
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
Fabian Stamm 2023-04-12 22:18:27 +02:00
parent 1f5625877b
commit 536e75abba
12 changed files with 3343 additions and 1733 deletions

View File

@ -1,3 +0,0 @@
{
"url": "https://drone.hibas123.de/hibas123/THM_OSPLUS_NEWS_MAILER"
}

View File

@ -4,7 +4,7 @@ name: default
steps: steps:
- name: Build with node - name: Build with node
image: node:12 image: node:19
commands: commands:
- npm install - npm install
- npm run build - npm run build

4
.gitignore vendored
View File

@ -2,4 +2,6 @@ node_modules/
.env .env
logs/ logs/
db.json db.json
lib/ lib/
.yarn/cache
.yarn/install-state.gz

File diff suppressed because one or more lines are too long

873
.yarn/releases/yarn-3.5.0.cjs vendored Normal file

File diff suppressed because one or more lines are too long

9
.yarnrc.yml Normal file
View File

@ -0,0 +1,9 @@
nodeLinker: node-modules
npmRegistryServer: "https://npm.hibas123.de"
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs
spec: "@yarnpkg/plugin-interactive-tools"
yarnPath: .yarn/releases/yarn-3.5.0.cjs

View File

@ -1,4 +1,4 @@
FROM node:12 FROM node:19
LABEL maintainer="Fabian Stamm <dev@fabianstamm.de>" LABEL maintainer="Fabian Stamm <dev@fabianstamm.de>"

1509
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -5,31 +5,32 @@
"author": "Fabian Stamm <dev@fabianstamm.de>", "author": "Fabian Stamm <dev@fabianstamm.de>",
"license": "MIT", "license": "MIT",
"private": true, "private": true,
"type": "module",
"scripts": { "scripts": {
"start": "node lib/index.js", "start": "node lib/index.js",
"build": "tsc", "build": "tsc",
"watch-ts": "tsc -w", "dev": "nodemon -e ts --exec 'node --loader ts-node/esm src/index.ts'"
"watch-js": "nodemon -i db.json lib/index.js",
"watch": "concurrently npm:watch-*"
}, },
"devDependencies": { "devDependencies": {
"@types/dotenv": "^8.2.0", "@types/dotenv": "^8.2.0",
"@types/html-entities": "^1.2.16", "@types/html-entities": "^1.3.4",
"@types/lowdb": "^1.0.5", "@types/node": "^18.15.11",
"@types/node": "^13.1.4", "@types/node-fetch": "^3.0.3",
"@types/node-fetch": "^2.5.4", "nodemon": "^2.0.22",
"concurrently": "^5.0.2", "ts-node": "^10.9.1",
"nodemon": "^2.0.2", "typescript": "^5.0.4"
"typescript": "^3.7.4"
}, },
"dependencies": { "dependencies": {
"@hibas123/nodelogging": "^2.1.2", "@hibas123/nodelogging": "^3.1.3",
"dotenv": "^8.2.0", "@types/lodash": "^4.14.192",
"html-entities": "^1.2.1", "dotenv": "^16.0.3",
"lowdb": "^1.0.0", "html-entities": "^2.3.3",
"node-fetch": "^2.6.0", "lodash": "^4.17.21",
"rss-parser": "^3.7.3", "lowdb": "^5.1.0",
"ssl-root-cas": "^1.2.5", "node-fetch": "^3.3.1",
"telegraf": "^3.35.0" "rss-parser": "^3.13.0",
} "ssl-root-cas": "^1.3.1",
} "telegraf": "^4.12.2"
},
"packageManager": "yarn@3.5.0"
}

View File

@ -1,224 +1,227 @@
require('https').globalAgent.options.ca = require('ssl-root-cas/latest').create(); // require('https').globalAgent.options.ca = require('ssl-root-cas/latest').create();
require('ssl-root-cas').inject(); // require('ssl-root-cas').inject();
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
import Logging from "@hibas123/nodelogging"; import Logging from "@hibas123/nodelogging";
import { createHash } from "crypto"; import { createHash } from "crypto";
import * as dotenv from "dotenv"; import * as dotenv from "dotenv";
import { AllHtmlEntities } from "html-entities"; import { decode } from "html-entities";
import low from "lowdb";
import FileSync from "lowdb/adapters/FileSync";
import fetch from "node-fetch"; import fetch from "node-fetch";
import rss from "rss-parser"; import rss from "rss-parser";
import Telegraf from "telegraf"; import { Telegraf } from "telegraf";
import { message } from "telegraf/filters";
import * as fs from "fs"; import * as fs from "fs";
import lodash from 'lodash'
dotenv.config();
const parser = new rss();
const entities = new AllHtmlEntities();
if (!fs.existsSync("./persist")) { Promise.resolve().then(async () => {
fs.mkdirSync("./persist") const { Low, LowSync } = await import("lowdb");
} // @ts-ignore
const { JSONFileSync } = await import("lowdb/node") as any;
const adapter = new FileSync<{ feeds: IDBFeed[] }>("persist/db.json"); class LowWithLodash<T> extends LowSync<T> {
const db = low(adapter); chain: lodash.ExpChain<this['data']> = lodash.chain(this).get('data')
db.defaults({ feeds: [] }).write(); }
interface IDBFeed { dotenv.config();
url: string; const parser = new rss();
subscriber: number[]; // const entities = new AllHtmlEntities();
oldEntries: string[];
}
class Database { if (!fs.existsSync("./persist")) {
static findFeed(url: string): DBFeed { fs.mkdirSync("./persist")
const feed = db.get("feeds").find(e => e.url === url).value(); }
return feed ? new DBFeed(feed) : undefined;
// @ts-ignore
const adapter = new JSONFileSync<{ feeds: IDBFeed[] }>("persist/db.json");
const db: any = new LowWithLodash(adapter);
db.read();
db.chain.defaults({ feeds: [] });
db.write();
interface IDBFeed {
url: string;
subscriber: number[];
oldEntries: string[];
}
class Database {
static findFeed(url: string): DBFeed {
const feed = db.chain.get("feeds").find(e => e.url === url).value();
return feed ? new DBFeed(feed) : undefined;
}
static addFeed(url: string): IDBFeed {
const feed = {
url: url,
oldEntries: [],
subscriber: []
};
db.chain.get("feeds").unshift(feed)
db.write();
return feed;
}
static addSubscriber(url: string, chatid: number) {
const feed = this.findFeed(url);
if (!feed)
this.addFeed(url);
else {
if (feed.subscriber.some(e => e === chatid)) {
return;
}
}
db.chain.get("feeds").find(e => e.url === url).get("subscriber").push(chatid)
db.write();
}
static findSubscribed(chatid: number) {
return db.chain.get("feeds").filter(e => e.subscriber.indexOf(chatid) >= 0).value();
}
static removeSubscriber(url: string, chatid: number) {
db.chain.get("feeds").find(e => e.url === url).get("subscriber").remove(e => e === chatid)
db.write();
}
static addItems(url: string, hashes: string[]) {
db.chain.get("feeds").find(e => e.url === url).get("oldEntries").unshift(...hashes)
db.write();
}
static getAll() {
return db.chain.get("feeds").map(feed => new DBFeed(feed)).value();
}
} }
static addFeed(url: string): IDBFeed { class DBFeed implements IDBFeed {
const feed = { url: string;
url: url, subscriber: number[];
oldEntries: [], oldEntries: string[];
subscriber: []
};
db.get("feeds").unshift(feed).write();
return feed;
}
static addSubscriber(url: string, chatid: number) { constructor(dbobject?: IDBFeed) {
const feed = this.findFeed(url); if (dbobject) {
if (!feed) for (let key in dbobject)
this.addFeed(url); this[key] = dbobject[key];
else {
if (feed.subscriber.some(e => e === chatid)) {
return;
} }
} }
db.get("feeds").find(e => e.url === url).get("subscriber").push(chatid).write();
}
static findSubscribed(chatid: number) { itemExists(item: IFeedItem): boolean {
return db.get("feeds").filter(e => e.subscriber.indexOf(chatid) >= 0).value(); const hash = calculateHash(item);
} return !!this.oldEntries.find(e => e === hash);
}
static removeSubscriber(url: string, chatid: number) { addItems(items: IFeedItem[]) {
db.get("feeds").find(e => e.url === url).get("subscriber").remove(e => e === chatid).write(); Database.addItems(this.url, items.map(item => calculateHash(item)));
}
static addItems(url: string, hashes: string[]) {
db.get("feeds").find(e => e.url === url).get("oldEntries").unshift(...hashes).write();
}
static getAll() {
return db.get("feeds").map(feed => new DBFeed(feed)).value();
}
}
class DBFeed implements IDBFeed {
url: string;
subscriber: number[];
oldEntries: string[];
constructor(dbobject?: IDBFeed) {
if (dbobject) {
for (let key in dbobject)
this[key] = dbobject[key];
} }
} }
itemExists(item: IFeedItem): boolean {
const hash = calculateHash(item); interface Feed {
return !!this.oldEntries.find(e => e === hash); title: string;
language: string;
description: string;
copyright: string;
items: IFeedItem[];
} }
addItems(items: IFeedItem[]) { interface IFeedItem {
Database.addItems(this.url, items.map(item => calculateHash(item))); title: string;
link: string;
content: string,
contentSnippet: string;
guid: string;
}
function calculateHash(item: IFeedItem) {
let hash = createHash("sha512");
if (item.content)
hash.update(item.content);
if (item.guid)
hash.update(item.guid);
if (item.title)
hash.update(item.title);
if (item.link)
hash.update(item.link);
if (item.contentSnippet)
hash.update(item.contentSnippet);
return hash.digest("hex");
}
async function checkFeed(feed: DBFeed) {
Logging.log("Fetching:", feed.url);
let data = await fetch(feed.url).then(res => res.text());
Logging.log("Received Data");
let feedData = await parser.parseString(data).catch(err => Logging.error(err)) as Feed;
// Check for new items
Logging.debug(feedData.items.length, feedData.items.map(e => calculateHash(e)));
const newItems = feedData.items.filter(item => !feed.itemExists(item));
// Sending notifications
await sendFeedTelegraf(feed, newItems);
feed.addItems(newItems);
} }
}
interface Feed { const bot = new Telegraf(process.env.TG_TOKEN)
title: string;
language: string;
description: string;
copyright: string;
items: IFeedItem[]; bot.start(async ctx => {
} await ctx.reply("Send some RSS Feed URLs to get started.");
})
interface IFeedItem { bot.command("list", async (ctx) => {
title: string; const chatid = ctx.chat.id;
link: string; const feeds = Database.findSubscribed(chatid).map(feed => feed.url).join("\n");
content: string, await ctx.reply("You are currently subscribed to: \n" + feeds);
contentSnippet: string; })
guid: string;
}
function calculateHash(item: IFeedItem) { bot.on(message("text", "entities"), async ctx => {
let hash = createHash("sha512"); const chatid = ctx.chat.id;
if (item.content) Logging.debug("Message From:", chatid, ctx.message);
hash.update(item.content);
if (item.guid)
hash.update(item.guid);
if (item.title)
hash.update(item.title);
if (item.link)
hash.update(item.link);
if (item.contentSnippet)
hash.update(item.contentSnippet);
return hash.digest("hex");
}
async function checkFeed(feed: DBFeed) { const urls = ctx.message.entities.filter(e => e.type === "url").map(e => ctx.message.text.substr(e.offset, e.length));
Logging.log("Fetching:", feed.url); await Promise.all(urls.map(async url => {
let data = await fetch(feed.url).then(res => res.text()); Database.addSubscriber(url, chatid);
Logging.log("Received Data"); await ctx.reply("Subscribed to: " + url);
let feed = Database.findFeed(url)
if (feed)
checkFeed(feed);
else
Logging.error("Cannot find created feed!")
}))
if (urls.length === 0)
await ctx.reply("No URLs found in message.");
})
let feedData = await parser.parseString(data).catch(err => Logging.error(err)) as Feed; bot.launch()
// Check for new items async function sendFeedTelegraf(feed: DBFeed, items: IFeedItem[]) {
Logging.debug(feedData.items.length, feedData.items.map(e => calculateHash(e))); Logging.debug("Before send", feed, items);
const newItems = feedData.items.filter(item => !feed.itemExists(item)); await Promise.all(feed.subscriber.map(
subscriber => Promise.all(
// Sending notifications items.map(
await sendFeedTelegraf(feed, newItems); item => bot.telegram.sendMessage(
subscriber,
feed.addItems(newItems); item.guid + "\n" + decode(item.title) + "\n\n" + decode(item.contentSnippet)
} ).catch(err => Logging.error(err)).then(() => Logging.debug("Message Sent"))
)
const bot = new Telegraf(process.env.TG_TOKEN)
bot.start(async ctx => {
await ctx.reply("Send some RSS Feed URLs to get started.");
})
bot.command("list", async (ctx) => {
const chatid = ctx.chat.id;
const feeds = Database.findSubscribed(chatid).map(feed => feed.url).join("\n");
await ctx.reply("You are currently subscribed to: \n" + feeds);
})
bot.on("message", async ctx => {
const chatid = ctx.chat.id;
Logging.debug("Message From:", chatid, ctx.message);
const urls = ctx.message.entities.filter(e => e.type === "url").map(e => ctx.message.text.substr(e.offset, e.length));
await Promise.all(urls.map(async url => {
Database.addSubscriber(url, chatid);
await ctx.reply("Subscribed to: " + url);
let feed = Database.findFeed(url)
if (feed)
checkFeed(feed);
else
Logging.error("Cannot find created feed!")
}))
})
bot.startPolling();
async function sendFeedTelegraf(feed: DBFeed, items: IFeedItem[]) {
Logging.debug("Before send", feed, items);
await Promise.all(feed.subscriber.map(
subscriber => Promise.all(
items.map(
item => bot.telegram.sendMessage(
subscriber,
item.guid + "\n" + entities.decode(item.title) + "\n\n" + entities.decode(item.contentSnippet)
).catch(err => Logging.error(err)).then(() => Logging.debug("Message Sent"))
) )
) ));
)); }
}
function checkAll() { function checkAll() {
Database.getAll().map(feed => checkFeed(feed).catch(err => Logging.error(err))); Database.getAll().map(feed => checkFeed(feed).catch(err => Logging.error(err)));
} }
setInterval(() => { setInterval(() => {
checkAll();
}, 1000 * 60 * 60);
checkAll(); checkAll();
}, 1000 * 60 * 60); })
checkAll();
// import { AllHtmlEntities } from "html-entities";
// import { fstat } from "fs";
// const entities = new AllHtmlEntities();
// async function sendFeedMail(feed: Feed, item: IFeedItem) {
// Logging.log("Sending Mail!")
// let mailOptions = {
// from: process.env.MAIL_SENDER,
// to: process.env.MAIL_RECEIVER,
// subject: '[OSPLUS_UPDATE] ' + entities.decode(item.title),
// text: entities.decode(item.contentSnippet),
// html: item.content
// };
// let info = await transporter.sendMail(mailOptions);
// Logging.log('Message sent: %s', info.messageId);
// db.set(calculateHash(item), true).write();
// }

View File

@ -1,14 +1,14 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "es2017", "target": "ESNext",
"module": "commonjs", "module": "ESNext",
"moduleResolution": "node", "moduleResolution": "node",
"outDir": "./lib", "outDir": "./lib",
"strict": false, "strict": false,
"esModuleInterop": true, "esModuleInterop": true,
"preserveWatchOutput": true "preserveWatchOutput": true,
}, "forceConsistentCasingInFileNames": true
"include": [ },
"./src" "include": ["./src"],
] "exclude": ["node_modules"]
} }

1693
yarn.lock Normal file

File diff suppressed because it is too large Load Diff