commit d0c832a0dd756e494b2cc3c9cc2474b7f6397671
parent 708999aad4dd3aaffa411384f9691468bc2ee093
Author: Demonstrandum <moi@knutsen.co>
Date: Tue, 4 Aug 2020 21:31:11 +0100
Shift arg list when `new' appears first. Only use URI-encoded query in URL.
Diffstat:
1 file changed, 31 insertions(+), 17 deletions(-)
diff --git a/lib/commands/youtube.ts b/lib/commands/youtube.ts
@@ -1,20 +1,28 @@
import fetch from "node-fetch";
-//.yt x
-//.yt x n, where n < 20
-//.yt new x
-//.yt channel/playlist x
+/*! # Command syntax:
+ * Let x : query, n : nth-result, in
+ * !youtube x
+ * !youtube x n, where 1 <= n <= 20
+ * !youtube new x
+ * !youtube {channel,playlist} x
+ */
export default async (home_scope: HomeScope) => {
const { message, args } = home_scope;
- var query = args.join(" ").trim();
- query = encodeURI(query);
- const sort_by = (args[0] == "new") ? "upload_date" : "relevance";
- const type = (args[0] == "channel" || args[0] == "playlist") ? args.shift() : "video";
+ let query = args.join(' ').trim();
+
+ const sort_by = (args[0] == "new")
+ ? (args.shift(), "upload_date")
+ : "relevance";
+ const type = (args[0] == "channel" || args[0] == "playlist")
+ ? args.shift()
+ : "video";
+
let num : number = 1;
- if (query.length === 0 || args.length === 0)
+ if (query.length === 0 || args.length === 0) {
query = "bruh city";
- else {
+ } else {
const num_match = query.match(/[ ]+(\d+)$/);
if (num_match) {
num = Number(num_match[1]);
@@ -22,24 +30,30 @@ export default async (home_scope: HomeScope) => {
}
}
- const result = await fetch(`https://invidio.us/api/v1/search?q=${query}&sort_by=${sort_by}&type=${type}`);
+ const query_uri = encodeURI(query);
+ const result = await fetch(`https://invidio.us/api/v1/search`
+ + `?q=${query_uri}&sort_by=${sort_by}&type=${type}`);
const res_json = await result.json();
const res = res_json[Math.abs(num - 1)];
+
let duration = new Date(res.lengthSeconds * 1000)
.toISOString()
.substr(11, 8);
if (duration.substr(0, 2) == '00')
duration = duration.slice(3);
- const views = Number(res.viewCount).to_abbrev(1);
+ const views : string = Number(res.viewCount).to_abbrev(1);
message.answer(`Search for '${query}' (result №${num}):`
- + ` https://youtu.be/${res.videoId}\n`
- + `published ${res.publishedText},`
+ + ` https://youtu.be/${res.videoId}`
+ + `\npublished ${res.publishedText},`
+ ` view count: ${views}, duration: ${duration}`);
- // TODO timestamp generation
- /*yt_search({ query })
+ // TODO: Timestamp generation.
+
+ /* // Old (actual) YT scraping.
+ yt_search({ query })
.then(message.reply.bind(message))
- .catch(message.answer.bind(message));*/
+ .catch(message.answer.bind(message));
+ */
};