Merge branch 'newlayout' into newlayout-stage
[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 import (get_jinja_loader, get_staticdirector,
31 setup_global_and_app_config, setup_workbench, setup_database,
32 setup_storage, setup_beaker_cache)
33
34
35 _log = logging.getLogger(__name__)
36
37
38 class MediaGoblinApp(object):
39 """
40 WSGI application of MediaGoblin
41
42 ... this is the heart of the program!
43 """
44 def __init__(self, config_path, setup_celery=True):
45 """
46 Initialize the application based on a configuration file.
47
48 Arguments:
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
52 setting up celery.)
53 """
54 _log.info("GNU MediaGoblin %s main server starting", __version__)
55 ##############
56 # Setup config
57 ##############
58
59 # Open and setup the config
60 global_config, app_config = setup_global_and_app_config(config_path)
61
62 ##########################################
63 # Setup other connections / useful objects
64 ##########################################
65
66 # Set up the database
67 self.connection, self.db = setup_database()
68
69 # Get the template environment
70 self.template_loader = get_jinja_loader(
71 app_config.get('local_templates'))
72
73 # Set up storage systems
74 self.public_store, self.queue_store = setup_storage()
75
76 # set up routing
77 self.routing = routing.get_mapper()
78
79 # set up staticdirector tool
80 self.staticdirector = get_staticdirector(app_config)
81
82 # set up caching
83 self.cache = setup_beaker_cache()
84
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)
91 else:
92 setup_celery_from_config(app_config, global_config)
93
94 #######################################################
95 # Insert appropriate things into mediagoblin.mg_globals
96 #
97 # certain properties need to be accessed globally eg from
98 # validators, etc, which might not access to the request
99 # object.
100 #######################################################
101
102 setup_globals(app=self)
103
104 # Workbench *currently* only used by celery, so this only
105 # matters in always eager mode :)
106 setup_workbench()
107
108 # instantiate application meddleware
109 self.meddleware = [common.import_component(m)(self)
110 for m in meddleware.ENABLED_MEDDLEWARE]
111
112 def __call__(self, environ, start_response):
113 request = Request(environ)
114
115 ## Routing / controller loading stuff
116 path_info = request.path_info
117 route_match = self.routing.match(path_info)
118
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
123 # the basepath.
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"]
129
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':
133 environ.pop('HTTPS')
134
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?
142 request.app = self
143 request.locale = translate.get_locale_from_request(request)
144
145 request.template_env = template.get_jinja_env(
146 self.template_loader, request.locale)
147 request.db = self.db
148 request.staticdirect = self.staticdirector
149
150 mg_request.setup_user_in_request(request)
151
152 # No matching page?
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 + '/'
160 if request.GET:
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)
165
166 # Okay, no matches. 404 time!
167 request.matchdict = {} # in case our template expects it
168 return render_404(request)(environ, start_response)
169
170 controller = common.import_component(route_match['controller'])
171
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)
177
178 request.start_response = start_response
179
180 # get the response from the controller
181 response = controller(request)
182
183 # pass the response through the meddleware
184 for m in self.meddleware[::-1]:
185 m.process_response(request, response)
186
187 # Reset the sql session, so that the next request
188 # gets a fresh session
189 try:
190 self.db.reset_after_request()
191 except TypeError:
192 # We're still on mongo
193 pass
194
195 return response(environ, start_response)
196
197
198 def paste_app_factory(global_config, **app_config):
199 configs = app_config['config'].split()
200 mediagoblin_config = None
201 for config in configs:
202 if os.path.exists(config) and os.access(config, os.R_OK):
203 mediagoblin_config = config
204 break
205
206 if not mediagoblin_config:
207 raise IOError("Usable mediagoblin config not found.")
208
209 mgoblin_app = MediaGoblinApp(mediagoblin_config)
210
211 return mgoblin_app