Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / common / extensions / docs / server2 / render_servlet.py
1 # Copyright 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 import logging
6 import posixpath
7 import traceback
8
9 from branch_utility import BranchUtility
10 from environment import IsPreviewServer
11 from file_system import FileNotFoundError
12 from redirector import Redirector
13 from servlet import Servlet, Response
14 from special_paths import SITE_VERIFICATION_FILE
15 from third_party.handlebar import Handlebar
16
17
18 def _MakeHeaders(content_type):
19   return {
20     'X-Frame-Options': 'sameorigin',
21     'Content-Type': content_type,
22     'Cache-Control': 'max-age=300',
23   }
24
25
26 class RenderServlet(Servlet):
27   '''Servlet which renders templates.
28   '''
29
30   class Delegate(object):
31     def CreateServerInstance(self):
32       raise NotImplementedError(self.__class__)
33
34   def __init__(self, request, delegate):
35     Servlet.__init__(self, request)
36     self._delegate = delegate
37
38   def Get(self):
39     ''' Render the page for a request.
40     '''
41     path = self._request.path.lstrip('/')
42
43     # The server used to be partitioned based on Chrome channel, but it isn't
44     # anymore. Redirect from the old state.
45     channel_name, path = BranchUtility.SplitChannelNameFromPath(path)
46     if channel_name is not None:
47       return Response.Redirect('/' + path, permanent=True)
48
49     server_instance = self._delegate.CreateServerInstance()
50
51     try:
52       return self._GetSuccessResponse(path, server_instance)
53     except FileNotFoundError:
54       # Find the closest 404.html file and serve that, e.g. if the path is
55       # extensions/manifest/typo.html then first look for
56       # extensions/manifest/404.html, then extensions/404.html, then 404.html.
57       #
58       # Failing that just print 'Not Found' but that should preferrably never
59       # happen, because it would look really bad.
60       path_components = path.split('/')
61       for i in xrange(len(path_components) - 1, -1, -1):
62         try:
63           path_404 = posixpath.join(*(path_components[0:i] + ['404']))
64           response = self._GetSuccessResponse(path_404, server_instance)
65           if response.status != 200:
66             continue
67           return Response.NotFound(response.content.ToString(),
68                                    headers=response.headers)
69         except FileNotFoundError: continue
70       logging.warning('No 404.html found in %s' % path)
71       return Response.NotFound('Not Found', headers=_MakeHeaders('text/plain'))
72
73   def _GetSuccessResponse(self, path, server_instance):
74     '''Returns the Response from trying to render |path| with
75     |server_instance|.  If |path| isn't found then a FileNotFoundError will be
76     raised, such that the only responses that will be returned from this method
77     are Ok and Redirect.
78     '''
79     content_provider, serve_from, path = (
80         server_instance.content_providers.GetByServeFrom(path))
81     assert content_provider, 'No ContentProvider found for %s' % path
82
83     redirect = Redirector(
84         server_instance.compiled_fs_factory,
85         content_provider.file_system).Redirect(self._request.host, path)
86     if redirect is not None:
87       return Response.Redirect(redirect, permanent=False)
88
89     canonical_path = content_provider.GetCanonicalPath(path)
90     if canonical_path != path:
91       redirect_path = posixpath.join(serve_from, canonical_path)
92       return Response.Redirect('/' + redirect_path, permanent=False)
93
94     content_and_type = content_provider.GetContentAndType(path).Get()
95     if not content_and_type.content:
96       logging.error('%s had empty content' % path)
97
98     content = content_and_type.content
99     if isinstance(content, Handlebar):
100       template_content, template_warnings = (
101           server_instance.template_renderer.Render(content, self._request))
102       # HACK: the site verification file (google2ed...) doesn't have a title.
103       content, doc_warnings = server_instance.document_renderer.Render(
104           template_content,
105           path,
106           render_title=path != SITE_VERIFICATION_FILE)
107       warnings = template_warnings + doc_warnings
108       if warnings:
109         sep = '\n - '
110         logging.warning('Rendering %s:%s%s' % (path, sep, sep.join(warnings)))
111
112     content_type = content_and_type.content_type
113     if isinstance(content, unicode):
114       content = content.encode('utf-8')
115       content_type += '; charset=utf-8'
116
117     return Response.Ok(content, headers=_MakeHeaders(content_type))