|
| 1 | +import { MessageMedia } from "whatsapp-web.js"; |
| 2 | +import fs from "fs"; |
| 3 | +import path from "path"; |
| 4 | +import { Innertube, UniversalCache, Utils } from "youtubei.js"; |
| 5 | +import log from "../log"; |
| 6 | +import { Video } from "./downloader"; |
| 7 | + |
| 8 | +const fileExists = async (filePath: string) => { |
| 9 | + try { |
| 10 | + await fs.promises.access(filePath, fs.constants.F_OK); |
| 11 | + return true; |
| 12 | + } catch { |
| 13 | + return false; |
| 14 | + } |
| 15 | +}; |
| 16 | + |
| 17 | +export async function YoutubeShortsInstantDownloader( |
| 18 | + query: string, |
| 19 | +): Promise<Video | undefined> { |
| 20 | + const yt = await Innertube.create({ |
| 21 | + cache: new UniversalCache(false), |
| 22 | + generate_session_locally: true, |
| 23 | + player_id: "0004de42", |
| 24 | + }); |
| 25 | + |
| 26 | + const endpoint = await yt.resolveURL(query); |
| 27 | + const videoId = endpoint.payload.videoId; |
| 28 | + if (!videoId) return undefined; |
| 29 | + |
| 30 | + const tempDir = "./.temp"; |
| 31 | + await fs.promises.mkdir(tempDir, { recursive: true }); |
| 32 | + const tempPath = path.join(tempDir, `${videoId}.mp4`); |
| 33 | + |
| 34 | + if (await fileExists(tempPath)) { |
| 35 | + return { |
| 36 | + video: MessageMedia.fromFilePath(tempPath), |
| 37 | + title: undefined, |
| 38 | + }; |
| 39 | + } |
| 40 | + |
| 41 | + const stream = await yt.download(videoId, { |
| 42 | + type: "video+audio", |
| 43 | + quality: "best", |
| 44 | + format: "mp4", |
| 45 | + }); |
| 46 | + |
| 47 | + if (!stream) return undefined; |
| 48 | + |
| 49 | + let writeStream = fs.createWriteStream(tempPath); |
| 50 | + |
| 51 | + for await (const chunk of Utils.streamToIterable(stream)) { |
| 52 | + writeStream.write(chunk); |
| 53 | + } |
| 54 | + |
| 55 | + await new Promise<void>((resolve, reject) => { |
| 56 | + writeStream.end(); |
| 57 | + writeStream.on("finish", resolve); |
| 58 | + writeStream.on("error", reject); |
| 59 | + }); |
| 60 | + |
| 61 | + return { |
| 62 | + video: MessageMedia.fromFilePath(tempPath), |
| 63 | + title: undefined, |
| 64 | + }; |
| 65 | +} |
0 commit comments