##// END OF EJS Templates
fixes testing email in settings
marcink -
r1798:2ee93fba beta
parent child Browse files
Show More
@@ -1,412 +1,414 b''
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 rhodecode.controllers.admin.settings
4 4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 5
6 6 settings controller for rhodecode admin
7 7
8 8 :created_on: Jul 14, 2010
9 9 :author: marcink
10 10 :copyright: (C) 2009-2011 Marcin Kuzminski <marcin@python-works.com>
11 11 :license: GPLv3, see COPYING for more details.
12 12 """
13 13 # This program is free software: you can redistribute it and/or modify
14 14 # it under the terms of the GNU General Public License as published by
15 15 # the Free Software Foundation, either version 3 of the License, or
16 16 # (at your option) any later version.
17 17 #
18 18 # This program is distributed in the hope that it will be useful,
19 19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 21 # GNU General Public License for more details.
22 22 #
23 23 # You should have received a copy of the GNU General Public License
24 24 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 25
26 26 import logging
27 27 import traceback
28 28 import formencode
29 29
30 30 from sqlalchemy import func
31 31 from formencode import htmlfill
32 32 from pylons import request, session, tmpl_context as c, url, config
33 33 from pylons.controllers.util import abort, redirect
34 34 from pylons.i18n.translation import _
35 35
36 36 from rhodecode.lib import helpers as h
37 37 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator, \
38 38 HasPermissionAnyDecorator, NotAnonymous
39 39 from rhodecode.lib.base import BaseController, render
40 40 from rhodecode.lib.celerylib import tasks, run_task
41 41 from rhodecode.lib.utils import repo2db_mapper, invalidate_cache, \
42 42 set_rhodecode_config, repo_name_slug
43 43 from rhodecode.model.db import RhodeCodeUi, Repository, RepoGroup, \
44 44 RhodeCodeSetting
45 45 from rhodecode.model.forms import UserForm, ApplicationSettingsForm, \
46 46 ApplicationUiSettingsForm
47 47 from rhodecode.model.scm import ScmModel
48 48 from rhodecode.model.user import UserModel
49 49 from rhodecode.model.db import User
50 50 from rhodecode.model.notification import EmailNotificationModel
51 51 from rhodecode.model.meta import Session
52 52
53 53 log = logging.getLogger(__name__)
54 54
55 55
56 56 class SettingsController(BaseController):
57 57 """REST Controller styled on the Atom Publishing Protocol"""
58 58 # To properly map this controller, ensure your config/routing.py
59 59 # file has a resource setup:
60 60 # map.resource('setting', 'settings', controller='admin/settings',
61 61 # path_prefix='/admin', name_prefix='admin_')
62 62
63 63 @LoginRequired()
64 64 def __before__(self):
65 65 c.admin_user = session.get('admin_user')
66 66 c.admin_username = session.get('admin_username')
67 67 super(SettingsController, self).__before__()
68 68
69 69 @HasPermissionAllDecorator('hg.admin')
70 70 def index(self, format='html'):
71 71 """GET /admin/settings: All items in the collection"""
72 72 # url('admin_settings')
73 73
74 74 defaults = RhodeCodeSetting.get_app_settings()
75 75 defaults.update(self.get_hg_ui_settings())
76 76 return htmlfill.render(
77 77 render('admin/settings/settings.html'),
78 78 defaults=defaults,
79 79 encoding="UTF-8",
80 80 force_defaults=False
81 81 )
82 82
83 83 @HasPermissionAllDecorator('hg.admin')
84 84 def create(self):
85 85 """POST /admin/settings: Create a new item"""
86 86 # url('admin_settings')
87 87
88 88 @HasPermissionAllDecorator('hg.admin')
89 89 def new(self, format='html'):
90 90 """GET /admin/settings/new: Form to create a new item"""
91 91 # url('admin_new_setting')
92 92
93 93 @HasPermissionAllDecorator('hg.admin')
94 94 def update(self, setting_id):
95 95 """PUT /admin/settings/setting_id: Update an existing item"""
96 96 # Forms posted to this method should contain a hidden field:
97 97 # <input type="hidden" name="_method" value="PUT" />
98 98 # Or using helpers:
99 99 # h.form(url('admin_setting', setting_id=ID),
100 100 # method='put')
101 101 # url('admin_setting', setting_id=ID)
102 102 if setting_id == 'mapping':
103 103 rm_obsolete = request.POST.get('destroy', False)
104 104 log.debug('Rescanning directories with destroy=%s', rm_obsolete)
105 105 initial = ScmModel().repo_scan()
106 106 log.debug('invalidating all repositories')
107 107 for repo_name in initial.keys():
108 108 invalidate_cache('get_repo_cached_%s' % repo_name)
109 109
110 110 added, removed = repo2db_mapper(initial, rm_obsolete)
111 111
112 112 h.flash(_('Repositories successfully'
113 113 ' rescanned added: %s,removed: %s') % (added, removed),
114 114 category='success')
115 115
116 116 if setting_id == 'whoosh':
117 117 repo_location = self.get_hg_ui_settings()['paths_root_path']
118 118 full_index = request.POST.get('full_index', False)
119 119 run_task(tasks.whoosh_index, repo_location, full_index)
120 120
121 121 h.flash(_('Whoosh reindex task scheduled'), category='success')
122 122 if setting_id == 'global':
123 123
124 124 application_form = ApplicationSettingsForm()()
125 125 try:
126 126 form_result = application_form.to_python(dict(request.POST))
127 127
128 128 try:
129 129 hgsettings1 = RhodeCodeSetting.get_by_name('title')
130 130 hgsettings1.app_settings_value = \
131 131 form_result['rhodecode_title']
132 132
133 133 hgsettings2 = RhodeCodeSetting.get_by_name('realm')
134 134 hgsettings2.app_settings_value = \
135 135 form_result['rhodecode_realm']
136 136
137 137 hgsettings3 = RhodeCodeSetting.get_by_name('ga_code')
138 138 hgsettings3.app_settings_value = \
139 139 form_result['rhodecode_ga_code']
140 140
141 141 self.sa.add(hgsettings1)
142 142 self.sa.add(hgsettings2)
143 143 self.sa.add(hgsettings3)
144 144 self.sa.commit()
145 145 set_rhodecode_config(config)
146 146 h.flash(_('Updated application settings'),
147 147 category='success')
148 148
149 149 except Exception:
150 150 log.error(traceback.format_exc())
151 151 h.flash(_('error occurred during updating '
152 152 'application settings'),
153 153 category='error')
154 154
155 155 self.sa.rollback()
156 156
157 157 except formencode.Invalid, errors:
158 158 return htmlfill.render(
159 159 render('admin/settings/settings.html'),
160 160 defaults=errors.value,
161 161 errors=errors.error_dict or {},
162 162 prefix_error=False,
163 163 encoding="UTF-8")
164 164
165 165 if setting_id == 'mercurial':
166 166 application_form = ApplicationUiSettingsForm()()
167 167 try:
168 168 form_result = application_form.to_python(dict(request.POST))
169 169
170 170 try:
171 171
172 172 hgsettings1 = self.sa.query(RhodeCodeUi)\
173 173 .filter(RhodeCodeUi.ui_key == 'push_ssl').one()
174 174 hgsettings1.ui_value = form_result['web_push_ssl']
175 175
176 176 hgsettings2 = self.sa.query(RhodeCodeUi)\
177 177 .filter(RhodeCodeUi.ui_key == '/').one()
178 178 hgsettings2.ui_value = form_result['paths_root_path']
179 179
180 180 #HOOKS
181 181 hgsettings3 = self.sa.query(RhodeCodeUi)\
182 182 .filter(RhodeCodeUi.ui_key == 'changegroup.update').one()
183 183 hgsettings3.ui_active = \
184 184 bool(form_result['hooks_changegroup_update'])
185 185
186 186 hgsettings4 = self.sa.query(RhodeCodeUi)\
187 187 .filter(RhodeCodeUi.ui_key ==
188 188 'changegroup.repo_size').one()
189 189 hgsettings4.ui_active = \
190 190 bool(form_result['hooks_changegroup_repo_size'])
191 191
192 192 hgsettings5 = self.sa.query(RhodeCodeUi)\
193 193 .filter(RhodeCodeUi.ui_key ==
194 194 'pretxnchangegroup.push_logger').one()
195 195 hgsettings5.ui_active = \
196 196 bool(form_result['hooks_pretxnchangegroup'
197 197 '_push_logger'])
198 198
199 199 hgsettings6 = self.sa.query(RhodeCodeUi)\
200 200 .filter(RhodeCodeUi.ui_key ==
201 201 'preoutgoing.pull_logger').one()
202 202 hgsettings6.ui_active = \
203 203 bool(form_result['hooks_preoutgoing_pull_logger'])
204 204
205 205 self.sa.add(hgsettings1)
206 206 self.sa.add(hgsettings2)
207 207 self.sa.add(hgsettings3)
208 208 self.sa.add(hgsettings4)
209 209 self.sa.add(hgsettings5)
210 210 self.sa.add(hgsettings6)
211 211 self.sa.commit()
212 212
213 213 h.flash(_('Updated mercurial settings'),
214 214 category='success')
215 215
216 216 except:
217 217 log.error(traceback.format_exc())
218 218 h.flash(_('error occurred during updating '
219 219 'application settings'), category='error')
220 220
221 221 self.sa.rollback()
222 222
223 223 except formencode.Invalid, errors:
224 224 return htmlfill.render(
225 225 render('admin/settings/settings.html'),
226 226 defaults=errors.value,
227 227 errors=errors.error_dict or {},
228 228 prefix_error=False,
229 229 encoding="UTF-8")
230 230
231
232 231 if setting_id == 'hooks':
233 232 ui_key = request.POST.get('new_hook_ui_key')
234 233 ui_value = request.POST.get('new_hook_ui_value')
235 234 try:
236 235
237 236 if ui_value and ui_key:
238 237 RhodeCodeUi.create_or_update_hook(ui_key, ui_value)
239 238 h.flash(_('Added new hook'),
240 239 category='success')
241 240
242 241 # check for edits
243 242 update = False
244 243 _d = request.POST.dict_of_lists()
245 for k, v in zip(_d.get('hook_ui_key', []), _d.get('hook_ui_value_new', [])):
244 for k, v in zip(_d.get('hook_ui_key', []),
245 _d.get('hook_ui_value_new', [])):
246 246 RhodeCodeUi.create_or_update_hook(k, v)
247 247 update = True
248 248
249 249 if update:
250 250 h.flash(_('Updated hooks'), category='success')
251 251 Session.commit()
252 252 except:
253 253 log.error(traceback.format_exc())
254 254 h.flash(_('error occurred during hook creation'),
255 255 category='error')
256 256
257 257 return redirect(url('admin_edit_setting', setting_id='hooks'))
258 258
259
260
261 259 if setting_id == 'email':
262 260 test_email = request.POST.get('test_email')
263 261 test_email_subj = 'RhodeCode TestEmail'
264 262 test_email_body = 'RhodeCode Email test'
263
265 264 test_email_html_body = EmailNotificationModel()\
266 .get_email_tmpl(EmailNotificationModel.TYPE_DEFAULT)
265 .get_email_tmpl(EmailNotificationModel.TYPE_DEFAULT,
266 body=test_email_body)
267 267
268 run_task(tasks.send_email, [test_email], test_email_subj,
268 recipients = [test_email] if [test_email] else None
269
270 run_task(tasks.send_email, recipients, test_email_subj,
269 271 test_email_body, test_email_html_body)
270 272
271 273 h.flash(_('Email task created'), category='success')
272 274 return redirect(url('admin_settings'))
273 275
274 276 @HasPermissionAllDecorator('hg.admin')
275 277 def delete(self, setting_id):
276 278 """DELETE /admin/settings/setting_id: Delete an existing item"""
277 279 # Forms posted to this method should contain a hidden field:
278 280 # <input type="hidden" name="_method" value="DELETE" />
279 281 # Or using helpers:
280 282 # h.form(url('admin_setting', setting_id=ID),
281 283 # method='delete')
282 284 # url('admin_setting', setting_id=ID)
283 285 if setting_id == 'hooks':
284 286 hook_id = request.POST.get('hook_id')
285 287 RhodeCodeUi.delete(hook_id)
286 288
287 289
288 290 @HasPermissionAllDecorator('hg.admin')
289 291 def show(self, setting_id, format='html'):
290 292 """
291 293 GET /admin/settings/setting_id: Show a specific item"""
292 294 # url('admin_setting', setting_id=ID)
293 295
294 296 @HasPermissionAllDecorator('hg.admin')
295 297 def edit(self, setting_id, format='html'):
296 298 """
297 299 GET /admin/settings/setting_id/edit: Form to
298 300 edit an existing item"""
299 301 # url('admin_edit_setting', setting_id=ID)
300 302
301 303 c.hooks = RhodeCodeUi.get_builtin_hooks()
302 304 c.custom_hooks = RhodeCodeUi.get_custom_hooks()
303 305
304 306 return htmlfill.render(
305 307 render('admin/settings/hooks.html'),
306 308 defaults={},
307 309 encoding="UTF-8",
308 310 force_defaults=False
309 311 )
310 312
311 313 @NotAnonymous()
312 314 def my_account(self):
313 315 """
314 316 GET /_admin/my_account Displays info about my account
315 317 """
316 318 # url('admin_settings_my_account')
317 319
318 320 c.user = User.get(self.rhodecode_user.user_id)
319 321 all_repos = self.sa.query(Repository)\
320 322 .filter(Repository.user_id == c.user.user_id)\
321 323 .order_by(func.lower(Repository.repo_name)).all()
322 324
323 325 c.user_repos = ScmModel().get_repos(all_repos)
324 326
325 327 if c.user.username == 'default':
326 328 h.flash(_("You can't edit this user since it's"
327 329 " crucial for entire application"), category='warning')
328 330 return redirect(url('users'))
329 331
330 332 defaults = c.user.get_dict()
331 333 return htmlfill.render(
332 334 render('admin/users/user_edit_my_account.html'),
333 335 defaults=defaults,
334 336 encoding="UTF-8",
335 337 force_defaults=False
336 338 )
337 339
338 340 def my_account_update(self):
339 341 """PUT /_admin/my_account_update: Update an existing item"""
340 342 # Forms posted to this method should contain a hidden field:
341 343 # <input type="hidden" name="_method" value="PUT" />
342 344 # Or using helpers:
343 345 # h.form(url('admin_settings_my_account_update'),
344 346 # method='put')
345 347 # url('admin_settings_my_account_update', id=ID)
346 348 user_model = UserModel()
347 349 uid = self.rhodecode_user.user_id
348 350 _form = UserForm(edit=True,
349 351 old_data={'user_id': uid,
350 352 'email': self.rhodecode_user.email})()
351 353 form_result = {}
352 354 try:
353 355 form_result = _form.to_python(dict(request.POST))
354 356 user_model.update_my_account(uid, form_result)
355 357 h.flash(_('Your account was updated successfully'),
356 358 category='success')
357 359 Session.commit()
358 360 except formencode.Invalid, errors:
359 361 c.user = User.get(self.rhodecode_user.user_id)
360 362 all_repos = self.sa.query(Repository)\
361 363 .filter(Repository.user_id == c.user.user_id)\
362 364 .order_by(func.lower(Repository.repo_name))\
363 365 .all()
364 366 c.user_repos = ScmModel().get_repos(all_repos)
365 367
366 368 return htmlfill.render(
367 369 render('admin/users/user_edit_my_account.html'),
368 370 defaults=errors.value,
369 371 errors=errors.error_dict or {},
370 372 prefix_error=False,
371 373 encoding="UTF-8")
372 374 except Exception:
373 375 log.error(traceback.format_exc())
374 376 h.flash(_('error occurred during update of user %s') \
375 377 % form_result.get('username'), category='error')
376 378
377 379 return redirect(url('my_account'))
378 380
379 381 @NotAnonymous()
380 382 @HasPermissionAnyDecorator('hg.admin', 'hg.create.repository')
381 383 def create_repository(self):
382 384 """GET /_admin/create_repository: Form to create a new item"""
383 385
384 386 c.repo_groups = RepoGroup.groups_choices()
385 387 c.repo_groups_choices = map(lambda k: unicode(k[0]), c.repo_groups)
386 388
387 389 new_repo = request.GET.get('repo', '')
388 390 c.new_repo = repo_name_slug(new_repo)
389 391
390 392 return render('admin/repos/repo_add_create_repository.html')
391 393
392 394 def get_hg_ui_settings(self):
393 395 ret = self.sa.query(RhodeCodeUi).all()
394 396
395 397 if not ret:
396 398 raise Exception('Could not get application ui settings !')
397 399 settings = {}
398 400 for each in ret:
399 401 k = each.ui_key
400 402 v = each.ui_value
401 403 if k == '/':
402 404 k = 'root_path'
403 405
404 406 if k.find('.') != -1:
405 407 k = k.replace('.', '_')
406 408
407 409 if each.ui_section == 'hooks':
408 410 v = each.ui_active
409 411
410 412 settings[each.ui_section + '_' + k] = v
411 413
412 414 return settings
General Comments 0
You need to be logged in to leave comments. Login now