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/>.
22 from webob
import Request
, exc
24 from mediagoblin
import routing
, meddleware
, __version__
25 from mediagoblin
.tools
import common
, translate
, template
26 from mediagoblin
.tools
.response
import render_404
27 from mediagoblin
.tools
.theme
import register_themes
28 from mediagoblin
.tools
import request
as mg_request
29 from mediagoblin
.mg_globals
import setup_globals
30 from mediagoblin
.init
.celery
import setup_celery_from_config
31 from mediagoblin
.init
.plugins
import setup_plugins
32 from mediagoblin
.init
import (get_jinja_loader
, get_staticdirector
,
33 setup_global_and_app_config
, setup_workbench
, setup_database
,
34 setup_storage
, setup_beaker_cache
)
35 from mediagoblin
.tools
.pluginapi
import PluginManager
38 _log
= logging
.getLogger(__name__
)
41 class MediaGoblinApp(object):
43 WSGI application of MediaGoblin
45 ... this is the heart of the program!
47 def __init__(self
, config_path
, setup_celery
=True):
49 Initialize the application based on a configuration file.
52 - config_path: path to the configuration file we're opening.
53 - setup_celery: whether or not to setup celery during init.
54 (Note: setting 'celery_setup_elsewhere' also disables
57 _log
.info("GNU MediaGoblin %s main server starting", __version__
)
58 _log
.debug("Using config file %s", config_path
)
63 # Open and setup the config
64 global_config
, app_config
= setup_global_and_app_config(config_path
)
66 ##########################################
67 # Setup other connections / useful objects
68 ##########################################
70 # Set up plugins -- need to do this early so that plugins can
72 _log
.info("Setting up plugins.")
76 self
.connection
, self
.db
= setup_database()
79 self
.theme_registry
, self
.current_theme
= register_themes(app_config
)
81 # Get the template environment
82 self
.template_loader
= get_jinja_loader(
83 app_config
.get('local_templates'),
85 PluginManager().get_template_paths()
88 # Set up storage systems
89 self
.public_store
, self
.queue_store
= setup_storage()
92 self
.routing
= routing
.get_mapper(PluginManager().get_routes())
94 # set up staticdirector tool
95 self
.staticdirector
= get_staticdirector(app_config
)
98 self
.cache
= setup_beaker_cache()
100 # Setup celery, if appropriate
101 if setup_celery
and not app_config
.get('celery_setup_elsewhere'):
102 if os
.environ
.get('CELERY_ALWAYS_EAGER', 'false').lower() == 'true':
103 setup_celery_from_config(
104 app_config
, global_config
,
105 force_celery_always_eager
=True)
107 setup_celery_from_config(app_config
, global_config
)
109 #######################################################
110 # Insert appropriate things into mediagoblin.mg_globals
112 # certain properties need to be accessed globally eg from
113 # validators, etc, which might not access to the request
115 #######################################################
117 setup_globals(app
=self
)
119 # Workbench *currently* only used by celery, so this only
120 # matters in always eager mode :)
123 # instantiate application meddleware
124 self
.meddleware
= [common
.import_component(m
)(self
)
125 for m
in meddleware
.ENABLED_MEDDLEWARE
]
127 def call_backend(self
, environ
, start_response
):
128 request
= Request(environ
)
130 ## Routing / controller loading stuff
131 path_info
= request
.path_info
132 route_match
= self
.routing
.match(path_info
)
134 # By using fcgi, mediagoblin can run under a base path
135 # like /mediagoblin/. request.path_info contains the
136 # path inside mediagoblin. If the something needs the
137 # full path of the current page, that should include
139 # Note: urlgen and routes are fine!
140 request
.full_path
= environ
["SCRIPT_NAME"] + request
.path_info
141 # python-routes uses SCRIPT_NAME. So let's use that too.
142 # The other option would be:
143 # request.full_path = environ["SCRIPT_URL"]
145 # Fix up environ for urlgen
146 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
147 if environ
.get('HTTPS', '').lower() == 'off':
150 ## Attach utilities to the request object
151 request
.matchdict
= route_match
152 request
.urlgen
= routes
.URLGenerator(self
.routing
, environ
)
153 # Do we really want to load this via middleware? Maybe?
154 request
.session
= request
.environ
['beaker.session']
155 # Attach self as request.app
156 # Also attach a few utilities from request.app for convenience?
158 request
.locale
= translate
.get_locale_from_request(request
)
160 request
.template_env
= template
.get_jinja_env(
161 self
.template_loader
, request
.locale
)
163 request
.staticdirect
= self
.staticdirector
165 mg_request
.setup_user_in_request(request
)
168 if route_match
is None:
169 # Try to do see if we have a match with a trailing slash
170 # added and if so, redirect
171 if not path_info
.endswith('/') \
172 and request
.method
== 'GET' \
173 and self
.routing
.match(path_info
+ '/'):
174 new_path_info
= path_info
+ '/'
176 new_path_info
= '%s?%s' % (
177 new_path_info
, urllib
.urlencode(request
.GET
))
178 redirect
= exc
.HTTPFound(location
=new_path_info
)
179 return request
.get_response(redirect
)(environ
, start_response
)
181 # Okay, no matches. 404 time!
182 request
.matchdict
= {} # in case our template expects it
183 return render_404(request
)(environ
, start_response
)
185 # import the controller, or if it's already a callable, call that
186 route_controller
= route_match
['controller']
187 if isinstance(route_controller
, unicode) \
188 or isinstance(route_controller
, str):
189 controller
= common
.import_component(route_match
['controller'])
191 controller
= route_match
['controller']
193 # pass the request through our meddleware classes
194 for m
in self
.meddleware
:
195 response
= m
.process_request(request
, controller
)
196 if response
is not None:
197 return response(environ
, start_response
)
199 request
.start_response
= start_response
201 # get the response from the controller
202 response
= controller(request
)
204 # pass the response through the meddleware
205 for m
in self
.meddleware
[::-1]:
206 m
.process_response(request
, response
)
208 return response(environ
, start_response
)
210 def __call__(self
, environ
, start_response
):
211 ## If more errors happen that look like unclean sessions:
212 # self.db.check_session_clean()
215 return self
.call_backend(environ
, start_response
)
217 # Reset the sql session, so that the next request
218 # gets a fresh session
219 self
.db
.reset_after_request()
222 def paste_app_factory(global_config
, **app_config
):
223 configs
= app_config
['config'].split()
224 mediagoblin_config
= None
225 for config
in configs
:
226 if os
.path
.exists(config
) and os
.access(config
, os
.R_OK
):
227 mediagoblin_config
= config
230 if not mediagoblin_config
:
231 raise IOError("Usable mediagoblin config not found.")
233 mgoblin_app
= MediaGoblinApp(mediagoblin_config
)