8027ad8749b99651d7f3d31f17727f65f9f19674
[mediagoblin.git] / mediagoblin / app.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 import os
18 import logging
19
20 from mediagoblin.routing import get_url_map
21 from mediagoblin.tools.routing import endpoint_to_controller
22
23 from werkzeug.wrappers import Request
24 from werkzeug.exceptions import HTTPException
25 from werkzeug.routing import RequestRedirect
26
27 from mediagoblin import meddleware, __version__
28 from mediagoblin.db.util import check_db_up_to_date
29 from mediagoblin.tools import common, session, translate, template
30 from mediagoblin.tools.response import render_http_exception
31 from mediagoblin.tools.theme import register_themes
32 from mediagoblin.tools import request as mg_request
33 from mediagoblin.media_types.tools import media_type_warning
34 from mediagoblin.mg_globals import setup_globals
35 from mediagoblin.init.celery import setup_celery_from_config
36 from mediagoblin.init.plugins import setup_plugins
37 from mediagoblin.init import (get_jinja_loader, get_staticdirector,
38 setup_global_and_app_config, setup_locales, setup_workbench, setup_database,
39 setup_storage)
40 from mediagoblin.tools.pluginapi import PluginManager, hook_transform
41 from mediagoblin.tools.crypto import setup_crypto
42 from mediagoblin.auth.tools import check_auth_enabled, no_auth_logout
43
44
45 _log = logging.getLogger(__name__)
46
47
48 class MediaGoblinApp(object):
49 """
50 WSGI application of MediaGoblin
51
52 ... this is the heart of the program!
53 """
54 def __init__(self, config_path, setup_celery=True):
55 """
56 Initialize the application based on a configuration file.
57
58 Arguments:
59 - config_path: path to the configuration file we're opening.
60 - setup_celery: whether or not to setup celery during init.
61 (Note: setting 'celery_setup_elsewhere' also disables
62 setting up celery.)
63 """
64 _log.info("GNU MediaGoblin %s main server starting", __version__)
65 _log.debug("Using config file %s", config_path)
66 ##############
67 # Setup config
68 ##############
69
70 # Open and setup the config
71 global_config, app_config = setup_global_and_app_config(config_path)
72
73 media_type_warning()
74
75 setup_crypto()
76
77 ##########################################
78 # Setup other connections / useful objects
79 ##########################################
80
81 # Setup Session Manager, not needed in celery
82 self.session_manager = session.SessionManager()
83
84 # load all available locales
85 setup_locales()
86
87 # Set up plugins -- need to do this early so that plugins can
88 # affect startup.
89 _log.info("Setting up plugins.")
90 setup_plugins()
91
92 # Set up the database
93 self.db = setup_database(app_config['run_migrations'])
94
95 # Quit app if need to run dbupdate
96 ## NOTE: This is currently commented out due to session errors..
97 ## We'd like to re-enable!
98 # check_db_up_to_date()
99
100 # Register themes
101 self.theme_registry, self.current_theme = register_themes(app_config)
102
103 # Get the template environment
104 self.template_loader = get_jinja_loader(
105 app_config.get('local_templates'),
106 self.current_theme,
107 PluginManager().get_template_paths()
108 )
109
110 # Check if authentication plugin is enabled and respond accordingly.
111 self.auth = check_auth_enabled()
112 if not self.auth:
113 app_config['allow_comments'] = False
114
115 # Set up storage systems
116 self.public_store, self.queue_store = setup_storage()
117
118 # set up routing
119 self.url_map = get_url_map()
120
121 # set up staticdirector tool
122 self.staticdirector = get_staticdirector(app_config)
123
124 # Setup celery, if appropriate
125 if setup_celery and not app_config.get('celery_setup_elsewhere'):
126 if os.environ.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':
127 setup_celery_from_config(
128 app_config, global_config,
129 force_celery_always_eager=True)
130 else:
131 setup_celery_from_config(app_config, global_config)
132
133 #######################################################
134 # Insert appropriate things into mediagoblin.mg_globals
135 #
136 # certain properties need to be accessed globally eg from
137 # validators, etc, which might not access to the request
138 # object.
139 #######################################################
140
141 setup_globals(app=self)
142
143 # Workbench *currently* only used by celery, so this only
144 # matters in always eager mode :)
145 setup_workbench()
146
147 # instantiate application meddleware
148 self.meddleware = [common.import_component(m)(self)
149 for m in meddleware.ENABLED_MEDDLEWARE]
150
151 def call_backend(self, environ, start_response):
152 request = Request(environ)
153
154 # Compatibility with django, use request.args preferrably
155 request.GET = request.args
156
157 ## Routing / controller loading stuff
158 map_adapter = self.url_map.bind_to_environ(request.environ)
159
160 # By using fcgi, mediagoblin can run under a base path
161 # like /mediagoblin/. request.path_info contains the
162 # path inside mediagoblin. If the something needs the
163 # full path of the current page, that should include
164 # the basepath.
165 # Note: urlgen and routes are fine!
166 request.full_path = environ["SCRIPT_NAME"] + request.path
167 # python-routes uses SCRIPT_NAME. So let's use that too.
168 # The other option would be:
169 # request.full_path = environ["SCRIPT_URL"]
170
171 # Fix up environ for urlgen
172 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
173 if environ.get('HTTPS', '').lower() == 'off':
174 environ.pop('HTTPS')
175
176 ## Attach utilities to the request object
177 # Do we really want to load this via middleware? Maybe?
178 session_manager = self.session_manager
179 request.session = session_manager.load_session_from_cookie(request)
180 # Attach self as request.app
181 # Also attach a few utilities from request.app for convenience?
182 request.app = self
183
184 request.db = self.db
185 request.staticdirect = self.staticdirector
186
187 request.locale = translate.get_locale_from_request(request)
188 request.template_env = template.get_jinja_env(
189 self.template_loader, request.locale)
190
191 def build_proxy(endpoint, **kw):
192 try:
193 qualified = kw.pop('qualified')
194 except KeyError:
195 qualified = False
196
197 return map_adapter.build(
198 endpoint,
199 values=dict(**kw),
200 force_external=qualified)
201
202 request.urlgen = build_proxy
203
204 # Log user out if authentication_disabled
205 no_auth_logout(request)
206
207 mg_request.setup_user_in_request(request)
208
209 request.controller_name = None
210 try:
211 found_rule, url_values = map_adapter.match(return_rule=True)
212 request.matchdict = url_values
213 except RequestRedirect as response:
214 # Deal with 301 responses eg due to missing final slash
215 return response(environ, start_response)
216 except HTTPException as exc:
217 # Stop and render exception
218 return render_http_exception(
219 request, exc,
220 exc.get_description(environ))(environ, start_response)
221
222 controller = endpoint_to_controller(found_rule)
223 # Make a reference to the controller's symbolic name on the request...
224 # used for lazy context modification
225 request.controller_name = found_rule.endpoint
226
227 # pass the request through our meddleware classes
228 try:
229 for m in self.meddleware:
230 response = m.process_request(request, controller)
231 if response is not None:
232 return response(environ, start_response)
233 except HTTPException as e:
234 return render_http_exception(
235 request, e,
236 e.get_description(environ))(environ, start_response)
237
238 request = hook_transform("modify_request", request)
239
240 request.start_response = start_response
241
242 # get the Http response from the controller
243 try:
244 response = controller(request)
245 except HTTPException as e:
246 response = render_http_exception(
247 request, e, e.get_description(environ))
248
249 # pass the response through the meddlewares
250 try:
251 for m in self.meddleware[::-1]:
252 m.process_response(request, response)
253 except HTTPException as e:
254 response = render_http_exception(
255 request, e, e.get_description(environ))
256
257 session_manager.save_session_to_cookie(request.session,
258 request, response)
259
260 return response(environ, start_response)
261
262 def __call__(self, environ, start_response):
263 ## If more errors happen that look like unclean sessions:
264 # self.db.check_session_clean()
265
266 try:
267 return self.call_backend(environ, start_response)
268 finally:
269 # Reset the sql session, so that the next request
270 # gets a fresh session
271 self.db.reset_after_request()
272
273
274 def paste_app_factory(global_config, **app_config):
275 configs = app_config['config'].split()
276 mediagoblin_config = None
277 for config in configs:
278 if os.path.exists(config) and os.access(config, os.R_OK):
279 mediagoblin_config = config
280 break
281
282 if not mediagoblin_config:
283 raise IOError("Usable mediagoblin config not found.")
284
285 mgoblin_app = MediaGoblinApp(mediagoblin_config)
286 mgoblin_app = hook_transform('wrap_wsgi', mgoblin_app)
287
288 return mgoblin_app