Skip to content

Instantly share code, notes, and snippets.

@tcannonfodder
Created October 2, 2020 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcannonfodder/1870a5c3a26157b10a24b4b385da6665 to your computer and use it in GitHub Desktop.
Save tcannonfodder/1870a5c3a26157b10a24b4b385da6665 to your computer and use it in GitHub Desktop.
A Sinatra server that listens for broadcasts from Noko, and gets the latest status of a timer
require 'sinatra'
require 'json'
require 'openssl'
require 'byebug'
require 'httparty'
NOKO_TOKEN = "YOUR TOKEN"
BROADCAST_RECEIVER_NAME = "Timer Status"
PAYLOAD_URI = "YOUR URI"
def api_headers
{"User-Agent" => "TimerStatus", "X-NokoToken" => NOKO_TOKEN, "Content-Type" => 'application/json', "Accept" => "application/json"}
end
def find_or_create_broadcast_receiver
url = "https://api.nokotime.com/v2/broadcast_receivers"
response = HTTParty.get(url, headers: api_headers, query: {name: BROADCAST_RECEIVER_NAME })
receivers = JSON.parse(response.body)
if receivers.size == 0
receiver_response = HTTParty.post(url, headers: api_headers, body: JSON.generate({
name: BROADCAST_RECEIVER_NAME,
payload_uri: PAYLOAD_URI,
subjects: ["timer"]
}))
puts "creating: #{receiver_response.code}"
else
receiver = JSON.parse(response.body).first
update_receiver_response = HTTParty.put(receiver["url"], headers: api_headers, body: JSON.generate({
name: BROADCAST_RECEIVER_NAME,
payload_uri: PAYLOAD_URI,
}))
puts "updating: #{update_receiver_response.code}"
receiver_response = HTTParty.put(receiver["reroll_secret_url"], headers: api_headers)
puts "re-roll secret: #{receiver_response.code}"
end
set :broadcast_receiver_secret, JSON.parse(receiver_response.body)["secret"]
end
def read_payload(secret, request)
body = request.body.read
push = JSON.parse(body)
given_signature = request.env["HTTP_X_NOKO_SIGNATURE"]
signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret, body)
return halt 500, "Signatures didn't match!" unless Rack::Utils.secure_compare(signature, given_signature)
puts body
return push
end
def timer_status(url)
response = HTTParty.get(url, headers: api_headers)
if response.code == 404
puts "👻 No more timer! (#{url})"
return
end
timer = JSON.parse(response.body)
project_name = timer["project"]["name"]
time = timer["formatted_time"]
case timer["state"]
when "pending"
puts "🟢 Timer is ready to go: #{project_name} ; #{time}"
when "running"
puts "🏃‍♀️ Timer is running: #{project_name} ; #{time}"
when "paused"
puts "⏸ Timer is paused: #{project_name} ; #{time}"
when "stopped"
puts "🛑 Timer is stopped: #{project_name} ; #{time}"
end
end
puts "Setting up receiver..."
find_or_create_broadcast_receiver
post '/broadcasts/timer_status' do
broadcast = read_payload( settings.broadcast_receiver_secret, request)
timer_status(broadcast["subject"]["url"])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment