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

46 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-09-17 14:36:32 +05:30
import { request } from './utils/request';
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-09-17 14:36:32 +05:30
let url = 'https://www.youtube.com/results?search_query=' + search.replaceAll(' ', '+');
options.type ??= 'video';
if (!url.match('&sp=')) {
url += '&sp=';
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-08-13 13:16:34 +05:30
}
}
2021-09-17 14:36:32 +05:30
const body = await request(url, {
headers: { 'accept-language': 'en-US,en-IN;q=0.9,en;q=0.8,hi;q=0.7' }
});
const data = ParseSearchResult(body, options);
return data;
}