From a9cea62d5b4faf92ba66cdfa94270b545b157999 Mon Sep 17 00:00:00 2001
From: Omar Roth <omarroth@hotmail.com>
Date: Mon, 5 Feb 2018 17:56:40 -0600
Subject: [PATCH] Add home page

---
 src/helpers.cr      | 27 ++++++++++++++++++++++++++-
 src/invidious.cr    | 15 +++++++++++++++
 src/views/index.ecr | 18 +++++++++++++++++-
 3 files changed, 58 insertions(+), 2 deletions(-)

diff --git a/src/helpers.cr b/src/helpers.cr
index a5148bdf..8106cb4f 100644
--- a/src/helpers.cr
+++ b/src/helpers.cr
@@ -183,4 +183,29 @@ def decrypt_signature(a)
   a[0] = a[49 % a.size]
   a[49] = c
   return a.join("")
-end
\ No newline at end of file
+end
+
+def rank_videos(db, n)
+  top = [] of {Float64, String}
+
+  db.query("SELECT id, wilson_score, published FROM videos WHERE views > 5000 ORDER BY published DESC LIMIT 10000") do |rs|
+    rs.each do
+      id = rs.read(String)
+      wilson_score = rs.read(Float64)
+      published = rs.read(Time)
+
+      # Exponential decay, older videos tend to rank lower
+      temperature = wilson_score * Math.exp(-0.02*((Time.now - published).hours))
+      top << {temperature, id}
+    end
+  end
+
+  top.sort!
+
+  # Make hottest come first
+  top.reverse!
+  top = top.map { |a, b| b }
+
+  # Return top
+  return top[1..n]
+end
diff --git a/src/invidious.cr b/src/invidious.cr
index b23dfe5b..18613ffe 100644
--- a/src/invidious.cr
+++ b/src/invidious.cr
@@ -123,6 +123,21 @@ macro templated(filename)
 end
 
 get "/" do |env|
+  top = rank_videos(PG_DB, 120)
+
+  args = [] of String
+  1..(top.size - 1).times { |i| args << "($#{i + 1}), " }
+  args << "($#{top.size}) "
+  args = args.join("")
+
+  videos = [] of Video
+  PG_DB.query("SELECT * FROM videos d INNER JOIN (VALUES #{args}) v(id) USING (id)", top) do |rs|
+    rs.each do
+      video = rs.read(Video)
+      videos << video
+    end
+  end
+
   templated "index"
 end
 
diff --git a/src/views/index.ecr b/src/views/index.ecr
index 885c8d5c..3d250f56 100644
--- a/src/views/index.ecr
+++ b/src/views/index.ecr
@@ -1,3 +1,19 @@
 <% content_for "header" do %>
 <title>Invidious</title>
-<% end %>
\ No newline at end of file
+<% end %>
+
+<% videos.each_slice(4) do |slice| %>
+<div class="pure-g">
+<% slice.each do |video| %>
+    <% player_response = JSON.parse(video.info["player_response"]) %>
+    <div class="pure-u-1 pure-u-md-1-4">
+        <div style="margin: 1em;">
+            <a style="width:100%;" class="link" href="/watch?v=<%= video.id %>">
+                <img style="width:100%" src="<%= player_response["videoDetails"]["thumbnail"]["thumbnails"][0]["url"] %>"/>
+                <%= video.title %>
+            </a>
+        </div>
+    </div>
+    <% end %>
+</div>
+<% end %>