1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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.
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.
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/>.
20 from mediagoblin
.routing
import get_url_map
21 from mediagoblin
.tools
.routing
import endpoint_to_controller
23 from werkzeug
.wrappers
import Request
24 from werkzeug
.exceptions
import HTTPException
25 from werkzeug
.routing
import RequestRedirect
27 from mediagoblin
import meddleware
, __version__
28 from mediagoblin
.tools
import common
, session
, translate
, template
29 from mediagoblin
.tools
.response
import render_http_exception
30 from mediagoblin
.tools
.theme
import register_themes
31 from mediagoblin
.tools
import request
as mg_request
32 from mediagoblin
.mg_globals
import setup_globals
33 from mediagoblin
.init
.celery
import setup_celery_from_config
34 from mediagoblin
.init
.plugins
import setup_plugins
35 from mediagoblin
.init
import (get_jinja_loader
, get_staticdirector
,
36 setup_global_and_app_config
, setup_locales
, setup_workbench
, setup_database
,
38 from mediagoblin
.tools
.pluginapi
import PluginManager
, hook_transform
39 from mediagoblin
.tools
.crypto
import setup_crypto
40 from mediagoblin
.auth
.tools
import check_auth_enabled
, no_auth_logout
43 _log
= logging
.getLogger(__name__
)
46 class MediaGoblinApp(object):
48 WSGI application of MediaGoblin
50 ... this is the heart of the program!
52 def __init__(self
, config_path
, setup_celery
=True):
54 Initialize the application based on a configuration file.
57 - config_path: path to the configuration file we're opening.
58 - setup_celery: whether or not to setup celery during init.
59 (Note: setting 'celery_setup_elsewhere' also disables
62 _log
.info("GNU MediaGoblin %s main server starting", __version__
)
63 _log
.debug("Using config file %s", config_path
)
68 # Open and setup the config
69 global_config
, app_config
= setup_global_and_app_config(config_path
)
73 ##########################################
74 # Setup other connections / useful objects
75 ##########################################
77 # Setup Session Manager, not needed in celery
78 self
.session_manager
= session
.SessionManager()
80 # load all available locales
83 # Set up plugins -- need to do this early so that plugins can
85 _log
.info("Setting up plugins.")
89 self
.db
= setup_database()
92 self
.theme_registry
, self
.current_theme
= register_themes(app_config
)
94 # Get the template environment
95 self
.template_loader
= get_jinja_loader(
96 app_config
.get('local_templates'),
98 PluginManager().get_template_paths()
101 # Check if authentication plugin is enabled and respond accordingly.
102 self
.auth
= check_auth_enabled()
104 # Set up storage systems
105 self
.public_store
, self
.queue_store
= setup_storage()
108 self
.url_map
= get_url_map()
110 # set up staticdirector tool
111 self
.staticdirector
= get_staticdirector(app_config
)
113 # Setup celery, if appropriate
114 if setup_celery
and not app_config
.get('celery_setup_elsewhere'):
115 if os
.environ
.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':
116 setup_celery_from_config(
117 app_config
, global_config
,
118 force_celery_always_eager
=True)
120 setup_celery_from_config(app_config
, global_config
)
122 #######################################################
123 # Insert appropriate things into mediagoblin.mg_globals
125 # certain properties need to be accessed globally eg from
126 # validators, etc, which might not access to the request
128 #######################################################
130 setup_globals(app
=self
)
132 # Workbench *currently* only used by celery, so this only
133 # matters in always eager mode :)
136 # instantiate application meddleware
137 self
.meddleware
= [common
.import_component(m
)(self
)
138 for m
in meddleware
.ENABLED_MEDDLEWARE
]
140 def call_backend(self
, environ
, start_response
):
141 request
= Request(environ
)
143 # Compatibility with django, use request.args preferrably
144 request
.GET
= request
.args
146 ## Routing / controller loading stuff
147 map_adapter
= self
.url_map
.bind_to_environ(request
.environ
)
149 # By using fcgi, mediagoblin can run under a base path
150 # like /mediagoblin/. request.path_info contains the
151 # path inside mediagoblin. If the something needs the
152 # full path of the current page, that should include
154 # Note: urlgen and routes are fine!
155 request
.full_path
= environ
["SCRIPT_NAME"] + request
.path
156 # python-routes uses SCRIPT_NAME. So let's use that too.
157 # The other option would be:
158 # request.full_path = environ["SCRIPT_URL"]
160 # Fix up environ for urlgen
161 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
162 if environ
.get('HTTPS', '').lower() == 'off':
165 ## Attach utilities to the request object
166 # Do we really want to load this via middleware? Maybe?
167 session_manager
= self
.session_manager
168 request
.session
= session_manager
.load_session_from_cookie(request
)
169 # Attach self as request.app
170 # Also attach a few utilities from request.app for convenience?
174 request
.staticdirect
= self
.staticdirector
176 request
.locale
= translate
.get_locale_from_request(request
)
177 request
.template_env
= template
.get_jinja_env(
178 self
.template_loader
, request
.locale
)
180 def build_proxy(endpoint
, **kw
):
182 qualified
= kw
.pop('qualified')
186 return map_adapter
.build(
189 force_external
=qualified
)
191 request
.urlgen
= build_proxy
193 mg_request
.setup_user_in_request(request
)
195 # Log user out if in no_auth mode
196 no_auth_logout(request
)
198 request
.controller_name
= None
200 found_rule
, url_values
= map_adapter
.match(return_rule
=True)
201 request
.matchdict
= url_values
202 except RequestRedirect
as response
:
203 # Deal with 301 responses eg due to missing final slash
204 return response(environ
, start_response
)
205 except HTTPException
as exc
:
206 # Stop and render exception
207 return render_http_exception(
209 exc
.get_description(environ
))(environ
, start_response
)
211 controller
= endpoint_to_controller(found_rule
)
212 # Make a reference to the controller's symbolic name on the request...
213 # used for lazy context modification
214 request
.controller_name
= found_rule
.endpoint
216 # pass the request through our meddleware classes
218 for m
in self
.meddleware
:
219 response
= m
.process_request(request
, controller
)
220 if response
is not None:
221 return response(environ
, start_response
)
222 except HTTPException
as e
:
223 return render_http_exception(
225 e
.get_description(environ
))(environ
, start_response
)
227 request
.start_response
= start_response
229 # get the Http response from the controller
231 response
= controller(request
)
232 except HTTPException
as e
:
233 response
= render_http_exception(
234 request
, e
, e
.get_description(environ
))
236 # pass the response through the meddlewares
238 for m
in self
.meddleware
[::-1]:
239 m
.process_response(request
, response
)
240 except HTTPException
as e
:
241 response
= render_http_exception(
242 request
, e
, e
.get_description(environ
))
244 session_manager
.save_session_to_cookie(request
.session
,
247 return response(environ
, start_response
)
249 def __call__(self
, environ
, start_response
):
250 ## If more errors happen that look like unclean sessions:
251 # self.db.check_session_clean()
254 return self
.call_backend(environ
, start_response
)
256 # Reset the sql session, so that the next request
257 # gets a fresh session
258 self
.db
.reset_after_request()
261 def paste_app_factory(global_config
, **app_config
):
262 configs
= app_config
['config'].split()
263 mediagoblin_config
= None
264 for config
in configs
:
265 if os
.path
.exists(config
) and os
.access(config
, os
.R_OK
):
266 mediagoblin_config
= config
269 if not mediagoblin_config
:
270 raise IOError("Usable mediagoblin config not found.")
272 mgoblin_app
= MediaGoblinApp(mediagoblin_config
)
273 mgoblin_app
= hook_transform('wrap_wsgi', mgoblin_app
)