Skip to content

Instantly share code, notes, and snippets.

@jberkel
Created October 7, 2010 12:35
Show Gist options
  • Save jberkel/615032 to your computer and use it in GitHub Desktop.
Save jberkel/615032 to your computer and use it in GitHub Desktop.
store apks in da cloud
#!/usr/bin/env ruby
require 'aws/s3'
require 'erb'
require 'cgi'
require 'json'
class CloudAPK
include AWS::S3
EXPIRES = 86400 * 365 * 5
def upload(file_name)
upload_html(upload_apk(file_name))
end
def upload_apk(file_name)
new_obj = apk_bucket.new_object
new_obj.key = File.basename(file_name)
new_obj.value = IO.read(file_name)
new_obj.store :content_type => 'application/vnd.android.package-archive'
new_obj
end
def upload_html(obj)
html = apk_bucket.new_object
html.key = obj.key + ".html"
html.value = create_qr(obj)
html.store :content_type => 'text/html'
html
end
def shorten(url)
key = ENV['BITLY_KEY']
login = ENV['BITLY_LOGIN']
if key.nil? || login.nil?
STDERR.puts "Set BITLY_KEY and BITLY_LOGIN for automatic link shortening"
return nil
end
resp = Net::HTTP.get_response(URI.parse(
"http://api.bitly.com/v3/shorten?longUrl=#{CGI.escape(url)}&apiKey=#{key}&login=#{login}")
)
case resp
when Net::HTTPSuccess
r = JSON.parse(resp.body)
return r['data']['url']
else resp.value()
end
end
def create_qr(obj, size = '500x500')
url = obj.url :expires_in => EXPIRES
ERB.new(<<-QR
<html>
<head><title><%= obj.key %></title></head>
<body>
<img src="http://chart.apis.google.com/chart?cht=qr&chl=<%= CGI.escape(url) %>&chs=<%=size%>&chld=L|0"/>
<br/>
<a href="<%=url%>"><h1> <%= obj.key %> </h1> </a>
</body>
</html>
QR
).result(binding)
end
def apk_bucket
connect('apk-in-the-cloud')
end
def connect(bucket_name)
unless @connected
Base.establish_connection!(
:access_key_id => ENV['AMAZON_ACCESS_KEY_ID'],
:secret_access_key => ENV['AMAZON_SECRET_ACCESS_KEY'])
@connected = true
end
begin
Bucket.find(bucket_name)
rescue
STDERR.puts "Need to make bucket #{bucket_name}.."
Bucket.create(bucket_name)
Bucket.find(bucket_name)
end
end
end
if __FILE__ == $0
raise "#{File.basename($0)} foo.apk" unless ARGV[0]
raise "#{ARGV[0]}: File not found" unless File.exists? ARGV[0]
apk = CloudAPK.new
obj = apk.upload(ARGV[0])
url = obj.url :expires_in => CloudAPK::EXPIRES
s_url = apk.shorten(url)
puts url
puts s_url if s_url
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment