Fix i18n in our browser
[mediagoblin.git] / mediagoblin / app.py
CommitLineData
8e1e744d 1# GNU MediaGoblin -- federated, autonomous media hosting
cf29e8a8 2# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
e5572c60
ML
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
571198c9 17import os
ec97c937 18import logging
31a8ff42 19
7742dcc1
JW
20from mediagoblin.routing import url_map, view_functions, add_route
21
f1d06e1d 22from werkzeug.wrappers import Request
7742dcc1 23from werkzeug.exceptions import HTTPException, NotFound
31a8ff42 24
7742dcc1 25from mediagoblin import meddleware, __version__
c0022ecc
CAW
26from mediagoblin.tools import common, translate, template
27from mediagoblin.tools.response import render_404
828fc630 28from mediagoblin.tools.theme import register_themes
152a3bfa 29from mediagoblin.tools import request as mg_request
6e7ce8d1 30from mediagoblin.mg_globals import setup_globals
073b61fe 31from mediagoblin.init.celery import setup_celery_from_config
29b6f917 32from mediagoblin.init.plugins import setup_plugins
50854db0
WKG
33from mediagoblin.init import (get_jinja_loader, get_staticdirector,
34 setup_global_and_app_config, setup_workbench, setup_database,
0533f117 35 setup_storage, setup_beaker_cache)
05e007c1 36from mediagoblin.tools.pluginapi import PluginManager
90e342f9 37
31a8ff42 38
ec97c937
E
39_log = logging.getLogger(__name__)
40
41
8e1e744d 42class MediaGoblinApp(object):
31a8ff42 43 """
3f5cf663
CAW
44 WSGI application of MediaGoblin
45
46 ... this is the heart of the program!
31a8ff42 47 """
3f5cf663
CAW
48 def __init__(self, config_path, setup_celery=True):
49 """
50 Initialize the application based on a configuration file.
51
52 Arguments:
53 - config_path: path to the configuration file we're opening.
54 - setup_celery: whether or not to setup celery during init.
55 (Note: setting 'celery_setup_elsewhere' also disables
56 setting up celery.)
57 """
ec97c937 58 _log.info("GNU MediaGoblin %s main server starting", __version__)
3f369674 59 _log.debug("Using config file %s", config_path)
3f5cf663
CAW
60 ##############
61 # Setup config
62 ##############
63
64 # Open and setup the config
fe289be4 65 global_config, app_config = setup_global_and_app_config(config_path)
3f5cf663
CAW
66
67 ##########################################
68 # Setup other connections / useful objects
69 ##########################################
70
29b6f917
WKG
71 # Set up plugins -- need to do this early so that plugins can
72 # affect startup.
73 _log.info("Setting up plugins.")
74 setup_plugins()
75
3f5cf663 76 # Set up the database
3f4b5e4a 77 self.connection, self.db = setup_database()
ff94114c 78
828fc630 79 # Register themes
975be468 80 self.theme_registry, self.current_theme = register_themes(app_config)
828fc630 81
5afdd7a1 82 # Get the template environment
42ef819c 83 self.template_loader = get_jinja_loader(
3b47da8e 84 app_config.get('local_templates'),
8545dd50 85 self.current_theme,
05e007c1 86 PluginManager().get_template_paths()
8545dd50 87 )
0c8a30e6 88
5afdd7a1 89 # Set up storage systems
dccef262 90 self.public_store, self.queue_store = setup_storage()
5afdd7a1
CAW
91
92 # set up routing
7742dcc1
JW
93 self.url_map = url_map
94
95 for route in PluginManager().get_routes():
d56e8263 96 _log.debug('adding plugin route: {0}'.format(route))
7742dcc1 97 add_route(*route)
31a8ff42 98
582c4d5f 99 # set up staticdirector tool
c85c9dc7 100 self.staticdirector = get_staticdirector(app_config)
3f5cf663 101
0533f117
CAW
102 # set up caching
103 self.cache = setup_beaker_cache()
104
3f5cf663
CAW
105 # Setup celery, if appropriate
106 if setup_celery and not app_config.get('celery_setup_elsewhere'):
d9a31a39 107 if os.environ.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':
3f5cf663
CAW
108 setup_celery_from_config(
109 app_config, global_config,
110 force_celery_always_eager=True)
111 else:
112 setup_celery_from_config(app_config, global_config)
113
114 #######################################################
115 # Insert appropriate things into mediagoblin.mg_globals
116 #
df9809c2
CAW
117 # certain properties need to be accessed globally eg from
118 # validators, etc, which might not access to the request
119 # object.
3f5cf663
CAW
120 #######################################################
121
243c3843 122 setup_globals(app=self)
1fd97db3
CAW
123
124 # Workbench *currently* only used by celery, so this only
125 # matters in always eager mode :)
7664b4db 126 setup_workbench()
df9809c2 127
ce5ae8da
CAW
128 # instantiate application meddleware
129 self.meddleware = [common.import_component(m)(self)
130 for m in meddleware.ENABLED_MEDDLEWARE]
0c8a30e6 131
e824570a 132 def call_backend(self, environ, start_response):
31a8ff42 133 request = Request(environ)
0c8a30e6 134
f1d06e1d
JW
135 ## Compatibility webob -> werkzeug
136 request.GET = request.args
f1d06e1d
JW
137 request.accept = request.accept_mimetypes
138
582c4d5f 139 ## Routing / controller loading stuff
7742dcc1 140 map_adapter = self.url_map.bind_to_environ(request.environ)
31a8ff42 141
05788ef4
E
142 # By using fcgi, mediagoblin can run under a base path
143 # like /mediagoblin/. request.path_info contains the
144 # path inside mediagoblin. If the something needs the
145 # full path of the current page, that should include
146 # the basepath.
147 # Note: urlgen and routes are fine!
f1d06e1d 148 request.full_path = environ["SCRIPT_NAME"] + request.path
05788ef4
E
149 # python-routes uses SCRIPT_NAME. So let's use that too.
150 # The other option would be:
151 # request.full_path = environ["SCRIPT_URL"]
152
871fc591 153 # Fix up environ for urlgen
d23d4b23 154 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
871fc591
E
155 if environ.get('HTTPS', '').lower() == 'off':
156 environ.pop('HTTPS')
157
3d0557bf 158 ## Attach utilities to the request object
3d0557bf
CAW
159 # Do we really want to load this via middleware? Maybe?
160 request.session = request.environ['beaker.session']
161 # Attach self as request.app
162 # Also attach a few utilities from request.app for convenience?
163 request.app = self
0c8a30e6 164
3d0557bf
CAW
165 request.db = self.db
166 request.staticdirect = self.staticdirector
167
1ec7ff2a
JW
168 request.locale = translate.get_locale_from_request(request)
169 request.template_env = template.get_jinja_env(
170 self.template_loader, request.locale)
7742dcc1
JW
171
172 def build_proxy(endpoint, **kw):
173 try:
174 qualified = kw.pop('qualified')
175 except KeyError:
176 qualified = False
177
178 return map_adapter.build(
179 endpoint,
180 values=dict(**kw),
181 force_external=qualified)
182
183 request.urlgen = build_proxy
184
1ec7ff2a
JW
185 mg_request.setup_user_in_request(request)
186
187 try:
188 endpoint, url_values = map_adapter.match()
189 request.matchdict = url_values
190 except NotFound as exc:
191 return render_404(request)(environ, start_response)
192 except HTTPException as exc:
193 # Support legacy webob.exc responses
194 return exc(environ, start_response)
195
7742dcc1 196 view_func = view_functions[endpoint]
31a8ff42 197
1ec7ff2a
JW
198 _log.debug('endpoint: {0} view_func: {1}'.format(
199 endpoint,
200 view_func))
201
7742dcc1
JW
202 # import the endpoint, or if it's already a callable, call that
203 if isinstance(view_func, unicode) \
204 or isinstance(view_func, str):
205 controller = common.import_component(view_func)
8a0d35e7 206 else:
7742dcc1 207 controller = view_func
91cf6738
NY
208
209 # pass the request through our meddleware classes
210 for m in self.meddleware:
211 response = m.process_request(request, controller)
212 if response is not None:
213 return response(environ, start_response)
214
31a8ff42
CAW
215 request.start_response = start_response
216
0c8a30e6
NY
217 # get the response from the controller
218 response = controller(request)
219
ce5ae8da
CAW
220 # pass the response through the meddleware
221 for m in self.meddleware[::-1]:
0c8a30e6
NY
222 m.process_response(request, response)
223
e824570a
E
224 return response(environ, start_response)
225
226 def __call__(self, environ, start_response):
227 ## If more errors happen that look like unclean sessions:
228 # self.db.check_session_clean()
229
2bc8ff0d 230 try:
e824570a
E
231 return self.call_backend(environ, start_response)
232 finally:
233 # Reset the sql session, so that the next request
234 # gets a fresh session
2bc8ff0d 235 self.db.reset_after_request()
31a8ff42
CAW
236
237
5784c4e9 238def paste_app_factory(global_config, **app_config):
91903aa6
CAW
239 configs = app_config['config'].split()
240 mediagoblin_config = None
241 for config in configs:
242 if os.path.exists(config) and os.access(config, os.R_OK):
243 mediagoblin_config = config
244 break
245
246 if not mediagoblin_config:
247 raise IOError("Usable mediagoblin config not found.")
248
249 mgoblin_app = MediaGoblinApp(mediagoblin_config)
b61874b2 250
c4d71564 251 return mgoblin_app