@@ -268,18 +268,20 @@ def fetch_reddit_comments(id, sort_by = "confidence")
268268 headers = HTTP ::Headers {" User-Agent" => " web:invidious:v#{ CURRENT_VERSION } (by github.com/iv-org/invidious)" }
269269
270270 # TODO: Use something like #479 for a static list of instances to use here
271- query = " (url:3D#{ id } %20OR%20url :#{ id } )%20 (site:invidio.us%20OR%20site :youtube.com%20OR%20site :youtu.be)"
272- search_results = client.get(" /search.json?q= #{ query } " , headers)
271+ query = URI :: Params .encode({ q: " (url:3D#{ id } OR url :#{ id } ) AND (site:invidio.us OR site :youtube.com OR site :youtu.be)" })
272+ search_results = client.get(" /search.json?#{ query } " , headers)
273273
274274 if search_results.status_code == 200
275275 search_results = RedditThing .from_json(search_results.body)
276276
277277 # For videos that have more than one thread, choose the one with the highest score
278- thread = search_results.data.as(RedditListing ).children.sort_by { |child | child.data.as(RedditLink ).score }[-1 ]
279- thread = thread.data.as(RedditLink )
280-
281- result = client.get(" /r/#{ thread.subreddit } /comments/#{ thread.id } .json?limit=100&sort=#{ sort_by } " , headers).body
282- result = Array (RedditThing ).from_json(result)
278+ threads = search_results.data.as(RedditListing ).children
279+ thread = threads.max_by?(& .data.as(RedditLink ).score).try(& .data.as(RedditLink ))
280+ result = thread.try do |t |
281+ body = client.get(" /r/#{ t.subreddit } /comments/#{ t.id } .json?limit=100&sort=#{ sort_by } " , headers).body
282+ Array (RedditThing ).from_json(body)
283+ end
284+ result ||= [] of RedditThing
283285 elsif search_results.status_code == 302
284286 # Previously, if there was only one result then the API would redirect to that result.
285287 # Now, it appears it will still return a listing so this section is likely unnecessary.
@@ -294,7 +296,8 @@ def fetch_reddit_comments(id, sort_by = "confidence")
294296
295297 client.close
296298
297- comments = result[1 ].data.as(RedditListing ).children
299+ comments = result[1 ]?.try(& .data.as(RedditListing ).children)
300+ comments ||= [] of RedditThing
298301 return comments, thread
299302end
300303
0 commit comments