From 2ba0063dc0833efe25a25dea7b3f8d95b599f0d6 Mon Sep 17 00:00:00 2001 From: Omar Roth Date: Mon, 27 Aug 2018 15:23:25 -0500 Subject: [PATCH] Add search filters --- src/invidious.cr | 26 +++++++++++++++++++++++++- src/invidious/search.cr | 13 +++++++++---- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/invidious.cr b/src/invidious.cr index bcbdcc6d..65846303 100644 --- a/src/invidious.cr +++ b/src/invidious.cr @@ -429,7 +429,31 @@ get "/search" do |env| page = env.params.query["page"]?.try &.to_i? page ||= 1 - search_params = build_search_params(sort_by: "relevance", content_type: "video") + sort = "relevance" + date = "" + duration = "" + features = [] of String + + operators = query.split(" ").select { |a| a.match(/\w+:[\w,]+/) } + operators.each do |operator| + key, value = operator.split(":") + + case key + when "sort" + sort = value + when "date" + date = value + when "duration" + duration = value + when "features" + features = value.split(",") + end + end + + query = (query.split(" ") - operators).join(" ") + + search_params = build_search_params(sort: sort, date: date, content_type: "video", + duration: duration, features: features) count, videos = search(query, page, search_params).as(Tuple) templated "search" diff --git a/src/invidious/search.cr b/src/invidious/search.cr index 04db3098..e5b006bf 100644 --- a/src/invidious/search.cr +++ b/src/invidious/search.cr @@ -14,9 +14,13 @@ end def search(query, page = 1, search_params = build_search_params(content_type: "video")) client = make_client(YT_URL) + if query.empty? + return {0, [] of SearchVideo} + end + html = client.get("/results?q=#{URI.escape(query)}&page=#{page}&sp=#{search_params}&disable_polymer=1").body if html.empty? - return [] of SearchVideo + return {0, [] of SearchVideo} end html = XML.parse_html(html) @@ -26,9 +30,10 @@ def search(query, page = 1, search_params = build_search_params(content_type: "v return {nodeset.size, videos} end -def build_search_params(sort_by = "relevance", date : String = "", content_type : String = "", duration : String = "", features : Array(String) = [] of String) +def build_search_params(sort : String = "relevance", date : String = "", content_type : String = "", + duration : String = "", features : Array(String) = [] of String) head = "\x08" - head += case sort_by + head += case sort when "relevance" "\x00" when "rating" @@ -38,7 +43,7 @@ def build_search_params(sort_by = "relevance", date : String = "", content_type when "view_count" "\x03" else - raise "No sort #{sort_by}" + raise "No sort #{sort}" end body = ""