Update downloading

This commit is contained in:
2022-01-09 21:51:33 +03:00
parent e0aebeaf24
commit a0f855b10b
3 changed files with 29 additions and 2 deletions

View File

@@ -1,7 +1,7 @@
import { Context } from 'telegraf';
import * as BookLibrary from "../services/book_library";
import { clearBookCache, getBookCache } from '../services/book_cache';
import { clearBookCache, getBookCache, downloadFromCache } from '../services/book_cache';
import { getBookCacheBuffer } from '../services/book_cache_buffer';
import { download } from '../services/downloader';
import { BotState, Cache } from '@/bots/manager';
@@ -14,6 +14,11 @@ async function _sendFile(ctx: Context, state: BotState, chatId: number, id: numb
await ctx.telegram.sendDocument(chatId, data)
}
const sendWithDownloadFromChannel = async () => {
const data = await downloadFromCache(id, format);
await ctx.telegram.sendDocument(chatId, data);
}
const getCachedMessage = async () => {
if (state.cache === Cache.ORIGINAL) {
return getBookCache(id, format);
@@ -30,7 +35,11 @@ async function _sendFile(ctx: Context, state: BotState, chatId: number, id: numb
};
if (state.cache === Cache.NO_CACHE) {
try {
await sendWithDownloadFromChannel();
} catch (e) {
await sendWithoutCache();
}
return;
}

View File

@@ -51,3 +51,21 @@ export async function getBookCache(bookId: number, fileType: string): Promise<Ca
export async function clearBookCache(bookId: number, fileType: string): Promise<CachedMessage> {
return (await _makeDeleteRequest<BookCache>(`/api/v1/${bookId}/${fileType}`)).data;
}
export interface DownloadedFile {
source: Buffer;
filename: string;
}
export async function downloadFromCache(bookId: number, fileType: string): Promise<DownloadedFile> {
const response = await got<string>(`${env.DOWNLOADER_URL}/api/v1/download/${bookId}/${fileType}`, {
headers: {
'Authorization': env.DOWNLOADER_API_KEY,
},
});
return {
source: response.rawBody,
filename: (response.headers['content-disposition'] || '').split('filename=')[1]
}
}