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