Skip to content

Commit

Permalink
async sevices
Browse files Browse the repository at this point in the history
  • Loading branch information
Feverqwe committed Jul 27, 2023
1 parent c7ce1d5 commit ab8e642
Show file tree
Hide file tree
Showing 8 changed files with 408 additions and 407 deletions.
4 changes: 2 additions & 2 deletions src/chatSender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import {ChatModel, MessageModel, StreamModelWithChannel} from './db';
import {getDebug} from './tools/getDebug';
import TelegramBot from 'node-telegram-bot-api';
import {tracker} from './tracker';
import ReadableStream = NodeJS.ReadableStream;
import {ErrEnum, errHandler, passEx} from './tools/passTgEx';
import {TelegramError} from "./types";
import {TelegramError} from './types';
import ReadableStream = NodeJS.ReadableStream;

const debug = getDebug('app:ChatSender');

Expand Down
2 changes: 1 addition & 1 deletion src/locale/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ const en = {
'alert_unknown-error': 'Oops something went wrong...',
'alert_chat-not-found': 'Telegram chat is not found!',
'alert_bot-is-not-channel-member': 'Bot is not a member of the channel!',
'context_options': 'Options:'
context_options: 'Options:',
};

export default en;
7 changes: 2 additions & 5 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import Events from 'events';
import {appConfig} from './appConfig';
import {getDebug} from './tools/getDebug';
import {getTelegramBot, TelegramBotWrapped} from './tools/telegramBotApi';
import WebServer from "./webServer";
import WebServer from './webServer';

const debug = getDebug('app:Main');

Expand Down Expand Up @@ -59,10 +59,7 @@ class Main extends Events {

async init() {
await this.db.init();
await Promise.all([
this.webServer.init(),
this.chat.init(),
]);
await Promise.all([this.webServer.init(), this.chat.init()]);
this.checker.init();
this.sender.init();
}
Expand Down
2 changes: 1 addition & 1 deletion src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import qs from 'node:querystring';
import TelegramBot from 'node-telegram-bot-api';
import {getDebug} from './tools/getDebug';
import Locale from './locale';
import {TelegramBotWrapped} from "./tools/telegramBotApi";
import {TelegramBotWrapped} from './tools/telegramBotApi';

const debug = getDebug('app:router');

Expand Down
206 changes: 105 additions & 101 deletions src/services/goodgame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,129 +57,133 @@ class Goodgame implements ServiceInterface {
return [/goodgame\.ru\//i].some((re) => re.test(url));
}

getStreams(channelIds: number[]) {
async getStreams(channelIds: number[]) {
const resultStreams: ServiceStream[] = [];
const skippedChannelIds: number[] = [];
const removedChannelIds: number[] = [];
return parallel(10, arrayByPart(channelIds, 25), (channelIds) => {
return fetchRequest('https://api2.goodgame.ru/v2/streams', {
searchParams: {
ids: channelIds.join(','),
adult: true,
hidden: true,
},
headers: {
Accept: 'application/vnd.goodgame.v2+json',
},
keepAlive: true,
responseType: 'json',
})
.then(({body}) => {
const streams = s.mask(body, StreamsStruct)._embedded.streams;

streams.forEach((stream) => {
if (stream.status !== 'Live') return;

let gameTitle = null;
stream.channel.games.some((game) => {
if (game.title) {
gameTitle = game.title;
return true;
}
});

const previews = [];
let thumb = stream.channel.thumb.replace(/_240(\.jpg)$/, '$1');
if (/^\/\//.test(thumb)) {
thumb = 'https:' + thumb;
}
if (thumb) {
previews.push(thumb);
}
await parallel(10, arrayByPart(channelIds, 25), async (channelIds) => {
try {
const {body} = await fetchRequest('https://api2.goodgame.ru/v2/streams', {
searchParams: {
ids: channelIds.join(','),
adult: true,
hidden: true,
},
headers: {
Accept: 'application/vnd.goodgame.v2+json',
},
keepAlive: true,
responseType: 'json',
});

const streams = s.mask(body, StreamsStruct)._embedded.streams;

let viewers: null | number = parseInt(stream.viewers, 10);
if (!isFinite(viewers)) {
viewers = null;
streams.forEach((stream) => {
if (stream.status !== 'Live') return;

let gameTitle = null;
stream.channel.games.some((game) => {
if (game.title) {
gameTitle = game.title;
return true;
}
});

resultStreams.push({
id: stream.id,
url: stream.channel.url,
title: stream.channel.title,
game: gameTitle,
isRecord: false,
previews: previews,
viewers: viewers,
channelId: stream.channel.id,
channelTitle: stream.channel.key,
channelUrl: stream.channel.url,
});
const previews = [];
let thumb = stream.channel.thumb.replace(/_240(\.jpg)$/, '$1');
if (/^\/\//.test(thumb)) {
thumb = 'https:' + thumb;
}
if (thumb) {
previews.push(thumb);
}

let viewers: null | number = parseInt(stream.viewers, 10);
if (!isFinite(viewers)) {
viewers = null;
}

resultStreams.push({
id: stream.id,
url: stream.channel.url,
title: stream.channel.title,
game: gameTitle,
isRecord: false,
previews: previews,
viewers: viewers,
channelId: stream.channel.id,
channelTitle: stream.channel.key,
channelUrl: stream.channel.url,
});
})
.catch((err: any) => {
debug(`getStreams for channels (%j) skip, cause: %o`, channelIds, err);
skippedChannelIds.push(...channelIds);
});
}).then(() => {
return {streams: resultStreams, skippedChannelIds, removedChannelIds};
} catch (err) {
debug(`getStreams for channels (%j) skip, cause: %o`, channelIds, err);
skippedChannelIds.push(...channelIds);
}
});
return {streams: resultStreams, skippedChannelIds, removedChannelIds};
}

getExistsChannelIds(ids: number[]) {
async getExistsChannelIds(ids: number[]) {
const resultChannelIds: number[] = [];
return parallel(10, ids, (channelId) => {
return this.requestChannelById(channelId).then(
() => {
await parallel(10, ids, async (channelId) => {
try {
await this.requestChannelById(channelId);
resultChannelIds.push(channelId);
} catch (error) {
const err = error as ErrorWithCode;
if (err.code === 'CHANNEL_BY_ID_IS_NOT_FOUND') {
// pass
} else {
debug('requestChannelById (%s) error: %o', channelId, err);
resultChannelIds.push(channelId);
},
(err: any) => {
if (err.code === 'CHANNEL_BY_ID_IS_NOT_FOUND') {
// pass
} else {
debug('requestChannelById (%s) error: %o', channelId, err);
resultChannelIds.push(channelId);
}
},
);
}).then(() => resultChannelIds);
}
}
});
return resultChannelIds;
}

findChannel(query: string) {
return this.getChannelIdByUrl(query)
.catch((err) => {
async findChannel(query: string) {
const channelIdOrQuery = await (async () => {
try {
return await this.getChannelIdByUrl(query);
} catch (error) {
const err = error as ErrorWithCode;
if (err.code === 'IS_NOT_CHANNEL_URL') {
// pass
return query;
}
throw err;
})
.then((query) => {
return this.requestChannelById(query);
});
}
})();
return this.requestChannelById(channelIdOrQuery);
}

requestChannelById(channelId: string | number) {
return fetchRequest('https://api2.goodgame.ru/v2/streams/' + encodeURIComponent(channelId), {
headers: {
Accept: 'application/vnd.goodgame.v2+json',
},
keepAlive: true,
responseType: 'json',
}).then(
({body}) => {
const stream = s.mask(body, StreamStrict);
const id = stream.channel.id;
const url = stream.channel.url;
const title = stream.channel.key;
return {id, title, url};
},
(err: HTTPError) => {
if (err.name === 'HTTPError' && err.response.statusCode === 404) {
throw new ErrorWithCode('Channel by id is not found', 'CHANNEL_BY_ID_IS_NOT_FOUND');
}
throw err;
},
);
async requestChannelById(channelId: string | number) {
try {
const {body} = await fetchRequest(
'https://api2.goodgame.ru/v2/streams/' + encodeURIComponent(channelId),
{
headers: {
Accept: 'application/vnd.goodgame.v2+json',
},
keepAlive: true,
responseType: 'json',
},
);

const stream = s.mask(body, StreamStrict);
const id = stream.channel.id;
const url = stream.channel.url;
const title = stream.channel.key;
return {id, title, url};
} catch (error) {
const err = error as HTTPError;
if (err.name === 'HTTPError' && err.response.statusCode === 404) {
throw new ErrorWithCode('Channel by id is not found', 'CHANNEL_BY_ID_IS_NOT_FOUND');
}
throw err;
}
}

async getChannelIdByUrl(url: string) {
Expand Down
Loading

0 comments on commit ab8e642

Please sign in to comment.