Merge branch 'master' into sqlmigrate
[mediagoblin.git] / mediagoblin / staticdirect.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 ####################################
18 # Staticdirect infrastructure.
19 # Borrowed largely from cc.engine
20 # by Chris Webber & Creative Commons
21 #
22 # This needs documentation!
23 ####################################
24
25 import pkg_resources
26 import logging
27
28 _log = logging.getLogger(__name__)
29
30
31 class StaticDirect(object):
32 def __init__(self):
33 self.cache = {}
34
35 def __call__(self, filepath):
36 if filepath in self.cache:
37 return self.cache[filepath]
38
39 if not pkg_resources.resource_exists('mediagoblin',
40 'static' + filepath):
41 _log.info("StaticDirect resource %r not found locally",
42 filepath)
43 static_direction = self.cache[filepath] = self.get(filepath)
44 return static_direction
45
46 def get(self, filepath):
47 # should be implemented by the individual staticdirector
48 pass
49
50
51 class RemoteStaticDirect(StaticDirect):
52 def __init__(self, remotepath):
53 StaticDirect.__init__(self)
54 self.remotepath = remotepath.rstrip('/')
55
56 def get(self, filepath):
57 return '%s/%s' % (
58 self.remotepath, filepath.lstrip('/'))
59
60
61 class MultiRemoteStaticDirect(StaticDirect):
62 """
63 For whene separate sections of the static data is served under
64 separate urls.
65 """
66 def __init__(self, remotepaths):
67 StaticDirect.__init__(self)
68 self.remotepaths = remotepaths
69
70 def get(self, filepath):
71 section, rest = filepath.strip('/').split('/', 1)
72
73 return '%s/%s' % (
74 self.remotepaths[section].rstrip('/'),
75 rest.lstrip('/'))