- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / common / extensions / docs / server2 / redirector.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 posixpath
6 from urlparse import urlsplit
7
8 from file_system import FileNotFoundError
9
10 class Redirector(object):
11   def __init__(self, compiled_fs_factory, file_system):
12     self._file_system = file_system
13     self._cache = compiled_fs_factory.ForJson(file_system)
14
15   def Redirect(self, host, path):
16     ''' Check if a path should be redirected, first according to host
17     redirection rules, then from rules in redirects.json files.
18
19     Returns the path that should be redirected to, or None if no redirection
20     should occur.
21     '''
22     return self._RedirectOldHosts(host, path) or self._RedirectFromConfig(path)
23
24   def _RedirectFromConfig(self, url):
25     ''' Lookup the redirects configuration file in the directory that contains
26     the requested resource. If no redirection rule is matched, or no
27     configuration file exists, returns None.
28     '''
29     dirname, filename = posixpath.split(url)
30
31     try:
32       rules = self._cache.GetFromFile(
33           posixpath.join(dirname, 'redirects.json')).Get()
34     except FileNotFoundError:
35       return None
36
37     redirect = rules.get(filename)
38     if redirect is None:
39       return None
40     if (redirect.startswith('/') or
41         urlsplit(redirect).scheme in ('http', 'https')):
42       return redirect
43
44     return posixpath.normpath(posixpath.join('/', dirname, redirect))
45
46   def _RedirectOldHosts(self, host, path):
47     ''' Redirect paths from the old code.google.com to the new
48     developer.chrome.com, retaining elements like the channel and https, if
49     used.
50     '''
51     if urlsplit(host).hostname != 'code.google.com':
52       return None
53
54     path = path.split('/')
55     if path and path[0] == 'chrome':
56       path.pop(0)
57
58     return 'https://developer.chrome.com/' + posixpath.join(*path)
59
60   def Cron(self):
61     ''' Load files during a cron run.
62     '''
63     for root, dirs, files in self._file_system.Walk(''):
64       if 'redirects.json' in files:
65         self._cache.GetFromFile(posixpath.join(root, 'redirects.json')).Get()