Created
September 23, 2020 17:54
-
-
Save tlwr/c16d7086984eff618533bbe3857f6cc6 to your computer and use it in GitHub Desktop.
Hosts a random govdesign poster
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'base64' | |
require 'http' | |
require 'rufus-scheduler' | |
require 'sinatra' | |
GH_URL = 'https://api.github.com/repos/alphagov/govdesign/contents' | |
STATE = { | |
lock: Mutex.new, | |
bytes: nil, | |
} | |
SCHEDULER = Rufus::Scheduler.new | |
LOADING_TEMPLATE = <<~HTML.freeze | |
<!doctype HTML> | |
<html> | |
<head><title>govdesign.cloudapps.digital</title></head> | |
<body>loading</body> | |
</html> | |
HTML | |
PAGE_TEMPLATE = <<~HTML.freeze | |
<!doctype HTML> | |
<html> | |
<head><title>govdesign.cloudapps.digital</title></head> | |
<body style="display: flex; justify-content: center; align-items: center;"> | |
<main id="pdf"> | |
<embed width="700" height="700" src="/poster.pdf#toolbar=0&navpanes=0&scrollbar=0&statusbar=0&messages=0&scrollbar=0"> | |
</embed> | |
</main> | |
</body> | |
</html> | |
HTML | |
def get_random_poster | |
files = JSON.parse(HTTP.get(GH_URL).to_s) | |
pdfs = files.select { |f| f['name'] =~ /[.]pdf$/ } | |
posters = pdfs.select { |p| p['name'] =~ /poster/i } | |
small_posters = posters.select { |p| p['size'] < 204800 } | |
poster = small_posters.shuffle.first | |
poster_url = poster['download_url'] | |
bytes = HTTP.follow.get(poster_url).to_s | |
STATE[:lock].synchronize { STATE[:bytes] = bytes } | |
end | |
SCHEDULER.every('15m') { get_random_poster } | |
get_random_poster | |
set :port, 8080 | |
get '/' do | |
bytes = STATE[:lock].synchronize { STATE[:bytes] } | |
if bytes.nil? | |
LOADING_TEMPLATE | |
else | |
PAGE_TEMPLATE | |
end | |
end | |
get '/poster.pdf' do | |
content_type 'application/pdf' | |
STATE[:lock].synchronize { STATE[:bytes] } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment