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
import request
as mg_request
28 from mediagoblin
.mg_globals
import setup_globals
29 from mediagoblin
.init
.celery
import setup_celery_from_config
30 from mediagoblin
.init
import (get_jinja_loader
, get_staticdirector
,
31 setup_global_and_app_config
, setup_workbench
, setup_database
,
32 setup_storage
, setup_beaker_cache
)
35 _log
= logging
.getLogger(__name__
)
38 class MediaGoblinApp(object):
40 WSGI application of MediaGoblin
42 ... this is the heart of the program!
44 def __init__(self
, config_path
, setup_celery
=True):
46 Initialize the application based on a configuration file.
49 - config_path: path to the configuration file we're opening.
50 - setup_celery: whether or not to setup celery during init.
51 (Note: setting 'celery_setup_elsewhere' also disables
54 _log
.info("GNU MediaGoblin %s main server starting", __version__
)
59 # Open and setup the config
60 global_config
, app_config
= setup_global_and_app_config(config_path
)
62 ##########################################
63 # Setup other connections / useful objects
64 ##########################################
67 self
.connection
, self
.db
= setup_database()
69 # Get the template environment
70 self
.template_loader
= get_jinja_loader(
71 app_config
.get('local_templates'))
73 # Set up storage systems
74 self
.public_store
, self
.queue_store
= setup_storage()
77 self
.routing
= routing
.get_mapper()
79 # set up staticdirector tool
80 self
.staticdirector
= get_staticdirector(app_config
)
83 self
.cache
= setup_beaker_cache()
85 # Setup celery, if appropriate
86 if setup_celery
and not app_config
.get('celery_setup_elsewhere'):
87 if os
.environ
.get('CELERY_ALWAYS_EAGER'):
88 setup_celery_from_config(
89 app_config
, global_config
,
90 force_celery_always_eager
=True)
92 setup_celery_from_config(app_config
, global_config
)
94 #######################################################
95 # Insert appropriate things into mediagoblin.mg_globals
97 # certain properties need to be accessed globally eg from
98 # validators, etc, which might not access to the request
100 #######################################################
102 setup_globals(app
=self
)
104 # Workbench *currently* only used by celery, so this only
105 # matters in always eager mode :)
108 # instantiate application meddleware
109 self
.meddleware
= [common
.import_component(m
)(self
)
110 for m
in meddleware
.ENABLED_MEDDLEWARE
]
112 def call_backend(self
, environ
, start_response
):
113 request
= Request(environ
)
115 ## Routing / controller loading stuff
116 path_info
= request
.path_info
117 route_match
= self
.routing
.match(path_info
)
119 # By using fcgi, mediagoblin can run under a base path
120 # like /mediagoblin/. request.path_info contains the
121 # path inside mediagoblin. If the something needs the
122 # full path of the current page, that should include
124 # Note: urlgen and routes are fine!
125 request
.full_path
= environ
["SCRIPT_NAME"] + request
.path_info
126 # python-routes uses SCRIPT_NAME. So let's use that too.
127 # The other option would be:
128 # request.full_path = environ["SCRIPT_URL"]
130 # Fix up environ for urlgen
131 # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
132 if environ
.get('HTTPS', '').lower() == 'off':
135 ## Attach utilities to the request object
136 request
.matchdict
= route_match
137 request
.urlgen
= routes
.URLGenerator(self
.routing
, environ
)
138 # Do we really want to load this via middleware? Maybe?
139 request
.session
= request
.environ
['beaker.session']
140 # Attach self as request.app
141 # Also attach a few utilities from request.app for convenience?
143 request
.locale
= translate
.get_locale_from_request(request
)
145 request
.template_env
= template
.get_jinja_env(
146 self
.template_loader
, request
.locale
)
148 request
.staticdirect
= self
.staticdirector
150 mg_request
.setup_user_in_request(request
)
153 if route_match
is None:
154 # Try to do see if we have a match with a trailing slash
155 # added and if so, redirect
156 if not path_info
.endswith('/') \
157 and request
.method
== 'GET' \
158 and self
.routing
.match(path_info
+ '/'):
159 new_path_info
= path_info
+ '/'
161 new_path_info
= '%s?%s' % (
162 new_path_info
, urllib
.urlencode(request
.GET
))
163 redirect
= exc
.HTTPFound(location
=new_path_info
)
164 return request
.get_response(redirect
)(environ
, start_response
)
166 # Okay, no matches. 404 time!
167 request
.matchdict
= {} # in case our template expects it
168 return render_404(request
)(environ
, start_response
)
170 controller
= common
.import_component(route_match
['controller'])
172 # pass the request through our meddleware classes
173 for m
in self
.meddleware
:
174 response
= m
.process_request(request
, controller
)
175 if response
is not None:
176 return response(environ
, start_response
)
178 request
.start_response
= start_response
180 # get the response from the controller
181 response
= controller(request
)
183 # pass the response through the meddleware
184 for m
in self
.meddleware
[::-1]:
185 m
.process_response(request
, response
)
187 return response(environ
, start_response
)
189 def __call__(self
, environ
, start_response
):
190 ## If more errors happen that look like unclean sessions:
191 # self.db.check_session_clean()
194 return self
.call_backend(environ
, start_response
)
196 # Reset the sql session, so that the next request
197 # gets a fresh session
198 self
.db
.reset_after_request()
201 def paste_app_factory(global_config
, **app_config
):
202 configs
= app_config
['config'].split()
203 mediagoblin_config
= None
204 for config
in configs
:
205 if os
.path
.exists(config
) and os
.access(config
, os
.R_OK
):
206 mediagoblin_config
= config
209 if not mediagoblin_config
:
210 raise IOError("Usable mediagoblin config not found.")
212 mgoblin_app
= MediaGoblinApp(mediagoblin_config
)