-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
81 lines (60 loc) · 2.2 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { Iconv } from "iconv";
import axios, { AxiosResponse } from "axios";
import { htmlToText } from "html-to-text";
import Joi from "joi";
const iconv = new Iconv("ISO-8859-1", "UTF-8");
const decode = (response: AxiosResponse<string>) => {
const buffer = iconv.convert(response.data);
response.data = buffer.toString();
return response;
};
axios.interceptors.response.use(decode);
const getShuffledArr = <T extends unknown[]>(arr: T) => {
const newArr = arr.slice() as T;
for (let i = newArr.length - 1; i > 0; i -= i) {
const rand = Math.floor(Math.random() * (i + 1));
[newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
}
return newArr;
};
const delims = [
'</div></div></div></div><div class="hwc"><div class="BNeawe tAd8D AP7Wnd"><div><div class="BNeawe tAd8D AP7Wnd">',
'</div></div></div><div><span class="hwc"><div class="BNeawe uEec3 AP7Wnd">',
];
const getSearchQueries = (artist: string, song: string) =>
getShuffledArr([
encodeURIComponent(`${artist} ${song} song`),
encodeURIComponent(`${artist} ${song} lyrics`),
encodeURIComponent(`${artist} ${song} song lyrics`),
encodeURIComponent(`${artist} ${song}`),
]);
const url = "https://www.google.com/search?q=";
const validateInput = (args: unknown[]) =>
Joi.attempt(args, Joi.array().items(Joi.string()).length(2).required()) as [
string,
string
];
async function lyricsSearcher(artist: string, song: string): Promise<string>;
async function lyricsSearcher(...args: unknown[]): Promise<string> {
const [artist, song] = validateInput(args);
const searchQueries = getSearchQueries(artist, song);
const lyricsArr = await Promise.all(
searchQueries.map(async (searchQuery) => {
try {
const { data: searchResult }: { data: string } = await axios.get(
`${url}${searchQuery}`
);
return searchResult.split(delims[0])[1].split(delims[1])[0];
} catch {
return "";
}
})
);
const lyrics = lyricsArr.find((l) => l);
if (lyrics === undefined) {
throw new Error("Could not find the lyrics");
}
const lines = lyrics.split("\n").map((line: string) => htmlToText(line));
return lines.join("\n").trim();
}
export = lyricsSearcher;