Launchpad automatic translations update.
[odoo/odoo.git] / addons / document_webdav / redirect.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2010 OpenERP s.a. (<http://openerp.com>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22
23 import logging
24 import urlparse
25 from openerp.service.websrv_lib import FixSendError, HTTPHandler, HttpOptions
26 from openerp.service.http_server import HttpLogHandler
27 _logger = logging.getLogger(__name__)
28 class RedirectHTTPHandler(HttpLogHandler, FixSendError, HttpOptions, HTTPHandler):
29     
30     _HTTP_OPTIONS = { 'Allow': ['OPTIONS', 'GET', 'HEAD', 'PROPFIND'] }
31     redirect_paths = {}
32
33     def __init__(self, request, client_address, server):
34         HTTPHandler.__init__(self,request,client_address,server)
35
36     def send_head(self):
37         """Common code for GET and HEAD commands.
38
39         It will either send the correct redirect (Location) response
40         or a 404.
41         """
42
43         if self.path.endswith('/'):
44             self.path = self.path[:-1]
45         
46         if not self.path:
47             # Return an empty page
48             self.send_response(200)
49             self.send_header("Content-Length", 0)
50             self.end_headers()
51             return None
52         
53         redir_path = self._find_redirect()
54         if redir_path is False:
55             self.send_error(404, "File not found")
56             return None
57         elif redir_path is None:
58             return None
59
60         server_proto = getattr(self.server, 'proto', 'http').lower()
61         addr, port = self.server.server_name, self.server.server_port
62         try:
63             addr, port = self.request.getsockname()
64         except Exception, e:
65             self.log_error("Cannot calculate own address:" , e)
66         
67         if self.headers.has_key('Host'):
68             uparts = list(urlparse.urlparse("%s://%s:%d"% (server_proto, addr,port)))
69             uparts[1] = self.headers['Host']
70             baseuri = urlparse.urlunparse(uparts)
71         else:
72             baseuri = "%s://%s:%d"% (server_proto, addr, port )
73
74
75         location = baseuri + redir_path
76         # relative uri: location = self.redirect_paths[self.path]
77
78         self.send_response(301)
79         self.send_header("Location", location)
80         self.send_header("Content-Length", 0)
81         self.end_headers()
82         # Do we need a Cache-content: header here?
83         _logger.debug("redirecting %s to %s", self.path, redir_path)
84         return None
85
86     def do_PROPFIND(self):
87         self._get_ignore_body()
88         return self.do_HEAD()
89
90     def _find_redirect(self):
91         """ Locate self.path among the redirects we can handle
92         @return The new path, False for 404 or None for already sent error
93         """
94         return self.redirect_paths.get(self.path, False)
95
96     def _get_ignore_body(self):
97         if not self.headers.has_key("content-length"):
98             return
99         max_chunk_size = 10*1024*1024
100         size_remaining = int(self.headers["content-length"])
101         got = ''
102         while size_remaining:
103             chunk_size = min(size_remaining, max_chunk_size)
104             got = self.rfile.read(chunk_size)
105             size_remaining -= len(got)
106
107 #eof
108
109
110 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: