523b930289b77d9de2cb648fad998d6829244f3f
[mediagoblin.git] / mediagoblin / app.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 Free Software Foundation, Inc
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
20 import routes
21 from webob import Request, exc
22
23 from mediagoblin import routing, util, storage, staticdirect
24 from mediagoblin.init.config import (
25 read_mediagoblin_config, generate_validation_report)
26 from mediagoblin.db.open import setup_connection_and_db_from_config
27 from mediagoblin.db.util import MigrationManager
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
31 from mediagoblin.workbench import WorkbenchManager
32
33
34 class Error(Exception): pass
35 class ImproperlyConfigured(Error): pass
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 ##############
55 # Setup config
56 ##############
57
58 # Open and setup the config
59 global_config, validation_result = read_mediagoblin_config(config_path)
60 app_config = global_config['mediagoblin']
61 # report errors if necessary
62 validation_report = generate_validation_report(
63 global_config, validation_result)
64 if validation_report:
65 raise ImproperlyConfigured(validation_report)
66
67 ##########################################
68 # Setup other connections / useful objects
69 ##########################################
70
71 # Set up the database
72 self.connection, self.db = setup_connection_and_db_from_config(
73 app_config)
74
75 # Init the migration number if necessary
76 migration_manager = MigrationManager(self.db)
77 migration_manager.install_migration_version_if_missing()
78
79 # Tiny hack to warn user if our migration is out of date
80 if not migration_manager.database_at_latest_migration():
81 print (
82 "*WARNING:* Your migrations are out of date, "
83 "maybe run ./bin/gmg migrate?")
84
85 # Get the template environment
86 self.template_loader = get_jinja_loader(
87 app_config.get('user_template_path'))
88
89 # Set up storage systems
90 self.public_store = storage.storage_system_from_config(
91 app_config, 'publicstore')
92 self.queue_store = storage.storage_system_from_config(
93 app_config, 'queuestore')
94
95 # set up routing
96 self.routing = routing.get_mapper()
97
98 # set up staticdirector tool
99 if app_config.has_key('direct_remote_path'):
100 self.staticdirector = staticdirect.RemoteStaticDirect(
101 app_config['direct_remote_path'].strip())
102 elif app_config.has_key('direct_remote_paths'):
103 direct_remote_path_lines = app_config[
104 'direct_remote_paths'].strip().splitlines()
105 self.staticdirector = staticdirect.MultiRemoteStaticDirect(
106 dict([line.strip().split(' ', 1)
107 for line in direct_remote_path_lines]))
108 else:
109 raise ImproperlyConfigured(
110 "One of direct_remote_path or "
111 "direct_remote_paths must be provided")
112
113 # Setup celery, if appropriate
114 if setup_celery and not app_config.get('celery_setup_elsewhere'):
115 if os.environ.get('CELERY_ALWAYS_EAGER'):
116 setup_celery_from_config(
117 app_config, global_config,
118 force_celery_always_eager=True)
119 else:
120 setup_celery_from_config(app_config, global_config)
121
122 #######################################################
123 # Insert appropriate things into mediagoblin.mg_globals
124 #
125 # certain properties need to be accessed globally eg from
126 # validators, etc, which might not access to the request
127 # object.
128 #######################################################
129
130 setup_globals(
131 app_config=app_config,
132 global_config=global_config,
133
134 # TODO: No need to set these two up as globals, we could
135 # just read them out of mg_globals.app_config
136 email_sender_address=app_config['email_sender_address'],
137 email_debug_mode=app_config['email_debug_mode'],
138
139 # Actual, useful to everyone objects
140 app=self,
141 db_connection=self.connection,
142 database=self.db,
143 public_store=self.public_store,
144 queue_store=self.queue_store,
145 workbench_manager=WorkbenchManager(app_config['workbench_path']))
146
147 def __call__(self, environ, start_response):
148 request = Request(environ)
149 path_info = request.path_info
150
151 ## Routing / controller loading stuff
152 route_match = self.routing.match(path_info)
153
154 # No matching page?
155 if route_match is None:
156 # Try to do see if we have a match with a trailing slash
157 # added and if so, redirect
158 if not path_info.endswith('/') \
159 and request.method == 'GET' \
160 and self.routing.match(path_info + '/'):
161 new_path_info = path_info + '/'
162 if request.GET:
163 new_path_info = '%s?%s' % (
164 new_path_info, urllib.urlencode(request.GET))
165 redirect = exc.HTTPFound(location=new_path_info)
166 return request.get_response(redirect)(environ, start_response)
167
168 # Okay, no matches. 404 time!
169 return exc.HTTPNotFound()(environ, start_response)
170
171 controller = util.import_component(route_match['controller'])
172 request.start_response = start_response
173
174 ## Attach utilities to the request object
175 request.matchdict = route_match
176 request.urlgen = routes.URLGenerator(self.routing, environ)
177 # Do we really want to load this via middleware? Maybe?
178 request.session = request.environ['beaker.session']
179 # Attach self as request.app
180 # Also attach a few utilities from request.app for convenience?
181 request.app = self
182 request.locale = util.get_locale_from_request(request)
183
184 request.template_env = util.get_jinja_env(
185 self.template_loader, request.locale)
186 request.db = self.db
187 request.staticdirect = self.staticdirector
188
189 util.setup_user_in_request(request)
190
191 return controller(request)(environ, start_response)
192
193
194 def paste_app_factory(global_config, **app_config):
195 mgoblin_app = MediaGoblinApp(app_config['config'])
196
197 return mgoblin_app