comparison rhodecode/controllers/admin/settings.py @ 547:1e757ac98988

renamed project to rhodecode
author Marcin Kuzminski <marcin@python-works.com>
date Wed, 06 Oct 2010 03:18:16 +0200
parents pylons_app/controllers/admin/settings.py@48be953851fc
children b75b77ef649d
comparison
equal deleted inserted replaced
546:7c2f5e4d7bbf 547:1e757ac98988
1 #!/usr/bin/env python
2 # encoding: utf-8
3 # settings controller for pylons
4 # Copyright (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; version 2
9 # of the License or (at your opinion) any later version of the license.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 # MA 02110-1301, USA.
20 """
21 Created on July 14, 2010
22 settings controller for pylons
23 @author: marcink
24 """
25 from formencode import htmlfill
26 from pylons import request, session, tmpl_context as c, url, app_globals as g, \
27 config
28 from pylons.controllers.util import abort, redirect
29 from pylons.i18n.translation import _
30 from rhodecode.lib import helpers as h
31 from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator, \
32 HasPermissionAnyDecorator
33 from rhodecode.lib.base import BaseController, render
34 from rhodecode.lib.utils import repo2db_mapper, invalidate_cache, \
35 set_hg_app_config, get_hg_settings, get_hg_ui_settings, make_ui
36 from rhodecode.model.db import User, UserLog, HgAppSettings, HgAppUi
37 from rhodecode.model.forms import UserForm, ApplicationSettingsForm, \
38 ApplicationUiSettingsForm
39 from rhodecode.model.hg_model import HgModel
40 from rhodecode.model.user_model import UserModel
41 from rhodecode.lib.celerylib import tasks, run_task
42 import formencode
43 import logging
44 import traceback
45
46 log = logging.getLogger(__name__)
47
48
49 class SettingsController(BaseController):
50 """REST Controller styled on the Atom Publishing Protocol"""
51 # To properly map this controller, ensure your config/routing.py
52 # file has a resource setup:
53 # map.resource('setting', 'settings', controller='admin/settings',
54 # path_prefix='/admin', name_prefix='admin_')
55
56
57 @LoginRequired()
58 def __before__(self):
59 c.admin_user = session.get('admin_user')
60 c.admin_username = session.get('admin_username')
61 super(SettingsController, self).__before__()
62
63
64 @HasPermissionAllDecorator('hg.admin')
65 def index(self, format='html'):
66 """GET /admin/settings: All items in the collection"""
67 # url('admin_settings')
68
69 defaults = get_hg_settings()
70 defaults.update(get_hg_ui_settings())
71 return htmlfill.render(
72 render('admin/settings/settings.html'),
73 defaults=defaults,
74 encoding="UTF-8",
75 force_defaults=False
76 )
77
78 @HasPermissionAllDecorator('hg.admin')
79 def create(self):
80 """POST /admin/settings: Create a new item"""
81 # url('admin_settings')
82
83 @HasPermissionAllDecorator('hg.admin')
84 def new(self, format='html'):
85 """GET /admin/settings/new: Form to create a new item"""
86 # url('admin_new_setting')
87
88 @HasPermissionAllDecorator('hg.admin')
89 def update(self, setting_id):
90 """PUT /admin/settings/setting_id: Update an existing item"""
91 # Forms posted to this method should contain a hidden field:
92 # <input type="hidden" name="_method" value="PUT" />
93 # Or using helpers:
94 # h.form(url('admin_setting', setting_id=ID),
95 # method='put')
96 # url('admin_setting', setting_id=ID)
97 if setting_id == 'mapping':
98 rm_obsolete = request.POST.get('destroy', False)
99 log.debug('Rescanning directories with destroy=%s', rm_obsolete)
100
101 initial = HgModel.repo_scan(g.paths[0][0], g.paths[0][1], g.baseui)
102 repo2db_mapper(initial, rm_obsolete)
103 invalidate_cache('cached_repo_list')
104 h.flash(_('Repositories successfully rescanned'), category='success')
105
106 if setting_id == 'whoosh':
107 repo_location = get_hg_ui_settings()['paths_root_path']
108 full_index = request.POST.get('full_index', False)
109 task = run_task(tasks.whoosh_index, repo_location, full_index)
110
111 h.flash(_('Whoosh reindex task scheduled'), category='success')
112 if setting_id == 'global':
113
114 application_form = ApplicationSettingsForm()()
115 try:
116 form_result = application_form.to_python(dict(request.POST))
117
118 try:
119 hgsettings1 = self.sa.query(HgAppSettings)\
120 .filter(HgAppSettings.app_settings_name == 'title').one()
121 hgsettings1.app_settings_value = form_result['hg_app_title']
122
123 hgsettings2 = self.sa.query(HgAppSettings)\
124 .filter(HgAppSettings.app_settings_name == 'realm').one()
125 hgsettings2.app_settings_value = form_result['hg_app_realm']
126
127
128 self.sa.add(hgsettings1)
129 self.sa.add(hgsettings2)
130 self.sa.commit()
131 set_hg_app_config(config)
132 h.flash(_('Updated application settings'),
133 category='success')
134
135 except:
136 log.error(traceback.format_exc())
137 h.flash(_('error occurred during updating application settings'),
138 category='error')
139
140 self.sa.rollback()
141
142
143 except formencode.Invalid as errors:
144 return htmlfill.render(
145 render('admin/settings/settings.html'),
146 defaults=errors.value,
147 errors=errors.error_dict or {},
148 prefix_error=False,
149 encoding="UTF-8")
150
151 if setting_id == 'mercurial':
152 application_form = ApplicationUiSettingsForm()()
153 try:
154 form_result = application_form.to_python(dict(request.POST))
155
156 try:
157
158 hgsettings1 = self.sa.query(HgAppUi)\
159 .filter(HgAppUi.ui_key == 'push_ssl').one()
160 hgsettings1.ui_value = form_result['web_push_ssl']
161
162 hgsettings2 = self.sa.query(HgAppUi)\
163 .filter(HgAppUi.ui_key == '/').one()
164 hgsettings2.ui_value = form_result['paths_root_path']
165
166
167 #HOOKS
168 hgsettings3 = self.sa.query(HgAppUi)\
169 .filter(HgAppUi.ui_key == 'changegroup.update').one()
170 hgsettings3.ui_active = bool(form_result['hooks_changegroup_update'])
171
172 hgsettings4 = self.sa.query(HgAppUi)\
173 .filter(HgAppUi.ui_key == 'changegroup.repo_size').one()
174 hgsettings4.ui_active = bool(form_result['hooks_changegroup_repo_size'])
175
176
177
178
179 self.sa.add(hgsettings1)
180 self.sa.add(hgsettings2)
181 self.sa.add(hgsettings3)
182 self.sa.add(hgsettings4)
183 self.sa.commit()
184
185 h.flash(_('Updated mercurial settings'),
186 category='success')
187
188 except:
189 log.error(traceback.format_exc())
190 h.flash(_('error occurred during updating application settings'),
191 category='error')
192
193 self.sa.rollback()
194
195
196 except formencode.Invalid as errors:
197 return htmlfill.render(
198 render('admin/settings/settings.html'),
199 defaults=errors.value,
200 errors=errors.error_dict or {},
201 prefix_error=False,
202 encoding="UTF-8")
203
204
205
206 return redirect(url('admin_settings'))
207
208 @HasPermissionAllDecorator('hg.admin')
209 def delete(self, setting_id):
210 """DELETE /admin/settings/setting_id: Delete an existing item"""
211 # Forms posted to this method should contain a hidden field:
212 # <input type="hidden" name="_method" value="DELETE" />
213 # Or using helpers:
214 # h.form(url('admin_setting', setting_id=ID),
215 # method='delete')
216 # url('admin_setting', setting_id=ID)
217
218 @HasPermissionAllDecorator('hg.admin')
219 def show(self, setting_id, format='html'):
220 """GET /admin/settings/setting_id: Show a specific item"""
221 # url('admin_setting', setting_id=ID)
222
223 @HasPermissionAllDecorator('hg.admin')
224 def edit(self, setting_id, format='html'):
225 """GET /admin/settings/setting_id/edit: Form to edit an existing item"""
226 # url('admin_edit_setting', setting_id=ID)
227
228
229 def my_account(self):
230 """
231 GET /_admin/my_account Displays info about my account
232 """
233 # url('admin_settings_my_account')
234 c.user = self.sa.query(User).get(c.hg_app_user.user_id)
235 c.user_repos = []
236 for repo in c.cached_repo_list.values():
237 if repo.dbrepo.user.username == c.user.username:
238 c.user_repos.append(repo)
239
240 if c.user.username == 'default':
241 h.flash(_("You can't edit this user since it's"
242 " crucial for entire application"), category='warning')
243 return redirect(url('users'))
244
245 defaults = c.user.__dict__
246 return htmlfill.render(
247 render('admin/users/user_edit_my_account.html'),
248 defaults=defaults,
249 encoding="UTF-8",
250 force_defaults=False
251 )
252
253 def my_account_update(self):
254 """PUT /_admin/my_account_update: Update an existing item"""
255 # Forms posted to this method should contain a hidden field:
256 # <input type="hidden" name="_method" value="PUT" />
257 # Or using helpers:
258 # h.form(url('admin_settings_my_account_update'),
259 # method='put')
260 # url('admin_settings_my_account_update', id=ID)
261 user_model = UserModel()
262 uid = c.hg_app_user.user_id
263 _form = UserForm(edit=True, old_data={'user_id':uid,
264 'email':c.hg_app_user.email})()
265 form_result = {}
266 try:
267 form_result = _form.to_python(dict(request.POST))
268 user_model.update_my_account(uid, form_result)
269 h.flash(_('Your account was updated succesfully'),
270 category='success')
271
272 except formencode.Invalid as errors:
273 c.user = self.sa.query(User).get(c.hg_app_user.user_id)
274 c.user_repos = []
275 for repo in c.cached_repo_list.values():
276 if repo.dbrepo.user.username == c.user.username:
277 c.user_repos.append(repo)
278 return htmlfill.render(
279 render('admin/users/user_edit_my_account.html'),
280 defaults=errors.value,
281 errors=errors.error_dict or {},
282 prefix_error=False,
283 encoding="UTF-8")
284 except Exception:
285 log.error(traceback.format_exc())
286 h.flash(_('error occured during update of user %s') \
287 % form_result.get('username'), category='error')
288
289 return redirect(url('my_account'))
290
291 @HasPermissionAnyDecorator('hg.admin', 'hg.create.repository')
292 def create_repository(self):
293 """GET /_admin/create_repository: Form to create a new item"""
294 new_repo = request.GET.get('repo', '')
295 c.new_repo = h.repo_name_slug(new_repo)
296
297 return render('admin/repos/repo_add_create_repository.html')
298