1# Copyright (c) 2013 Amazon.com, Inc. or its affiliates.  All Rights Reserved
2#
3# Permission is hereby granted, free of charge, to any person obtaining a
4# copy of this software and associated documentation files (the
5# "Software"), to deal in the Software without restriction, including
6# without limitation the rights to use, copy, modify, merge, publish, dis-
7# tribute, sublicense, and/or sell copies of the Software, and to permit
8# persons to whom the Software is furnished to do so, subject to the fol-
9# lowing conditions:
10#
11# The above copyright notice and this permission notice shall be included
12# in all copies or substantial portions of the Software.
13#
14# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
16# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
17# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20# IN THE SOFTWARE.
21#
22
23def tag(key, value):
24    start = '<%s>' % key
25    end = '</%s>' % key
26    return '%s%s%s' % (start, value, end)
27
28
29class WebsiteConfiguration(object):
30    """
31    Website configuration for a bucket.
32
33    :ivar suffix: Suffix that is appended to a request that is for a
34        "directory" on the website endpoint (e.g. if the suffix is
35        index.html and you make a request to samplebucket/images/
36        the data that is returned will be for the object with the
37        key name images/index.html).  The suffix must not be empty
38        and must not include a slash character.
39
40    :ivar error_key: The object key name to use when a 4xx class error
41        occurs.  This key identifies the page that is returned when
42        such an error occurs.
43
44    :ivar redirect_all_requests_to: Describes the redirect behavior for every
45        request to this bucket's website endpoint. If this value is non None,
46        no other values are considered when configuring the website
47        configuration for the bucket. This is an instance of
48        ``RedirectLocation``.
49
50    :ivar routing_rules: ``RoutingRules`` object which specifies conditions
51        and redirects that apply when the conditions are met.
52
53    """
54
55    def __init__(self, suffix=None, error_key=None,
56                 redirect_all_requests_to=None, routing_rules=None):
57        self.suffix = suffix
58        self.error_key = error_key
59        self.redirect_all_requests_to = redirect_all_requests_to
60        if routing_rules is not None:
61            self.routing_rules = routing_rules
62        else:
63            self.routing_rules = RoutingRules()
64
65    def startElement(self, name, attrs, connection):
66        if name == 'RoutingRules':
67            self.routing_rules = RoutingRules()
68            return self.routing_rules
69        elif name == 'IndexDocument':
70            return _XMLKeyValue([('Suffix', 'suffix')], container=self)
71        elif name == 'ErrorDocument':
72            return _XMLKeyValue([('Key', 'error_key')], container=self)
73
74    def endElement(self, name, value, connection):
75        pass
76
77    def to_xml(self):
78        parts = ['<?xml version="1.0" encoding="UTF-8"?>',
79          '<WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">']
80        if self.suffix is not None:
81            parts.append(tag('IndexDocument', tag('Suffix', self.suffix)))
82        if self.error_key is not None:
83            parts.append(tag('ErrorDocument', tag('Key', self.error_key)))
84        if self.redirect_all_requests_to is not None:
85            parts.append(self.redirect_all_requests_to.to_xml())
86        if self.routing_rules:
87            parts.append(self.routing_rules.to_xml())
88        parts.append('</WebsiteConfiguration>')
89        return ''.join(parts)
90
91
92class _XMLKeyValue(object):
93    def __init__(self, translator, container=None):
94        self.translator = translator
95        if container:
96            self.container = container
97        else:
98            self.container = self
99
100    def startElement(self, name, attrs, connection):
101        pass
102
103    def endElement(self, name, value, connection):
104        for xml_key, attr_name in self.translator:
105            if name == xml_key:
106                setattr(self.container, attr_name, value)
107
108    def to_xml(self):
109        parts = []
110        for xml_key, attr_name in self.translator:
111            content = getattr(self.container, attr_name)
112            if content is not None:
113                parts.append(tag(xml_key, content))
114        return ''.join(parts)
115
116
117class RedirectLocation(_XMLKeyValue):
118    """Specify redirect behavior for every request to a bucket's endpoint.
119
120    :ivar hostname: Name of the host where requests will be redirected.
121
122    :ivar protocol: Protocol to use (http, https) when redirecting requests.
123        The default is the protocol that is used in the original request.
124
125    """
126    TRANSLATOR = [('HostName', 'hostname'),
127                  ('Protocol', 'protocol'),
128                 ]
129
130    def __init__(self, hostname=None, protocol=None):
131        self.hostname = hostname
132        self.protocol = protocol
133        super(RedirectLocation, self).__init__(self.TRANSLATOR)
134
135    def to_xml(self):
136        return tag('RedirectAllRequestsTo',
137            super(RedirectLocation, self).to_xml())
138
139
140class RoutingRules(list):
141
142    def add_rule(self, rule):
143        """
144
145        :type rule: :class:`boto.s3.website.RoutingRule`
146        :param rule: A routing rule.
147
148        :return: This ``RoutingRules`` object is returned,
149            so that it can chain subsequent calls.
150
151        """
152        self.append(rule)
153        return self
154
155    def startElement(self, name, attrs, connection):
156        if name == 'RoutingRule':
157            rule = RoutingRule(Condition(), Redirect())
158            self.add_rule(rule)
159            return rule
160
161    def endElement(self, name, value, connection):
162        pass
163
164    def __repr__(self):
165        return "RoutingRules(%s)" % super(RoutingRules, self).__repr__()
166
167    def to_xml(self):
168        inner_text = []
169        for rule in self:
170            inner_text.append(rule.to_xml())
171        return tag('RoutingRules', '\n'.join(inner_text))
172
173
174class RoutingRule(object):
175    """Represents a single routing rule.
176
177    There are convenience methods to making creating rules
178    more concise::
179
180        rule = RoutingRule.when(key_prefix='foo/').then_redirect('example.com')
181
182    :ivar condition: Describes condition that must be met for the
183        specified redirect to apply.
184
185    :ivar redirect: Specifies redirect behavior.  You can redirect requests to
186        another host, to another page, or with another protocol. In the event
187        of an error, you can can specify a different error code to return.
188
189    """
190    def __init__(self, condition=None, redirect=None):
191        self.condition = condition
192        self.redirect = redirect
193
194    def startElement(self, name, attrs, connection):
195        if name == 'Condition':
196            return self.condition
197        elif name == 'Redirect':
198            return self.redirect
199
200    def endElement(self, name, value, connection):
201        pass
202
203    def to_xml(self):
204        parts = []
205        if self.condition:
206            parts.append(self.condition.to_xml())
207        if self.redirect:
208            parts.append(self.redirect.to_xml())
209        return tag('RoutingRule', '\n'.join(parts))
210
211    @classmethod
212    def when(cls, key_prefix=None, http_error_code=None):
213        return cls(Condition(key_prefix=key_prefix,
214                             http_error_code=http_error_code), None)
215
216    def then_redirect(self, hostname=None, protocol=None, replace_key=None,
217                      replace_key_prefix=None, http_redirect_code=None):
218        self.redirect = Redirect(
219                hostname=hostname, protocol=protocol,
220                replace_key=replace_key,
221                replace_key_prefix=replace_key_prefix,
222                http_redirect_code=http_redirect_code)
223        return self
224
225
226class Condition(_XMLKeyValue):
227    """
228    :ivar key_prefix: The object key name prefix when the redirect is applied.
229        For example, to redirect requests for ExamplePage.html, the key prefix
230        will be ExamplePage.html. To redirect request for all pages with the
231        prefix docs/, the key prefix will be /docs, which identifies all
232        objects in the docs/ folder.
233
234    :ivar http_error_code: The HTTP error code when the redirect is applied. In
235        the event of an error, if the error code equals this value, then the
236        specified redirect is applied.
237
238    """
239    TRANSLATOR = [
240        ('KeyPrefixEquals', 'key_prefix'),
241        ('HttpErrorCodeReturnedEquals', 'http_error_code'),
242        ]
243
244    def __init__(self, key_prefix=None, http_error_code=None):
245        self.key_prefix = key_prefix
246        self.http_error_code = http_error_code
247        super(Condition, self).__init__(self.TRANSLATOR)
248
249    def to_xml(self):
250        return tag('Condition', super(Condition, self).to_xml())
251
252
253class Redirect(_XMLKeyValue):
254    """
255    :ivar hostname: The host name to use in the redirect request.
256
257    :ivar protocol: The protocol to use in the redirect request.  Can be either
258    'http' or 'https'.
259
260    :ivar replace_key: The specific object key to use in the redirect request.
261        For example, redirect request to error.html.
262
263    :ivar replace_key_prefix: The object key prefix to use in the redirect
264        request. For example, to redirect requests for all pages with prefix
265        docs/ (objects in the docs/ folder) to documents/, you can set a
266        condition block with KeyPrefixEquals set to docs/ and in the Redirect
267        set ReplaceKeyPrefixWith to /documents.
268
269    :ivar http_redirect_code: The HTTP redirect code to use on the response.
270
271    """
272
273    TRANSLATOR = [
274        ('Protocol', 'protocol'),
275        ('HostName', 'hostname'),
276        ('ReplaceKeyWith', 'replace_key'),
277        ('ReplaceKeyPrefixWith', 'replace_key_prefix'),
278        ('HttpRedirectCode', 'http_redirect_code'),
279        ]
280
281    def __init__(self, hostname=None, protocol=None, replace_key=None,
282                 replace_key_prefix=None, http_redirect_code=None):
283        self.hostname = hostname
284        self.protocol = protocol
285        self.replace_key = replace_key
286        self.replace_key_prefix = replace_key_prefix
287        self.http_redirect_code = http_redirect_code
288        super(Redirect, self).__init__(self.TRANSLATOR)
289
290    def to_xml(self):
291        return tag('Redirect', super(Redirect, self).to_xml())
292
293
294