-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathskynotra.rb
85 lines (74 loc) · 1.87 KB
/
skynotra.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
require 'bundler'
require 'digest/sha1'
require 'fog'
require 'json'
require 'net/http'
require 'redis'
require 'uri'
Bundler.require if defined?(Bundler)
before do
$redis = if redistogo_url = ENV["REDISTOGO_URL"]
uri = URI.parse redistogo_url
Redis.new host: uri.host, port: uri.port, password: uri.password
else
Redis.new
end
$s3 = Fog::Storage.new({
provider: 'AWS',
aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
})
$s3_dir = $s3.directories.create key: 'skynotra', public: true
end
def cache key, &block
if val = $redis.get(key)
val
else
val = block.call
$redis.set key, val
val
end
end
module Skynotra
class Application < Sinatra::Application
set :public_folder, 'public'
get '/' do
slim :index
end
get '/observations.json' do
content_type :json
cache "observations:#{params[:target]}" do
observations = SkyMorph::Observation.find(params[:target]).map(&:to_hash)
JSON.dump(observations)
end
end
get '/images.json' do
content_type :json
cache "images:#{params[:keys]}" do
image_url = get_image_url(params[:keys])
JSON.dump({ image_url: image_url })
end
end
get '/images.gif' do
sha = Digest::SHA1.hexdigest(params[:keys])
file = $s3_dir.files.get(sha) || begin
puts "Downloading image ..."
image_url = URI.parse(get_image_url(params[:keys]))
image = Net::HTTP.get_response(image_url).body
# Cache image in S3
s3_file = $s3_dir.files.new({
key: sha,
body: image,
public: true
})
s3_file.save
s3_file
end
redirect file.public_url
end
private
def get_image_url(key)
SkyMorph::Image.find(key).first.path
end
end
end