basic-implementation #1

Open
florent wants to merge 8 commits from basic-implementation into master
6 changed files with 328 additions and 340 deletions
Showing only changes of commit f0afa8740d - Show all commits

View File

@ -1,7 +1,7 @@
import { Client, Message, TextChannel } from 'discord.js'; import { Client, Message, TextChannel } from "discord.js";
import { ImplementableApi } from './implementableApi'; import { ImplementableApi } from "./implementableApi";
import { once as eventsOnce } from 'events'; import { once as eventsOnce } from "events";
namespace DiscordParser { namespace DiscordParser {
export type Config = ImplementableApi.Config & { export type Config = ImplementableApi.Config & {
@ -28,7 +28,7 @@ type ChannelsType = {
ChannelPeerTube: TextChannel; ChannelPeerTube: TextChannel;
}; };
type TBaseDiscordMessageType = ('addListener' | 'newEntriesNotify') & type TBaseDiscordMessageType = ("addListener" | "newEntriesNotify") &
ImplementableApi.TBaseMessageType; ImplementableApi.TBaseMessageType;
class DiscordParser< class DiscordParser<
@ -55,16 +55,13 @@ class DiscordParser<
): Promise<DiscordParser<T>> { ): Promise<DiscordParser<T>> {
const client = new Client(); const client = new Client();
client.login(config.token); client.login(config.token);
await eventsOnce(client, 'ready'); await eventsOnce(client, "ready");
const channels: ChannelsType = { const channels: ChannelsType = {
ChannelPeerTube: this.getTextChannel( ChannelPeerTube: this.getTextChannel(
client, client,
config.channelsId.idChannelPeerTube config.channelsId.idChannelPeerTube
), ),
ChannelYtb: this.getTextChannel( ChannelYtb: this.getTextChannel(client, config.channelsId.idChannelYtb),
client,
config.channelsId.idChannelYtb
),
}; };
return new DiscordParser<T>({ return new DiscordParser<T>({
@ -78,13 +75,13 @@ class DiscordParser<
private static getTextChannel(client: Client, id: string): TextChannel { private static getTextChannel(client: Client, id: string): TextChannel {
const channel = client.channels.resolve(id); const channel = client.channels.resolve(id);
if (!channel || !(channel instanceof TextChannel)) if (!channel || !(channel instanceof TextChannel))
throw 'Bad token or bad channel id. Be careful, the channel must be a TextChannel'; throw "Bad token or bad channel id. Be careful, the channel must be a TextChannel";
amaury.joly marked this conversation as resolved Outdated
if (!resp.ChannelPeerTube || !resp.ChannelYtb) {
  throw new Error('Theres an issue concerned the channel check');
}
return {...};
```ts if (!resp.ChannelPeerTube || !resp.ChannelYtb) { throw new Error('Theres an issue concerned the channel check'); } return {...}; ```
return channel; return channel;
} }
public receivedMessage(message: ImplementableApi.Message<T>) { public receivedMessage(message: ImplementableApi.Message<T>) {
switch (message.type) { switch (message.type) {
case 'newEntriesNotify': case "newEntriesNotify":
this.sendMsgYtb( this.sendMsgYtb(
`New YouTubes entries received :\n${message.rawContent.items.map( `New YouTubes entries received :\n${message.rawContent.items.map(
(item: any) => (item: any) =>
@ -106,18 +103,17 @@ class DiscordParser<
} }
private settingEvents(): void { private settingEvents(): void {
this.client.on('message', (message: Message) => { this.client.on("message", (message: Message) => {
const resolvedChannel = this.channels; const resolvedChannel = this.channels;
let id_arr: string[] = []; let id_arr: string[] = [];
for (const key in this.channels) for (const key in this.channels) id_arr.push(resolvedChannel[key].id);
id_arr.push(resolvedChannel[key].id);
if (this.channels) if (this.channels)
if (id_arr.includes(message.channel.id)) { if (id_arr.includes(message.channel.id)) {

Je comprends pas la partie de ce code, il répond à quel cas d'utilisation ?

Sinon :

if ( Object.values(this.channels).some(channel => channel.id === message.channel.id) ) {
Je comprends pas la partie de ce code, il répond à quel cas d'utilisation ? Sinon : ```ts if ( Object.values(this.channels).some(channel => channel.id === message.channel.id) ) { ```
const msg_splitted = message.content.split(' '); const msg_splitted = message.content.split(" ");
if (msg_splitted[0] === this.botPrefix) { if (msg_splitted[0] === this.botPrefix) {
switch (msg_splitted[1]) { switch (msg_splitted[1]) {
case 'add': case "add":
const send_message: ImplementableApi.Message<TBaseDiscordMessageType> = const send_message: ImplementableApi.Message<TBaseDiscordMessageType> =
{ {
rawContent: { rawContent: {
@ -125,10 +121,10 @@ class DiscordParser<
user: message.author.toString(), user: message.author.toString(),
date: message.createdAt.toUTCString(), date: message.createdAt.toUTCString(),
}, },
type: 'addListener', type: "addListener",
}; };
message.channel.send('Ceci est un feedback'); message.channel.send("Ceci est un feedback");
this.emit('addListener', send_message); this.emit("addListener", send_message);
} }
} }
} }

View File

@ -1,4 +1,4 @@
import EventEmitter from 'events'; import EventEmitter from "events";
namespace ImplementableApi { namespace ImplementableApi {
export type Config = { export type Config = {
@ -12,7 +12,7 @@ namespace ImplementableApi {
*/ */
export type Message<T extends TBaseMessageType> = { export type Message<T extends TBaseMessageType> = {
idListener?: number; idListener?: number;
type: T | 'logging'; type: T | "logging";
rawContent: any; rawContent: any;
}; };
export type TBaseMessageType = string; export type TBaseMessageType = string;

View File

@ -1,4 +1,4 @@
// export * as Router from "./router" // export * as Router from "./router"
export {Router} from "./router" export { Router } from "./router";
export {ImplementableApi} from "./implementableApi" export { ImplementableApi } from "./implementableApi";

View File

@ -1,6 +1,6 @@
import { ImplementableApi } from './implementableApi'; import { ImplementableApi } from "./implementableApi";
import pino, { Logger } from 'pino'; import pino, { Logger } from "pino";
namespace LogWriter { namespace LogWriter {
export type Config = ImplementableApi.Config & { export type Config = ImplementableApi.Config & {
@ -24,15 +24,12 @@ class LogWriter extends ImplementableApi {
private writeMsg(message: string): void; private writeMsg(message: string): void;
private writeMsg(message: ImplementableApi.Message): void; private writeMsg(message: ImplementableApi.Message): void;
private writeMsg(message: ImplementableApi.Message | string) { private writeMsg(message: ImplementableApi.Message | string) {
if (typeof message !== 'string') if (typeof message !== "string")
message = `[${message.type}] ${ message = `[${message.type}] ${
typeof message.rawContent === 'string' typeof message.rawContent === "string"
? message.rawContent ? message.rawContent
: JSON.stringify(message.rawContent) : JSON.stringify(message.rawContent)
} ${ } ${message.idListener ?? `( listener_id : ${message.idListener} )\n`}`;
message.idListener ??
`( listener_id : ${message.idListener} )\n`
}`;
// const str = `[${new Date().toISOString()}] ${message}\n`; // const str = `[${new Date().toISOString()}] ${message}\n`;
this.logger.info(message); this.logger.info(message);

View File

@ -1,9 +1,9 @@
import { ImplementableApi } from './implementableApi'; import { ImplementableApi } from "./implementableApi";
// Api request lib // Api request lib
import fetch, { FetchError, Headers } from 'node-fetch'; import fetch, { FetchError, Headers } from "node-fetch";
import { URLSearchParams } from 'url'; import { URLSearchParams } from "url";
import FormData from 'form-data'; import FormData from "form-data";
import dedent from 'ts-dedent'; import dedent from "ts-dedent";
namespace PeerTubeRequester { namespace PeerTubeRequester {
export type Config = ImplementableApi.Config & { export type Config = ImplementableApi.Config & {
@ -22,8 +22,8 @@ type UploadInstruction = {
type ClientToken = { type ClientToken = {
client_id: string; client_id: string;
client_secret: string; client_secret: string;
grant_type: 'password'; grant_type: "password";
response_type: 'code'; response_type: "code";
username: string; username: string;
password: string; password: string;
}; };
@ -51,7 +51,7 @@ class PeerTubeRequester extends ImplementableApi {
message: ImplementableApi.Message message: ImplementableApi.Message
): Promise<void> { ): Promise<void> {
switch (message.type) { switch (message.type) {
case 'newEntriesNotify': case "newEntriesNotify":
await this.newEntriesNotify(message); await this.newEntriesNotify(message);
break; break;
default: default:
@ -63,12 +63,12 @@ class PeerTubeRequester extends ImplementableApi {
message: ImplementableApi.Message message: ImplementableApi.Message
): Promise<void> { ): Promise<void> {
// parse content // parse content
const items = message.rawContent['items']; const items = message.rawContent["items"];
if (Array.isArray(items)) if (Array.isArray(items))
for (const item of items) { for (const item of items) {
const media_group = item['media:group']; const media_group = item["media:group"];
const args: UploadInstruction = { const args: UploadInstruction = {
channelId: '848', // to do binding avec les idDeChaines Skeptikom channelId: "848", // to do binding avec les idDeChaines Skeptikom
targetUrl: item.link, targetUrl: item.link,
}; };
await this.apiRequest(args); await this.apiRequest(args);
@ -87,8 +87,8 @@ class PeerTubeRequester extends ImplementableApi {
const client_info: { [key: string]: string } = { const client_info: { [key: string]: string } = {
client_id, client_id,
client_secret, client_secret,
grant_type: 'password', grant_type: "password",
response_type: 'code', response_type: "code",
username: this.username, username: this.username,
password: this.password, password: this.password,
}; };
@ -96,13 +96,10 @@ class PeerTubeRequester extends ImplementableApi {
let myParams = new URLSearchParams(); let myParams = new URLSearchParams();
for (const key in client_info) myParams.append(key, client_info[key]); for (const key in client_info) myParams.append(key, client_info[key]);
response = await fetch( response = await fetch(`https://${this.domain_name}/api/v1/users/token`, {
`https://${this.domain_name}/api/v1/users/token`, method: "post",
{
method: 'post',
body: myParams, body: myParams,
} });
);
if (!response.ok) { if (!response.ok) {
throw new Error(response.statusText); // CRASH throw new Error(response.statusText); // CRASH
} }
@ -111,13 +108,13 @@ class PeerTubeRequester extends ImplementableApi {
// Upload // Upload
const myUploadForm = new URLSearchParams(); const myUploadForm = new URLSearchParams();
const myHeader = new Headers(); const myHeader = new Headers();
myHeader.append('Authorization', `Bearer ${access_token}`); myHeader.append("Authorization", `Bearer ${access_token}`);

Un commentaire ici, c'est compenser à mon sens un problème sémantique dans le code.

J'aurais tendance à faire deux fonctions privées this.authenticate() et this.upload()

Un commentaire ici, c'est compenser à mon sens un problème sémantique dans le code. J'aurais tendance à faire deux fonctions privées `this.authenticate()` et `this.upload()`
for (const key in message) myUploadForm.append(key, message[key]); for (const key in message) myUploadForm.append(key, message[key]);
response = await fetch( response = await fetch(
`https://${this.domain_name}/api/v1/videos/imports`, `https://${this.domain_name}/api/v1/videos/imports`,
{ {
method: 'post', method: "post",
headers: myHeader, headers: myHeader,
body: myUploadForm, body: myUploadForm,
} }

View File

@ -1,11 +1,11 @@
import { ImplementableApi } from './implementableApi'; import { ImplementableApi } from "./implementableApi";
import EventEmitter from 'events'; import EventEmitter from "events";
namespace Router { namespace Router {
export type EventsType = { export type EventsType = {
name: string; name: string;
type: 'emit' | 'received'; type: "emit" | "received";
}; };
export type InternalConfig = { export type InternalConfig = {
events: EventsType[]; events: EventsType[];
@ -32,17 +32,15 @@ class Router<
this.receivedMessage({ this.receivedMessage({
rawContent: `The dependency \`${api.name}\` was well injected into the router`, rawContent: `The dependency \`${api.name}\` was well injected into the router`,
type: 'logging', type: "logging",
}); });
} }
private setEvents(api: ImplementableApi<MessageType>) { private setEvents(api: ImplementableApi<MessageType>) {
for (const event of this.events.filter( for (const event of this.events.filter((ev) => ev.type === "received")) {
(ev) => ev.type === 'received'
)) {
api.on(event.name, (obj: ImplementableApi.Message<MessageType>) => { api.on(event.name, (obj: ImplementableApi.Message<MessageType>) => {
this.receivedMessage({ this.receivedMessage({
type: 'logging', type: "logging",
rawContent: `A message of type \`${obj.type}\` was emited by \`${api.name}\` with the event \`${event.name}\``, rawContent: `A message of type \`${obj.type}\` was emited by \`${api.name}\` with the event \`${event.name}\``,
}); });
this.emit(event.name, obj); this.emit(event.name, obj);
@ -53,7 +51,7 @@ class Router<
public receivedMessage(message: ImplementableApi.Message<MessageType>) { public receivedMessage(message: ImplementableApi.Message<MessageType>) {
this.redirectMessage({ this.redirectMessage({
rawContent: `A message of type \`${message.type}\` was received`, rawContent: `A message of type \`${message.type}\` was received`,
type: 'logging', type: "logging",
}); });
this.redirectMessage(message); this.redirectMessage(message);
} }