Files
play-dl-test/play-dl/YouTube/search.ts

51 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-10-11 18:38:08 +05:30
import { request } from './../Request';
2021-09-17 14:36:32 +05:30
import { ParseSearchInterface, ParseSearchResult } from './utils/parser';
2021-09-27 22:20:50 +05:30
import { YouTubeVideo } from './classes/Video';
import { YouTubeChannel } from './classes/Channel';
import { YouTubePlayList } from './classes/Playlist';
2021-08-12 13:28:17 +05:30
2021-08-13 13:16:34 +05:30
enum SearchType {
Video = 'EgIQAQ%253D%253D',
PlayList = 'EgIQAw%253D%253D',
2021-09-17 14:36:32 +05:30
Channel = 'EgIQAg%253D%253D'
2021-08-13 13:16:34 +05:30
}
2021-09-29 20:23:16 +05:30
/**
* Type for YouTube returns
*/
2021-09-27 22:20:50 +05:30
export type YouTube = YouTubeVideo | YouTubeChannel | YouTubePlayList;
2021-09-29 20:23:16 +05:30
/**
* Command to search from YouTube
* @param search The query to search
* @param options limit & type of YouTube search you want.
* @returns YouTube type.
*/
2021-09-27 22:20:50 +05:30
export async function yt_search(search: string, options: ParseSearchInterface = {}): Promise<YouTube[]> {
2021-10-21 14:54:53 +05:30
let url = 'https://www.youtube.com/results?search_query=' + search;
2021-09-17 14:36:32 +05:30
options.type ??= 'video';
2021-12-01 18:26:22 +01:00
if (url.indexOf('&sp=') === -1) {
2021-09-17 14:36:32 +05:30
url += '&sp=';
2021-12-01 18:26:22 +01:00
switch (options.type) {
2021-08-13 13:16:34 +05:30
case 'channel':
2021-09-17 14:36:32 +05:30
url += SearchType.Channel;
break;
2021-08-13 13:16:34 +05:30
case 'playlist':
2021-09-17 14:36:32 +05:30
url += SearchType.PlayList;
break;
2021-08-13 13:16:34 +05:30
case 'video':
2021-09-17 14:36:32 +05:30
url += SearchType.Video;
break;
2021-12-01 18:26:22 +01:00
default:
throw new Error(`Unknown search type: ${options.type}`);
2021-08-13 13:16:34 +05:30
}
}
2021-09-17 14:36:32 +05:30
const body = await request(url, {
2021-12-07 10:43:23 +05:30
headers: {
2021-12-26 15:34:31 +05:30
'accept-language': options.language || 'en-US;q=0.9'
2021-12-02 12:14:34 +05:30
}
2021-09-17 14:36:32 +05:30
});
2021-12-01 20:43:16 +05:30
if (body.indexOf('Our systems have detected unusual traffic from your computer network.') !== -1)
throw new Error('Captcha page: YouTube has detected that you are a bot!');
2021-12-01 18:26:22 +01:00
return ParseSearchResult(body, options);
2021-09-17 14:36:32 +05:30
}