PageRenderTime 34ms CodeModel.GetById 16ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/s3upload.rb

http://github.com/slaskis/s3upload
Ruby | 68 lines | 53 code | 13 blank | 2 comment | 1 complexity | f8ef046bf532cc6d5fba7fe877d72e4c MD5 | raw file
 1require 'openssl'
 2require 'digest/sha1'
 3require "base64"
 4
 5module S3 
 6  class Upload
 7    
 8    attr_accessor :bucket, :expires, :secret_key, :access_key_id, :acl
 9    
10    def initialize( access_key_id , secret_key , bucket , acl="public-read" , expires=nil)
11      @access_key_id = access_key_id
12      @secret_key = secret_key
13      @bucket = bucket
14      @acl = acl
15      
16      # default to one hour from now
17      @expires = expires || (Time.now + 3600)
18      
19    end
20    
21    def to_xml( key , content_type )
22      @key = key
23      @content_type = content_type
24      
25      props = {
26        :accessKeyId => access_key_id,
27        :acl => acl,
28        :bucket => bucket,
29        :contentType => @content_type,
30        :expires => expiration_str,
31        :key => @key,
32        :secure => false,
33        :signature => signature,
34        :policy => policy
35      }
36
37      # Create xml of the properties
38      xml = "<s3>"
39      props.each {|k,v| xml << "<#{k}>#{v}</#{k}>"}
40      xml << "</s3>"
41    end
42    
43    private
44    
45    def expiration_str
46      @expires.utc.strftime('%Y-%m-%dT%H:%M:%S.000Z')
47    end
48    
49    def policy
50      @policy ||= Base64.encode64( "{
51          'expiration': '#{expiration_str}',
52          'conditions': [
53              {'bucket': '#{bucket}'},
54              {'key': '#{@key}'},
55              {'acl': '#{acl}'},
56              {'Content-Type': '#{@content_type}'},
57              ['starts-with', '$Filename', ''],
58              ['eq', '$success_action_status', '201']
59          ]
60      }").gsub(/\n|\r/, '')
61    end
62    
63    def signature
64      [OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), secret_key, policy)].pack("m").strip
65    end
66    
67  end
68end