alancse-aws-s3 0.4.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,308 @@
1
+ module AWS
2
+ module S3
3
+ # A bucket can be set to log the requests made on it. By default logging is turned off. You can check if a bucket has logging enabled:
4
+ #
5
+ # Bucket.logging_enabled_for? 'jukebox'
6
+ # # => false
7
+ #
8
+ # Enabling it is easy:
9
+ #
10
+ # Bucket.enable_logging_for('jukebox')
11
+ #
12
+ # Unless you specify otherwise, logs will be written to the bucket you want to log. The logs are just like any other object. By default they will start with the prefix 'log-'. You can customize what bucket you want the logs to be delivered to, as well as customize what the log objects' key is prefixed with by setting the <tt>target_bucket</tt> and <tt>target_prefix</tt> option:
13
+ #
14
+ # Bucket.enable_logging_for(
15
+ # 'jukebox', 'target_bucket' => 'jukebox-logs'
16
+ # )
17
+ #
18
+ # Now instead of logging right into the jukebox bucket, the logs will go into the bucket called jukebox-logs.
19
+ #
20
+ # Once logs have accumulated, you can access them using the <tt>logs</tt> method:
21
+ #
22
+ # pp Bucket.logs('jukebox')
23
+ # [#<AWS::S3::Logging::Log '/jukebox-logs/log-2006-11-14-07-15-24-2061C35880A310A1'>,
24
+ # #<AWS::S3::Logging::Log '/jukebox-logs/log-2006-11-14-08-15-27-D8EEF536EC09E6B3'>,
25
+ # #<AWS::S3::Logging::Log '/jukebox-logs/log-2006-11-14-08-15-29-355812B2B15BD789'>]
26
+ #
27
+ # Each log has a <tt>lines</tt> method that gives you information about each request in that log. All the fields are available
28
+ # as named methods. More information is available in Logging::Log::Line.
29
+ #
30
+ # logs = Bucket.logs('jukebox')
31
+ # log = logs.first
32
+ # line = log.lines.first
33
+ # line.operation
34
+ # # => 'REST.GET.LOGGING_STATUS'
35
+ # line.request_uri
36
+ # # => 'GET /jukebox?logging HTTP/1.1'
37
+ # line.remote_ip
38
+ # # => "67.165.183.125"
39
+ #
40
+ # Disabling logging is just as simple as enabling it:
41
+ #
42
+ # Bucket.disable_logging_for('jukebox')
43
+ module Logging
44
+ # Logging status captures information about the calling bucket's logging settings. If logging is enabled for the bucket
45
+ # the status object will indicate what bucket the logs are written to via the <tt>target_bucket</tt> method as well as
46
+ # the logging key prefix with via <tt>target_prefix</tt>.
47
+ #
48
+ # See the documentation for Logging::Management::ClassMethods for more information on how to get the logging status of a bucket.
49
+ class Status
50
+ include SelectiveAttributeProxy
51
+ attr_reader :enabled
52
+ alias_method :logging_enabled?, :enabled
53
+
54
+ def initialize(attributes = {}) #:nodoc:
55
+ attributes = {'target_bucket' => nil, 'target_prefix' => nil}.merge(attributes)
56
+ @enabled = attributes.has_key?('logging_enabled')
57
+ @attributes = attributes.delete('logging_enabled') || attributes
58
+ end
59
+
60
+ def to_xml #:nodoc:
61
+ Builder.new(self).to_s
62
+ end
63
+
64
+ private
65
+ attr_reader :attributes
66
+
67
+ class Builder < XmlGenerator #:nodoc:
68
+ attr_reader :logging_status
69
+ def initialize(logging_status)
70
+ @logging_status = logging_status
71
+ super()
72
+ end
73
+
74
+ def build
75
+ xml.tag!('BucketLoggingStatus', 'xmlns' => 'http://s3.amazonaws.com/doc/2006-03-01/') do
76
+ if logging_status.target_bucket && logging_status.target_prefix
77
+ xml.LoggingEnabled do
78
+ xml.TargetBucket logging_status.target_bucket
79
+ xml.TargetPrefix logging_status.target_prefix
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
86
+
87
+ # A bucket log exposes requests made on the given bucket. Lines of the log represent a single request. The lines of a log
88
+ # can be accessed with the lines method.
89
+ #
90
+ # log = Bucket.logs_for('marcel').first
91
+ # log.lines
92
+ #
93
+ # More information about the logged requests can be found in the documentation for Log::Line.
94
+ class Log
95
+ def initialize(log_object) #:nodoc:
96
+ @log = log_object
97
+ end
98
+
99
+ # Returns the lines for the log. Each line is wrapped in a Log::Line.
100
+ def lines
101
+ log.value.map {|line| Line.new(line)}
102
+ end
103
+ memoized :lines
104
+
105
+ def inspect #:nodoc:
106
+ "#<%s:0x%s '%s'>" % [self.class.name, object_id, log.path]
107
+ end
108
+
109
+ private
110
+ attr_reader :log
111
+
112
+ # Each line of a log exposes the raw line, but it also has method accessors for all the fields of the logged request.
113
+ #
114
+ # The list of supported log line fields are listed in the S3 documentation: http://docs.amazonwebservices.com/AmazonS3/2006-03-01/LogFormat.html
115
+ #
116
+ # line = log.lines.first
117
+ # line.remote_ip
118
+ # # => '72.21.206.5'
119
+ #
120
+ # If a certain field does not apply to a given request (for example, the <tt>key</tt> field does not apply to a bucket request),
121
+ # or if it was unknown or unavailable, it will return <tt>nil</tt>.
122
+ #
123
+ # line.operation
124
+ # # => 'REST.GET.BUCKET'
125
+ # line.key
126
+ # # => nil
127
+ class Line < String
128
+ DATE = /\[([^\]]+)\]/
129
+ QUOTED_STRING = /"([^"]+)"/
130
+ REST = /(\S+)/
131
+ LINE_SCANNER = /#{DATE}|#{QUOTED_STRING}|#{REST}/
132
+
133
+ cattr_accessor :decorators
134
+ @@decorators = Hash.new {|hash, key| hash[key] = lambda {|entry| CoercibleString.coerce(entry)}}
135
+ cattr_reader :fields
136
+ @@fields = []
137
+
138
+ class << self
139
+ def field(name, offset, type = nil, &block) #:nodoc:
140
+ decorators[name] = block if block_given?
141
+ fields << name
142
+ class_eval(<<-EVAL, __FILE__, __LINE__)
143
+ def #{name}
144
+ value = parts[#{offset} - 1]
145
+ if value == '-'
146
+ nil
147
+ else
148
+ self.class.decorators[:#{name}].call(value)
149
+ end
150
+ end
151
+ memoized :#{name}
152
+ EVAL
153
+ end
154
+
155
+ # Time.parse doesn't like %d/%B/%Y:%H:%M:%S %z so we have to transform it unfortunately
156
+ def typecast_time(datetime) #:nodoc:
157
+ month = datetime[/[a-z]+/i]
158
+ datetime.sub!(%r|^(\w{2})/(\w{3})|, '\2/\1')
159
+ if Date.constants.include?('ABBR_MONTHS')
160
+ datetime.sub!(month, Date::ABBR_MONTHS[month.downcase].to_s)
161
+ end
162
+ datetime.sub!(':', ' ')
163
+ Time.parse(datetime)
164
+ end
165
+ end
166
+
167
+ def initialize(line) #:nodoc:
168
+ super(line)
169
+ @parts = parse
170
+ end
171
+
172
+ field(:owner, 1) {|entry| Owner.new('id' => entry) }
173
+ field :bucket, 2
174
+ field(:time, 3) {|entry| typecast_time(entry)}
175
+ field :remote_ip, 4
176
+ field(:requestor, 5) {|entry| Owner.new('id' => entry) }
177
+ field :request_id, 6
178
+ field :operation, 7
179
+ field :key, 8
180
+ field :request_uri, 9
181
+ field :http_status, 10
182
+ field :error_code, 11
183
+ field :bytes_sent, 12
184
+ field :object_size, 13
185
+ field :total_time, 14
186
+ field :turn_around_time, 15
187
+ field :referrer, 16
188
+ field :user_agent, 17
189
+
190
+ # Returns all fields of the line in a hash of the form <tt>:field_name => :field_value</tt>.
191
+ #
192
+ # line.attributes.values_at(:bucket, :key)
193
+ # # => ['marcel', 'kiss.jpg']
194
+ def attributes
195
+ self.class.fields.inject({}) do |attribute_hash, field|
196
+ attribute_hash[field] = send(field)
197
+ attribute_hash
198
+ end
199
+ end
200
+
201
+ private
202
+ attr_reader :parts
203
+
204
+ def parse
205
+ scan(LINE_SCANNER).flatten.compact
206
+ end
207
+ end
208
+ end
209
+
210
+ module Management #:nodoc:
211
+ def self.included(klass) #:nodoc:
212
+ klass.extend(ClassMethods)
213
+ klass.extend(LoggingGrants)
214
+ end
215
+
216
+ module ClassMethods
217
+ # Returns the logging status for the bucket named <tt>name</tt>. From the logging status you can determine the bucket logs are delivered to
218
+ # and what the bucket object's keys are prefixed with. For more information see the Logging::Status class.
219
+ #
220
+ # Bucket.logging_status_for 'marcel'
221
+ def logging_status_for(name = nil, status = nil)
222
+ if name.is_a?(Status)
223
+ status = name
224
+ name = nil
225
+ end
226
+
227
+ path = path(name) << '?logging'
228
+ status ? put(path, {}, status.to_xml) : Status.new(get(path).parsed)
229
+ end
230
+ alias_method :logging_status, :logging_status_for
231
+
232
+ # Enables logging for the bucket named <tt>name</tt>. You can specify what bucket to log to with the <tt>'target_bucket'</tt> option as well
233
+ # as what prefix to add to the log files with the <tt>'target_prefix'</tt> option. Unless you specify otherwise, logs will be delivered to
234
+ # the same bucket that is being logged and will be prefixed with <tt>log-</tt>.
235
+ def enable_logging_for(name = nil, options = {})
236
+ name = bucket_name(name)
237
+ default_options = {'target_bucket' => name, 'target_prefix' => 'log-'}
238
+ options = default_options.merge(options)
239
+ grant_logging_access_to_target_bucket(options['target_bucket'])
240
+ logging_status(name, Status.new(options))
241
+ end
242
+ alias_method :enable_logging, :enable_logging_for
243
+
244
+ # Disables logging for the bucket named <tt>name</tt>.
245
+ def disable_logging_for(name = nil)
246
+ logging_status(bucket_name(name), Status.new)
247
+ end
248
+ alias_method :disable_logging, :disable_logging_for
249
+
250
+ # Returns true if logging has been enabled for the bucket named <tt>name</tt>.
251
+ def logging_enabled_for?(name = nil)
252
+ logging_status(bucket_name(name)).logging_enabled?
253
+ end
254
+ alias_method :logging_enabled?, :logging_enabled_for?
255
+
256
+ # Returns the collection of logs for the bucket named <tt>name</tt>.
257
+ #
258
+ # Bucket.logs_for 'marcel'
259
+ #
260
+ # Accepts the same options as Bucket.find, such as <tt>:max_keys</tt> and <tt>:marker</tt>.
261
+ def logs_for(name = nil, options = {})
262
+ if name.is_a?(Hash)
263
+ options = name
264
+ name = nil
265
+ end
266
+
267
+ name = bucket_name(name)
268
+ logging_status = logging_status_for(name)
269
+ return [] unless logging_status.logging_enabled?
270
+ objects(logging_status.target_bucket, options.merge(:prefix => logging_status.target_prefix)).map do |log_object|
271
+ Log.new(log_object)
272
+ end
273
+ end
274
+ alias_method :logs, :logs_for
275
+ end
276
+
277
+ module LoggingGrants #:nodoc:
278
+ def grant_logging_access_to_target_bucket(target_bucket)
279
+ acl = acl(target_bucket)
280
+ acl.grants << ACL::Grant.grant(:logging_write)
281
+ acl.grants << ACL::Grant.grant(:logging_read_acp)
282
+ acl(target_bucket, acl)
283
+ end
284
+ end
285
+
286
+ def logging_status
287
+ self.class.logging_status_for(name)
288
+ end
289
+
290
+ def enable_logging(*args)
291
+ self.class.enable_logging_for(name, *args)
292
+ end
293
+
294
+ def disable_logging(*args)
295
+ self.class.disable_logging_for(name, *args)
296
+ end
297
+
298
+ def logging_enabled?
299
+ self.class.logging_enabled_for?(name)
300
+ end
301
+
302
+ def logs(options = {})
303
+ self.class.logs_for(name, options)
304
+ end
305
+ end
306
+ end
307
+ end
308
+ end
@@ -0,0 +1,611 @@
1
+ module AWS
2
+ module S3
3
+ # S3Objects represent the data you store on S3. They have a key (their name) and a value (their data). All objects belong to a
4
+ # bucket.
5
+ #
6
+ # You can store an object on S3 by specifying a key, its data and the name of the bucket you want to put it in:
7
+ #
8
+ # S3Object.store('me.jpg', open('headshot.jpg'), 'photos')
9
+ #
10
+ # The content type of the object will be inferred by its extension. If the appropriate content type can not be inferred, S3 defaults
11
+ # to <tt>binary/octect-stream</tt>.
12
+ #
13
+ # If you want to override this, you can explicitly indicate what content type the object should have with the <tt>:content_type</tt> option:
14
+ #
15
+ # file = 'black-flowers.m4a'
16
+ # S3Object.store(
17
+ # file,
18
+ # open(file),
19
+ # 'jukebox',
20
+ # :content_type => 'audio/mp4a-latm'
21
+ # )
22
+ #
23
+ # You can read more about storing files on S3 in the documentation for S3Object.store.
24
+ #
25
+ # If you just want to fetch an object you've stored on S3, you just specify its name and its bucket:
26
+ #
27
+ # picture = S3Object.find 'headshot.jpg', 'photos'
28
+ #
29
+ # N.B. The actual data for the file is not downloaded in both the example where the file appeared in the bucket and when fetched directly.
30
+ # You get the data for the file like this:
31
+ #
32
+ # picture.value
33
+ #
34
+ # You can fetch just the object's data directly:
35
+ #
36
+ # S3Object.value 'headshot.jpg', 'photos'
37
+ #
38
+ # Or stream it by passing a block to <tt>stream</tt>:
39
+ #
40
+ # open('song.mp3', 'w') do |file|
41
+ # S3Object.stream('song.mp3', 'jukebox') do |chunk|
42
+ # file.write chunk
43
+ # end
44
+ # end
45
+ #
46
+ # The data of the file, once download, is cached, so subsequent calls to <tt>value</tt> won't redownload the file unless you
47
+ # tell the object to reload its <tt>value</tt>:
48
+ #
49
+ # # Redownloads the file's data
50
+ # song.value(:reload)
51
+ #
52
+ # Other functionality includes:
53
+ #
54
+ # # Check if an object exists?
55
+ # S3Object.exists? 'headshot.jpg', 'photos'
56
+ #
57
+ # # Copying an object
58
+ # S3Object.copy 'headshot.jpg', 'headshot2.jpg', 'photos'
59
+ #
60
+ # # Renaming an object
61
+ # S3Object.rename 'headshot.jpg', 'portrait.jpg', 'photos'
62
+ #
63
+ # # Deleting an object
64
+ # S3Object.delete 'headshot.jpg', 'photos'
65
+ #
66
+ # ==== More about objects and their metadata
67
+ #
68
+ # You can find out the content type of your object with the <tt>content_type</tt> method:
69
+ #
70
+ # song.content_type
71
+ # # => "audio/mpeg"
72
+ #
73
+ # You can change the content type as well if you like:
74
+ #
75
+ # song.content_type = 'application/pdf'
76
+ # song.store
77
+ #
78
+ # (Keep in mind that due to limitiations in S3's exposed API, the only way to change things like the content_type
79
+ # is to PUT the object onto S3 again. In the case of large files, this will result in fully re-uploading the file.)
80
+ #
81
+ # A bevie of information about an object can be had using the <tt>about</tt> method:
82
+ #
83
+ # pp song.about
84
+ # {"last-modified" => "Sat, 28 Oct 2006 21:29:26 GMT",
85
+ # "content-type" => "binary/octect-stream",
86
+ # "etag" => "\"dc629038ffc674bee6f62eb64ff3a\"",
87
+ # "date" => "Sat, 28 Oct 2006 21:30:41 GMT",
88
+ # "x-amz-request-id" => "B7BC68F55495B1C8",
89
+ # "server" => "AmazonS3",
90
+ # "content-length" => "3418766"}
91
+ #
92
+ # You can get and set metadata for an object:
93
+ #
94
+ # song.metadata
95
+ # # => {}
96
+ # song.metadata[:album] = "A River Ain't Too Much To Love"
97
+ # # => "A River Ain't Too Much To Love"
98
+ # song.metadata[:released] = 2005
99
+ # pp song.metadata
100
+ # {"x-amz-meta-released" => 2005,
101
+ # "x-amz-meta-album" => "A River Ain't Too Much To Love"}
102
+ # song.store
103
+ #
104
+ # That metadata will be saved in S3 and is hence forth available from that object:
105
+ #
106
+ # song = S3Object.find('black-flowers.mp3', 'jukebox')
107
+ # pp song.metadata
108
+ # {"x-amz-meta-released" => "2005",
109
+ # "x-amz-meta-album" => "A River Ain't Too Much To Love"}
110
+ # song.metada[:released]
111
+ # # => "2005"
112
+ # song.metada[:released] = 2006
113
+ # pp song.metada
114
+ # {"x-amz-meta-released" => 2006,
115
+ # "x-amz-meta-album" => "A River Ain't Too Much To Love"}
116
+ class S3Object < Base
117
+ class << self
118
+ # Returns the value of the object with <tt>key</tt> in the specified bucket.
119
+ #
120
+ # === Conditional GET options
121
+ #
122
+ # * <tt>:if_modified_since</tt> - Return the object only if it has been modified since the specified time,
123
+ # otherwise return a 304 (not modified).
124
+ # * <tt>:if_unmodified_since</tt> - Return the object only if it has not been modified since the specified time,
125
+ # otherwise raise PreconditionFailed.
126
+ # * <tt>:if_match</tt> - Return the object only if its entity tag (ETag) is the same as the one specified,
127
+ # otherwise raise PreconditionFailed.
128
+ # * <tt>:if_none_match</tt> - Return the object only if its entity tag (ETag) is different from the one specified,
129
+ # otherwise return a 304 (not modified).
130
+ #
131
+ # === Other options
132
+ # * <tt>:range</tt> - Return only the bytes of the object in the specified range.
133
+ def value(key, bucket = nil, options = {}, &block)
134
+ Value.new(get(path!(bucket, key, options), options, &block))
135
+ end
136
+
137
+ def stream(key, bucket = nil, options = {}, &block)
138
+ value(key, bucket, options) do |response|
139
+ response.read_body(&block)
140
+ end
141
+ end
142
+
143
+ # Returns the object whose key is <tt>name</tt> in the specified bucket. If the specified key does not
144
+ # exist, a NoSuchKey exception will be raised.
145
+ def find(key, bucket = nil)
146
+ # N.B. This is arguably a hack. From what the current S3 API exposes, when you retrieve a bucket, it
147
+ # provides a listing of all the files in that bucket (assuming you haven't limited the scope of what it returns).
148
+ # Each file in the listing contains information about that file. It is from this information that an S3Object is built.
149
+ #
150
+ # If you know the specific file that you want, S3 allows you to make a get request for that specific file and it returns
151
+ # the value of that file in its response body. This response body is used to build an S3Object::Value object.
152
+ # If you want information about that file, you can make a head request and the headers of the response will contain
153
+ # information about that file. There is no way, though, to say, give me the representation of just this given file the same
154
+ # way that it would appear in a bucket listing.
155
+ #
156
+ # When fetching a bucket, you can provide options which narrow the scope of what files should be returned in that listing.
157
+ # Of those options, one is <tt>marker</tt> which is a string and instructs the bucket to return only object's who's key comes after
158
+ # the specified marker according to alphabetic order. Another option is <tt>max-keys</tt> which defaults to 1000 but allows you
159
+ # to dictate how many objects should be returned in the listing. With a combination of <tt>marker</tt> and <tt>max-keys</tt> you can
160
+ # *almost* specify exactly which file you'd like it to return, but <tt>marker</tt> is not inclusive. In other words, if there is a bucket
161
+ # which contains three objects who's keys are respectively 'a', 'b' and 'c', then fetching a bucket listing with marker set to 'b' will only
162
+ # return 'c', not 'b'.
163
+ #
164
+ # Given all that, my hack to fetch a bucket with only one specific file, is to set the marker to the result of calling String#previous on
165
+ # the desired object's key, which functionally makes the key ordered one degree higher than the desired object key according to
166
+ # alphabetic ordering. This is a hack, but it should work around 99% of the time. I can't think of a scenario where it would return
167
+ # something incorrect.
168
+
169
+ # We need to ensure the key doesn't have extended characters but not uri escape it before doing the lookup and comparing since if the object exists,
170
+ # the key on S3 will have been normalized
171
+ key = key.remove_extended unless key.utf8?
172
+ bucket = Bucket.find(bucket_name(bucket), :marker => key.previous, :max_keys => 1)
173
+ # If our heuristic failed, trigger a NoSuchKey exception
174
+ if (object = bucket.objects.first) && object.key == key
175
+ object
176
+ else
177
+ raise NoSuchKey.new("No such key `#{key}'", bucket)
178
+ end
179
+ end
180
+
181
+ # Makes a copy of the object with <tt>key</tt> to <tt>copy_name</tt>.
182
+ def copy(key, copy_key, bucket = nil, options = {})
183
+ bucket = bucket_name(bucket)
184
+ original = open(url_for(key, bucket))
185
+ default_options = {:content_type => original.content_type}
186
+ store(copy_key, original, bucket, default_options.merge(options))
187
+ acl(copy_key, bucket, acl(key, bucket))
188
+ end
189
+
190
+ # Rename the object with key <tt>from</tt> to have key in <tt>to</tt>.
191
+ def rename(from, to, bucket = nil, options = {})
192
+ copy(from, to, bucket, options)
193
+ delete(from, bucket)
194
+ end
195
+
196
+ # Fetch information about the object with <tt>key</tt> from <tt>bucket</tt>. Information includes content type, content length,
197
+ # last modified time, and others.
198
+ #
199
+ # If the specified key does not exist, NoSuchKey is raised.
200
+ def about(key, bucket = nil, options = {})
201
+ response = head(path!(bucket, key, options), options)
202
+ raise NoSuchKey.new("No such key `#{key}'", bucket) if response.code == 404
203
+ About.new(response.headers)
204
+ end
205
+
206
+ # Checks if the object with <tt>key</tt> in <tt>bucket</tt> exists.
207
+ #
208
+ # S3Object.exists? 'kiss.jpg', 'marcel'
209
+ # # => true
210
+ def exists?(key, bucket = nil)
211
+ about(key, bucket)
212
+ true
213
+ rescue NoSuchKey
214
+ false
215
+ end
216
+
217
+ # Delete object with <tt>key</tt> from <tt>bucket</tt>.
218
+ def delete(key, bucket = nil, options = {})
219
+ # A bit confusing. Calling super actually makes an HTTP DELETE request. The delete method is
220
+ # defined in the Base class. It happens to have the same name.
221
+ super(path!(bucket, key, options), options).success?
222
+ end
223
+
224
+ # When storing an object on the S3 servers using S3Object.store, the <tt>data</tt> argument can be a string or an I/O stream.
225
+ # If <tt>data</tt> is an I/O stream it will be read in segments and written to the socket incrementally. This approach
226
+ # may be desirable for very large files so they are not read into memory all at once.
227
+ #
228
+ # # Non streamed upload
229
+ # S3Object.store('greeting.txt', 'hello world!', 'marcel')
230
+ #
231
+ # # Streamed upload
232
+ # S3Object.store('roots.mpeg', open('roots.mpeg'), 'marcel')
233
+ def store(key, data, bucket = nil, options = {})
234
+ validate_key!(key)
235
+ # Must build path before infering content type in case bucket is being used for options
236
+ path = path!(bucket, key, options)
237
+ infer_content_type!(key, options)
238
+
239
+ put(path, options, data) # Don't call .success? on response. We want to get the etag.
240
+ end
241
+ alias_method :create, :store
242
+ alias_method :save, :store
243
+
244
+ # All private objects are accessible via an authenticated GET request to the S3 servers. You can generate an
245
+ # authenticated url for an object like this:
246
+ #
247
+ # S3Object.url_for('beluga_baby.jpg', 'marcel_molina')
248
+ #
249
+ # By default authenticated urls expire 5 minutes after they were generated.
250
+ #
251
+ # Expiration options can be specified either with an absolute time since the epoch with the <tt>:expires</tt> options,
252
+ # or with a number of seconds relative to now with the <tt>:expires_in</tt> options:
253
+ #
254
+ # # Absolute expiration date
255
+ # # (Expires January 18th, 2038)
256
+ # doomsday = Time.mktime(2038, 1, 18).to_i
257
+ # S3Object.url_for('beluga_baby.jpg',
258
+ # 'marcel',
259
+ # :expires => doomsday)
260
+ #
261
+ # # Expiration relative to now specified in seconds
262
+ # # (Expires in 3 hours)
263
+ # S3Object.url_for('beluga_baby.jpg',
264
+ # 'marcel',
265
+ # :expires_in => 60 * 60 * 3)
266
+ #
267
+ # You can specify whether the url should go over SSL with the <tt>:use_ssl</tt> option:
268
+ #
269
+ # # Url will use https protocol
270
+ # S3Object.url_for('beluga_baby.jpg',
271
+ # 'marcel',
272
+ # :use_ssl => true)
273
+ #
274
+ # By default, the ssl settings for the current connection will be used.
275
+ #
276
+ # If you have an object handy, you can use its <tt>url</tt> method with the same objects:
277
+ #
278
+ # song.url(:expires_in => 30)
279
+ #
280
+ # To get an unauthenticated url for the object, such as in the case
281
+ # when the object is publicly readable, pass the
282
+ # <tt>:authenticated</tt> option with a value of <tt>false</tt>.
283
+ #
284
+ # S3Object.url_for('beluga_baby.jpg',
285
+ # 'marcel',
286
+ # :authenticated => false)
287
+ # # => http://s3.amazonaws.com/marcel/beluga_baby.jpg
288
+ def url_for(name, bucket = nil, options = {})
289
+ connection.url_for(path!(bucket, name, options), current_host, options) # Do not normalize options
290
+ end
291
+
292
+ def path!(bucket, name, options = {}) #:nodoc:
293
+ # We're using the second argument for options
294
+ if bucket.is_a?(Hash)
295
+ options.replace(bucket)
296
+ bucket = nil
297
+ end
298
+ self.current_host = bucket_name(bucket)
299
+ "/#{name}"
300
+ end
301
+
302
+ private
303
+
304
+ def validate_key!(key)
305
+ raise InvalidKeyName.new(key) unless key && key.size <= 1024
306
+ end
307
+
308
+ def infer_content_type!(key, options)
309
+ return if options.has_key?(:content_type)
310
+ if mime_type = MIME::Types.type_for(key).first
311
+ options[:content_type] = mime_type.content_type
312
+ end
313
+ end
314
+ end
315
+
316
+ class Value < String #:nodoc:
317
+ attr_reader :response
318
+ def initialize(response)
319
+ super(response.body)
320
+ @response = response
321
+ end
322
+ end
323
+
324
+ class About < Hash #:nodoc:
325
+ def initialize(headers)
326
+ super()
327
+ replace(headers)
328
+ metadata
329
+ end
330
+
331
+ def [](header)
332
+ super(header.to_header)
333
+ end
334
+
335
+ def []=(header, value)
336
+ super(header.to_header, value)
337
+ end
338
+
339
+ def to_headers
340
+ self.merge(metadata.to_headers)
341
+ end
342
+
343
+ def metadata
344
+ Metadata.new(self)
345
+ end
346
+ memoized :metadata
347
+ end
348
+
349
+ class Metadata < Hash #:nodoc:
350
+ HEADER_PREFIX = 'x-amz-meta-'
351
+ SIZE_LIMIT = 2048 # 2 kilobytes
352
+
353
+ def initialize(headers)
354
+ @headers = headers
355
+ super()
356
+ extract_metadata!
357
+ end
358
+
359
+ def []=(header, value)
360
+ super(header_name(header.to_header), value)
361
+ end
362
+
363
+ def [](header)
364
+ super(header_name(header.to_header))
365
+ end
366
+
367
+ def to_headers
368
+ validate!
369
+ self
370
+ end
371
+
372
+ private
373
+ attr_reader :headers
374
+
375
+ def extract_metadata!
376
+ headers.keys.grep(Regexp.new(HEADER_PREFIX)).each do |metadata_header|
377
+ self[metadata_header] = headers.delete(metadata_header)
378
+ end
379
+ end
380
+
381
+ def header_name(name)
382
+ name =~ Regexp.new(HEADER_PREFIX) ? name : [HEADER_PREFIX, name].join
383
+ end
384
+
385
+ def validate!
386
+ invalid_headers = inject([]) do |invalid, (name, value)|
387
+ invalid << name unless valid?(value)
388
+ invalid
389
+ end
390
+
391
+ raise InvalidMetadataValue.new(invalid_headers) unless invalid_headers.empty?
392
+ end
393
+
394
+ def valid?(value)
395
+ value && value.size < SIZE_LIMIT
396
+ end
397
+ end
398
+
399
+ attr_writer :value #:nodoc:
400
+
401
+ # Provides readers and writers for all valid header settings listed in <tt>valid_header_settings</tt>.
402
+ # Subsequent saves to the object after setting any of the valid headers settings will be reflected in
403
+ # information about the object.
404
+ #
405
+ # some_s3_object.content_type
406
+ # => nil
407
+ # some_s3_object.content_type = 'text/plain'
408
+ # => "text/plain"
409
+ # some_s3_object.content_type
410
+ # => "text/plain"
411
+ # some_s3_object.store
412
+ # S3Object.about(some_s3_object.key, some_s3_object.bucket.name)['content-type']
413
+ # => "text/plain"
414
+ include SelectiveAttributeProxy #:nodoc
415
+
416
+ proxy_to :about, :exclusively => false
417
+
418
+ # Initializes a new S3Object.
419
+ def initialize(attributes = {}, &block)
420
+ super
421
+ self.value = attributes.delete(:value)
422
+ self.bucket = attributes.delete(:bucket)
423
+ yield self if block_given?
424
+ end
425
+
426
+ # The current object's bucket. If no bucket has been set, a NoBucketSpecified exception will be raised. For
427
+ # cases where you are not sure if the bucket has been set, you can use the belongs_to_bucket? method.
428
+ def bucket
429
+ @bucket or raise NoBucketSpecified
430
+ end
431
+
432
+ # Sets the bucket that the object belongs to.
433
+ def bucket=(bucket)
434
+ @bucket = bucket
435
+ self
436
+ end
437
+
438
+ # Returns true if the current object has been assigned to a bucket yet. Objects must belong to a bucket before they
439
+ # can be saved onto S3.
440
+ def belongs_to_bucket?
441
+ !@bucket.nil?
442
+ end
443
+ alias_method :orphan?, :belongs_to_bucket?
444
+
445
+ # Returns the key of the object. If the key is not set, a NoKeySpecified exception will be raised. For cases
446
+ # where you are not sure if the key has been set, you can use the key_set? method. Objects must have a key
447
+ # set to be saved onto S3. Objects which have already been saved onto S3 will always have their key set.
448
+ def key
449
+ attributes['key'] or raise NoKeySpecified
450
+ end
451
+
452
+ # Sets the key for the current object.
453
+ def key=(value)
454
+ attributes['key'] = value
455
+ end
456
+
457
+ # Returns true if the current object has had its key set yet. Objects which have already been saved will
458
+ # always return true. This method is useful for objects which have not been saved yet so you know if you
459
+ # need to set the object's key since you can not save an object unless its key has been set.
460
+ #
461
+ # object.store if object.key_set? && object.belongs_to_bucket?
462
+ def key_set?
463
+ !attributes['key'].nil?
464
+ end
465
+
466
+ # Lazily loads object data.
467
+ #
468
+ # Force a reload of the data by passing <tt>:reload</tt>.
469
+ #
470
+ # object.value(:reload)
471
+ #
472
+ # When loading the data for the first time you can optionally yield to a block which will
473
+ # allow you to stream the data in segments.
474
+ #
475
+ # object.value do |segment|
476
+ # send_data segment
477
+ # end
478
+ #
479
+ # The full list of options are listed in the documentation for its class method counter part, S3Object::value.
480
+ def value(options = {}, &block)
481
+ if options.is_a?(Hash)
482
+ reload = !options.empty?
483
+ else
484
+ reload = options
485
+ options = {}
486
+ end
487
+ memoize(reload) do
488
+ self.class.stream(key, bucket.name, options, &block)
489
+ end
490
+ end
491
+
492
+ # Interface to information about the current object. Information is read only, though some of its data
493
+ # can be modified through specific methods, such as content_type and content_type=.
494
+ #
495
+ # pp some_object.about
496
+ # {"last-modified" => "Sat, 28 Oct 2006 21:29:26 GMT",
497
+ # "x-amz-id-2" => "LdcQRk5qLwxJQiZ8OH50HhoyKuqyWoJ67B6i+rOE5MxpjJTWh1kCkL+I0NQzbVQn",
498
+ # "content-type" => "binary/octect-stream",
499
+ # "etag" => "\"dc629038ffc674bee6f62eb68454ff3a\"",
500
+ # "date" => "Sat, 28 Oct 2006 21:30:41 GMT",
501
+ # "x-amz-request-id" => "B7BC68F55495B1C8",
502
+ # "server" => "AmazonS3",
503
+ # "content-length" => "3418766"}
504
+ #
505
+ # some_object.content_type
506
+ # # => "binary/octect-stream"
507
+ # some_object.content_type = 'audio/mpeg'
508
+ # some_object.content_type
509
+ # # => 'audio/mpeg'
510
+ # some_object.store
511
+ def about
512
+ stored? ? self.class.about(key, bucket.name) : About.new
513
+ end
514
+ memoized :about
515
+
516
+ # Interface to viewing and editing metadata for the current object. To be treated like a Hash.
517
+ #
518
+ # some_object.metadata
519
+ # # => {}
520
+ # some_object.metadata[:author] = 'Dave Thomas'
521
+ # some_object.metadata
522
+ # # => {"x-amz-meta-author" => "Dave Thomas"}
523
+ # some_object.metadata[:author]
524
+ # # => "Dave Thomas"
525
+ def metadata
526
+ about.metadata
527
+ end
528
+ memoized :metadata
529
+
530
+ # Saves the current object with the specified <tt>options</tt>. Valid options are listed in the documentation for S3Object::store.
531
+ def store(options = {})
532
+ raise DeletedObject if frozen?
533
+ options = about.to_headers.merge(options) if stored?
534
+ response = self.class.store(key, value, bucket.name, options)
535
+ bucket.update(:stored, self)
536
+ response.success?
537
+ end
538
+ alias_method :create, :store
539
+ alias_method :save, :store
540
+
541
+ # Deletes the current object. Trying to save an object after it has been deleted with
542
+ # raise a DeletedObject exception.
543
+ def delete
544
+ bucket.update(:deleted, self)
545
+ freeze
546
+ self.class.delete(key, bucket.name)
547
+ end
548
+
549
+ # Copies the current object, given it the name <tt>copy_name</tt>. Keep in mind that due to limitations in
550
+ # S3's API, this operation requires retransmitting the entire object to S3.
551
+ def copy(copy_name, options = {})
552
+ self.class.copy(key, copy_name, bucket.name, options)
553
+ end
554
+
555
+ # Rename the current object. Keep in mind that due to limitations in S3's API, this operation requires
556
+ # retransmitting the entire object to S3.
557
+ def rename(to, options = {})
558
+ self.class.rename(key, to, bucket.name, options)
559
+ end
560
+
561
+ def etag(reload = false)
562
+ return nil unless stored?
563
+ memoize(reload) do
564
+ reload ? about(reload)['etag'][1...-1] : attributes['e_tag'][1...-1]
565
+ end
566
+ end
567
+
568
+ # Returns the owner of the current object.
569
+ def owner
570
+ Owner.new(attributes['owner'])
571
+ end
572
+ memoized :owner
573
+
574
+ # Generates an authenticated url for the current object. Accepts the same options as its class method
575
+ # counter part S3Object.url_for.
576
+ def url(options = {})
577
+ self.class.url_for(key, bucket.name, options)
578
+ end
579
+
580
+ # Returns true if the current object has been stored on S3 yet.
581
+ def stored?
582
+ !attributes['e_tag'].nil?
583
+ end
584
+
585
+ def ==(s3object) #:nodoc:
586
+ path == s3object.path
587
+ end
588
+
589
+ def path #:nodoc:
590
+ self.class.path!(
591
+ belongs_to_bucket? ? bucket.name : '(no bucket)',
592
+ key_set? ? key : '(no key)'
593
+ )
594
+ end
595
+
596
+ # Don't dump binary data :)
597
+ def inspect #:nodoc:
598
+ "#<%s:0x%s '%s'>" % [self.class, object_id, path]
599
+ end
600
+
601
+ private
602
+ def proxiable_attribute?(name)
603
+ valid_header_settings.include?(name)
604
+ end
605
+
606
+ def valid_header_settings
607
+ %w(cache_control content_type content_length content_md5 content_disposition content_encoding expires)
608
+ end
609
+ end
610
+ end
611
+ end