diff --git a/play-dl/Request/index.ts b/play-dl/Request/index.ts index fccbe15..5e91149 100644 --- a/play-dl/Request/index.ts +++ b/play-dl/Request/index.ts @@ -136,9 +136,8 @@ export function request_resolve_redirect(url: string): Promise { resolve(url); } else if (statusCode < 400) { const resolved = await request_resolve_redirect(res.headers.location as string).catch((err) => err); - - if (res instanceof Error) { - reject(res); + if (resolved instanceof Error) { + reject(resolved); return; } @@ -149,6 +148,38 @@ export function request_resolve_redirect(url: string): Promise { }); } +export function request_content_length(url: string): Promise { + return new Promise(async (resolve, reject) => { + let res = await https_getter(url, { method: 'HEAD' }).catch((err: Error) => err); + if (res instanceof Error) { + reject(res); + return; + } + const statusCode = Number(res.statusCode); + if (statusCode < 300) { + resolve(Number(res.headers['content-length'])); + } else if (statusCode < 400) { + const newURL = await request_resolve_redirect(res.headers.location as string).catch((err) => err); + if (newURL instanceof Error) { + reject(newURL); + return; + } + + const res2 = await request_content_length(newURL).catch((err) => err); + if (res2 instanceof Error) { + reject(res2); + return; + } + + resolve(res2); + } else { + reject( + new Error(`Failed to get content length with error: ${res.statusCode}, ${res.statusMessage}, ${url}`) + ); + } + }); +} + /** * Main module that play-dl uses for making a https request * @param req_url URL to make https request to diff --git a/play-dl/YouTube/stream.ts b/play-dl/YouTube/stream.ts index f87efd5..b9fdfd0 100644 --- a/play-dl/YouTube/stream.ts +++ b/play-dl/YouTube/stream.ts @@ -1,4 +1,4 @@ -import { request_stream } from '../Request'; +import { request_content_length, request_stream } from '../Request'; import { LiveStream, Stream } from './classes/LiveStream'; import { SeekStream } from './classes/SeekStream'; import { InfoData, StreamInfoData } from './utils/constants'; @@ -104,11 +104,19 @@ export async function stream_from_info( ); } else if (options.seek) throw new Error('Can not seek with discordPlayerCompatibility set to true.'); } + + let contentLength; + if (final[0].contentLength) { + contentLength = Number(final[0].contentLength); + } else { + contentLength = await request_content_length(final[0].url); + } + return new Stream( final[0].url, type, info.video_details.durationInSec, - Number(final[0].contentLength), + contentLength, info.video_details.url, options );