import GelbooruServiceResponse from "../types/GelbooruServiceResponse"; import Image from "../types/Image"; import BotApiService from "./BotApiService"; import GelbooruApiService from "./GelbooruApiService"; class ImageService { postsQueue: Image[] = []; async get(): Promise { while (this.postsQueue.length === 0) { const validPosts = await this.getNewValidImages(); this.postsQueue = validPosts; } return this.postsQueue.pop() as Image; } private async getNewValidImages(): Promise { const gelbooruResponse: GelbooruServiceResponse = await GelbooruApiService.get(); const posts = gelbooruResponse.posts; const botResponse = await BotApiService.getAll(); const imagesUrls = botResponse.images.map(image => image.url); const validPosts = Promise.all(posts .filter(post => !imagesUrls.some(url => url === post.url)) .map(async (post): Promise => { const imageData = await this.urlToImageData(post.url); const encodedImage = this.imageToBase64(imageData); return { url: post.url, tags: post.tags, content: encodedImage }; })); return validPosts; } private async urlToImageData(url: string): Promise { return await (await fetch(url)).text(); } private imageToBase64(imageData: string): string { return Buffer.from(imageData, "binary").toString("base64"); } } export default new ImageService();