Parent: [c2310a] (diff)

Child: [c98680] (diff)

Download this file

app_globals.py    353 lines (295 with data), 11.6 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# -*- coding: utf-8 -*-
"""The application's Globals object"""
__all__ = ['Globals']
import logging
import socket
import cgi
import json
import shlex
import datetime
from urllib import urlencode
from ConfigParser import RawConfigParser
from collections import defaultdict
import pkg_resources
import pysolr
import oembed
import markdown
import pygments
import pygments.lexers
import pygments.formatters
import pygments.util
import webob.exc
from tg import config, session
from pylons import c, request
from paste.deploy.converters import asbool, asint
from pypeline.markup import markup as pypeline_markup
import ew as ew_core
import ew.jinja2_ew as ew
import allura.tasks.event_tasks
from allura import model as M
from allura.lib.markdown_extensions import ForgeExtension
from allura.lib import gravatar, plugin
from allura.lib import helpers as h
from allura.lib.widgets import analytics
from allura.lib.security import Credentials
from allura.lib.async import Connection, MockAMQ
log = logging.getLogger(__name__)
class Globals(object):
"""Container for objects available throughout the life of the application.
One instance of Globals is created during application initialization and
is available during requests via the 'app_globals' variable.
"""
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
if self.__shared_state: return
self.allura_templates = pkg_resources.resource_filename('allura', 'templates')
# Setup SOLR
self.solr_server = config.get('solr.server')
if asbool(config.get('solr.mock')):
self.solr = MockSOLR()
elif self.solr_server:
self.solr = pysolr.Solr(self.solr_server)
else: # pragma no cover
self.solr = None
self.use_queue = asbool(config.get('use_queue', False))
# Load login/logout urls; only used for SFX logins
self.login_url = config.get('auth.login_url', '/auth/')
self.logout_url = config.get('auth.logout_url', '/auth/logout')
# Setup RabbitMQ
if asbool(config.get('amqp.mock')):
self.amq_conn = self.mock_amq = MockAMQ(self)
else:
self.amq_conn = Connection(
hostname=config.get('amqp.hostname', 'localhost'),
port=asint(config.get('amqp.port', 5672)),
userid=config.get('amqp.userid', 'testuser'),
password=config.get('amqp.password', 'testpw'),
vhost=config.get('amqp.vhost', 'testvhost'))
# Setup OEmbed
cp = RawConfigParser()
cp.read(config['oembed.config'])
self.oembed_consumer = consumer = oembed.OEmbedConsumer()
for endpoint in cp.sections():
values = [ v for k,v in cp.items(endpoint) ]
consumer.addEndpoint(oembed.OEmbedEndpoint(endpoint, values))
# Setup Gravatar
self.gravatar = gravatar.url
self.oid_store = M.OpenIdStore()
# Setup pygments
self.pygments_formatter = pygments.formatters.HtmlFormatter(
cssclass='codehilite',
linenos='inline')
# Setup Pypeline
self.pypeline_markup = pypeline_markup
# Setup analytics
self.analytics = analytics.GoogleAnalytics(account=config.get('ga.account', 'UA-32013-57'))
# Setup theme
self.theme = plugin.ThemeProvider.get()
self.icons = dict(
admin = Icon('x', 'ico-admin'),
pencil = Icon('p', 'ico-pencil'),
help = Icon('h', 'ico-help'),
search = Icon('s', 'ico-search'),
history = Icon('N', 'ico-history'),
feed = Icon('f', 'ico-feed'),
mail = Icon('M', 'ico-mail'),
reply = Icon('w', 'ico-reply'),
tag = Icon('z', 'ico-tag'),
flag = Icon('^', 'ico-flag'),
undelete = Icon('+', 'ico-undelete'),
delete = Icon('#', 'ico-delete'),
close = Icon('D', 'ico-close'),
table = Icon('n', 'ico-table'),
stats = Icon('Y', 'ico-stats'),
pin = Icon('@', 'ico-pin'),
folder = Icon('o', 'ico-folder'),
fork = Icon('R', 'ico-fork'),
merge = Icon('J', 'ico-merge'),
plus = Icon('+', 'ico-plus'),
conversation = Icon('q', 'ico-conversation'),
group = Icon('g', 'ico-group'),
user = Icon('U', 'ico-user'),
# Permissions
perm_read = Icon('E', 'ico-focus'),
perm_update = Icon('0', 'ico-sync'),
perm_create = Icon('e', 'ico-config'),
perm_delete = Icon('-', 'ico-minuscirc'),
perm_tool = Icon('x', 'ico-config'),
perm_security = Icon('(', 'ico-lock'),
)
def post_event(self, topic, *args, **kwargs):
allura.tasks.event_tasks.event.post(topic, *args, **kwargs)
@property
def credentials(self):
return Credentials.get()
def handle_paging(self, limit, page, default=50):
if limit:
if c.user in (None, M.User.anonymous()):
session['results_per_page'] = int(limit)
session.save()
else:
c.user.set_pref('results_per_page', int(limit))
else:
if c.user in (None, M.User.anonymous()):
limit = 'results_per_page' in session and session['results_per_page'] or default
else:
limit = c.user.get_pref('results_per_page') or default
page = max(int(page), 0)
start = page * int(limit)
return (limit, page, start)
def document_class(self, neighborhood):
classes = ''
if neighborhood:
classes += ' neighborhood-%s' % neighborhood.name
if not neighborhood and c.project:
classes += ' neighborhood-%s' % c.project.neighborhood.name
if c.project:
classes += ' project-%s' % c.project.shortname
if c.app:
classes += ' mountpoint-%s' % c.app.config.options.mount_point
return classes
def highlight(self, text, lexer=None, filename=None):
if not text:
return h.html.literal('<em>Empty file</em>')
# Don't use line numbers for diff highlight's, as per [#1484]
if lexer == 'diff':
formatter = pygments.formatters.HtmlFormatter(cssclass='codehilite', linenos=False)
else:
formatter = self.pygments_formatter
if lexer is None:
try:
lexer = pygments.lexers.get_lexer_for_filename(filename, encoding='chardet')
except pygments.util.ClassNotFound:
# no highlighting, but we should escape, encode, and wrap it in a <pre>
text = h.really_unicode(text)
text = cgi.escape(text)
return h.html.literal(u'<pre>' + text + u'</pre>')
else:
lexer = pygments.lexers.get_lexer_by_name(lexer, encoding='chardet')
return h.html.literal(pygments.highlight(text, lexer, formatter))
def forge_markdown(self, **kwargs):
'''return a markdown.Markdown object on which you can call convert'''
return markdown.Markdown(
extensions=['codehilite', ForgeExtension(**kwargs), 'tables'],
output_format='html4')
@property
def markdown(self):
return self.forge_markdown()
@property
def markdown_wiki(self):
return self.forge_markdown(wiki=True)
@property
def production_mode(self):
return asbool(config.get('debug')) == False
@property
def resource_manager(self):
return ew_core.widget_context.resource_manager
def register_forge_css(self, href, **kw):
self.resource_manager.register(ew.CSSLink('allura/' + href, **kw))
def register_forge_js(self, href, **kw):
self.resource_manager.register(ew.JSLink('allura/' + href, **kw))
def register_app_css(self, href, **kw):
app = kw.pop('app', c.app)
self.resource_manager.register(
ew.CSSLink('tool/%s/%s' % (app.config.tool_name, href), **kw))
def register_app_js(self, href, **kw):
app = kw.pop('app', c.app)
self.resource_manager.register(
ew.JSLink('tool/%s/%s' % (app.config.tool_name, href), **kw))
def register_js_snippet(self, text, **kw):
self.resource_manager.register(
ew.JSScript(text, **kw))
def oid_session(self):
if 'openid_info' in session:
return session['openid_info']
else:
session['openid_info'] = result = {}
session.save()
return result
def forge_static(self, resource):
base = config['static.url_base']
if base.startswith(':'):
base = request.scheme + base
return base + resource
def theme_static(self, resource):
if isinstance(resource,tuple):
theme_name = resource[1]
resource = resource[0]
else:
theme_name = config.get('theme', 'allura')
base = config['static.url_base']
if base.startswith(':'):
base = request.scheme + base
return base + theme_name + '/' + resource
def app_static(self, resource, app=None):
base = config['static.url_base']
app = app or c.app
if base.startswith(':'):
base = request.scheme + base
return (base + app.config.tool_name + '/' + resource)
def set_project(self, pid):
c.project = M.Project.query.get(shortname=pid, deleted=False)
def set_app(self, name):
c.app = c.project.app_instance(name)
def url(self, base, **kw):
params = urlencode(kw)
if params:
return '%s://%s%s?%s' % (request.scheme, request.host, base, params)
else:
return '%s://%s%s' % (request.scheme, request.host, base)
def postload_contents(self):
text = '''
'''
return json.dumps(dict(text=text))
def year(self):
return datetime.datetime.utcnow().year
class MockSOLR(object):
class MockHits(list):
@property
def hits(self):
return len(self)
@property
def docs(self):
return self
def __init__(self):
self.db = {}
def add(self, objects):
for o in objects:
o['text'] = ''.join(o['text'])
self.db[o['id']] = o
def commit(self):
pass
def search(self, q, fq=None, **kw):
if isinstance(q, unicode):
q = q.encode('latin-1')
# Parse query
preds = []
q_parts = shlex.split(q)
if fq: q_parts += fq
for part in q_parts:
if ':' in part:
field, value = part.split(':', 1)
preds.append((field, value))
else:
preds.append(('text', part))
result = self.MockHits()
for obj in self.db.values():
for field, value in preds:
if field == 'text' or field.endswith('_t'):
if value not in str(obj.get(field, '')):
break
else:
if value != str(obj.get(field, '')):
break
else:
result.append(obj)
return result
def delete(self, *args, **kwargs):
pass
class Icon(object):
def __init__(self, char, css):
self.char = char
self.css = css
def connect_amqp(config):
return