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
42 _log
= logging
.getLogger(__name__
)
45 class MediaGoblinApp(object):
47 WSGI application of MediaGoblin
49 ... this is the heart of the program!
51 def __init__(self
, config_path
, setup_celery
=True):
53 Initialize the application based on a configuration file.
56 - config_path: path to the configuration file we're opening.
57 - setup_celery: whether or not to setup celery during init.
58 (Note: setting 'celery_setup_elsewhere' also disables
61 _log
.info("GNU MediaGoblin %s main server starting", __version__
)
62 _log
.debug("Using config file %s", config_path
)
67 # Open and setup the config
68 global_config
, app_config
= setup_global_and_app_config(config_path
)
72 ##########################################
73 # Setup other connections / useful objects
74 ##########################################
76 # Setup Session Manager, not needed in celery
77 self
.session_manager
= session
.SessionManager()
79 # load all available locales
82 # Set up plugins -- need to do this early so that plugins can
84 _log
.info("Setting up plugins.")
88 self
.db
= setup_database()
91 self
.theme_registry
, self
.current_theme
= register_themes(app_config
)
93 # Get the template environment
94 self
.template_loader
= get_jinja_loader(
95 app_config
.get('local_templates'),
97 PluginManager().get_template_paths()
100 # Set up storage systems
101 self
.public_store
, self
.queue_store
= setup_storage()
104 self
.url_map
= get_url_map()
106 # set up staticdirector tool
107 self
.staticdirector
= get_staticdirector(app_config
)
109 # Setup celery, if appropriate
110 if setup_celery
and not app_config
.get('celery_setup_elsewhere'):
111 if os
.environ
.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':
112 setup_celery_from_config(
113 app_config
, global_config
,
114 force_celery_always_eager
=True)
116 setup_celery_from_config(app_config
, global_config
)
118 #######################################################
119 # Insert appropriate things into mediagoblin.mg_globals
121 # certain properties need to be accessed globally eg from
122 # validators, etc, which might not access to the request
124 #######################################################
126 setup_globals(app
=self
)
128 # Workbench *currently* only used by celery, so this only
129 # matters in always eager mode :)
132 # instantiate application meddleware
133 self
.meddleware
= [common
.import_component(m
)(self
)
134 for m
in meddleware
.ENABLED_MEDDLEWARE
]
136 def call_backend(self
, environ
, start_response
):
137 request
= Request(environ
)
139 # Compatibility with django, use request.args preferrably
140 request
.GET
= request
.args
142 ## Routing / controller loading stuff
143 map_adapter
= self
.url_map
.bind_to_environ(request
.environ
)
145 # By using fcgi, mediagoblin can run under a base path
146 # like /mediagoblin/. request.path_info contains the
147 # path inside mediagoblin. If the something needs the
148 # full path of the current page, that should include
150 # Note: urlgen and routes are fine!
151 request
.full_path
= environ
["SCRIPT_NAME"] + request
.path
152 # python-routes uses SCRIPT_NAME. So let's use that too.
153 # The other option would be:
154 # request.full_path = environ["SCRIPT_URL"]
156 # Fix up environ for urlgen
157 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
158 if environ
.get('HTTPS', '').lower() == 'off':
161 ## Attach utilities to the request object
162 # Do we really want to load this via middleware? Maybe?
163 session_manager
= self
.session_manager
164 request
.session
= session_manager
.load_session_from_cookie(request
)
165 # Attach self as request.app
166 # Also attach a few utilities from request.app for convenience?
170 request
.staticdirect
= self
.staticdirector
172 request
.locale
= translate
.get_locale_from_request(request
)
173 request
.template_env
= template
.get_jinja_env(
174 self
.template_loader
, request
.locale
)
176 def build_proxy(endpoint
, **kw
):
178 qualified
= kw
.pop('qualified')
182 return map_adapter
.build(
185 force_external
=qualified
)
187 request
.urlgen
= build_proxy
189 mg_request
.setup_user_in_request(request
)
191 request
.controller_name
= None
193 found_rule
, url_values
= map_adapter
.match(return_rule
=True)
194 request
.matchdict
= url_values
195 except RequestRedirect
as response
:
196 # Deal with 301 responses eg due to missing final slash
197 return response(environ
, start_response
)
198 except HTTPException
as exc
:
199 # Stop and render exception
200 return render_http_exception(
202 exc
.get_description(environ
))(environ
, start_response
)
204 controller
= endpoint_to_controller(found_rule
)
205 # Make a reference to the controller's symbolic name on the request...
206 # used for lazy context modification
207 request
.controller_name
= found_rule
.endpoint
209 # pass the request through our meddleware classes
211 for m
in self
.meddleware
:
212 response
= m
.process_request(request
, controller
)
213 if response
is not None:
214 return response(environ
, start_response
)
215 except HTTPException
as e
:
216 return render_http_exception(
218 e
.get_description(environ
))(environ
, start_response
)
220 request
.start_response
= start_response
222 # get the Http response from the controller
224 response
= controller(request
)
225 except HTTPException
as e
:
226 response
= render_http_exception(
227 request
, e
, e
.get_description(environ
))
229 # pass the response through the meddlewares
231 for m
in self
.meddleware
[::-1]:
232 m
.process_response(request
, response
)
233 except HTTPException
as e
:
234 response
= render_http_exception(
235 request
, e
, e
.get_description(environ
))
237 session_manager
.save_session_to_cookie(request
.session
,
240 return response(environ
, start_response
)
242 def __call__(self
, environ
, start_response
):
243 ## If more errors happen that look like unclean sessions:
244 # self.db.check_session_clean()
247 return self
.call_backend(environ
, start_response
)
249 # Reset the sql session, so that the next request
250 # gets a fresh session
251 self
.db
.reset_after_request()
254 def paste_app_factory(global_config
, **app_config
):
255 configs
= app_config
['config'].split()
256 mediagoblin_config
= None
257 for config
in configs
:
258 if os
.path
.exists(config
) and os
.access(config
, os
.R_OK
):
259 mediagoblin_config
= config
262 if not mediagoblin_config
:
263 raise IOError("Usable mediagoblin config not found.")
265 mgoblin_app
= MediaGoblinApp(mediagoblin_config
)
266 mgoblin_app
= hook_transform('wrap_wsgi', mgoblin_app
)