about summary refs log tree commit diff
path: root/app/controllers/api/v1/werewolf_controller.rb
diff options
context:
space:
mode:
authormultiple creatures <dev@multiple-creature.party>2019-10-14 01:02:10 -0500
committermultiple creatures <dev@multiple-creature.party>2019-10-14 01:02:10 -0500
commit4bb53650a4f24f4f400e57337f47a48e83c9d3b0 (patch)
tree4e2a0b27b903f7a2dc734c39c7a3b53f7cf9f1f4 /app/controllers/api/v1/werewolf_controller.rb
parent47cd2611bf4dc5f9fa14e5c82c032912a9b8cab8 (diff)
add `/api/v1/werewolf` endpoint
Diffstat (limited to 'app/controllers/api/v1/werewolf_controller.rb')
-rw-r--r--app/controllers/api/v1/werewolf_controller.rb64
1 files changed, 64 insertions, 0 deletions
diff --git a/app/controllers/api/v1/werewolf_controller.rb b/app/controllers/api/v1/werewolf_controller.rb
new file mode 100644
index 000000000..74428a290
--- /dev/null
+++ b/app/controllers/api/v1/werewolf_controller.rb
@@ -0,0 +1,64 @@
+# frozen_string_literal: true
+
+class Api::V1::WerewolfController < Api::BaseController
+  respond_to :json
+  skip_before_action :set_cache_headers
+
+  def index
+    render json: werewolf_info
+  end
+
+  private
+
+  def werewolf_info
+    Rails.cache.fetch("werewolf:info", expires_in: 6.hours) do
+      this_fraction = moon_fraction(Time.now.utc)
+      {
+        werewolf: this_fraction > 0.99,
+        lastwolf: last_full_moon.strftime('%F'),
+        nextwolf: next_full_moon.strftime('%F'),
+        fullness: "#{(this_fraction * 100).round}%",
+      }
+    end
+  end
+
+  def last_full_moon
+    now     = Time.now.utc.beginning_of_day
+    offset  = 0
+    growing = false
+    moon    = moon_fraction(now)
+    last    = 0
+
+    until growing && moon < last
+      last = moon
+      offset += 1
+      moon = moon_fraction(now - offset.hours)
+      growing = true unless growing || moon < last
+    end
+
+    offset -= 1
+    now - offset.hours
+  end
+
+  def next_full_moon
+    now     = Time.now.utc.beginning_of_day
+    offset  = 0
+    growing = false
+    moon    = moon_fraction(now)
+    last    = 0
+
+    until growing && moon < last
+      last = moon
+      offset += 1
+      moon = moon_fraction(now + offset.hours)
+      growing = true unless growing || moon < last
+    end
+
+    offset -= 1
+    now + offset.hours
+  end
+
+  def moon_fraction(time)
+    SunCalc.moon_illumination(time)[:fraction]
+  end
+end