##// END OF EJS Templates
ui: allow selecting and specifing ssh clone url....
marcink -
r2497:9a1b0044 default
parent child Browse files
Show More
@@ -1,763 +1,764 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2018 RhodeCode GmbH
3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
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/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21
21
22 import logging
22 import logging
23 import collections
23 import collections
24
24
25 import datetime
25 import datetime
26 import formencode
26 import formencode
27 import formencode.htmlfill
27 import formencode.htmlfill
28
28
29 import rhodecode
29 import rhodecode
30 from pyramid.view import view_config
30 from pyramid.view import view_config
31 from pyramid.httpexceptions import HTTPFound, HTTPNotFound
31 from pyramid.httpexceptions import HTTPFound, HTTPNotFound
32 from pyramid.renderers import render
32 from pyramid.renderers import render
33 from pyramid.response import Response
33 from pyramid.response import Response
34
34
35 from rhodecode.apps._base import BaseAppView
35 from rhodecode.apps._base import BaseAppView
36 from rhodecode.apps.admin.navigation import navigation_list
36 from rhodecode.apps.admin.navigation import navigation_list
37 from rhodecode.apps.svn_support.config_keys import generate_config
37 from rhodecode.apps.svn_support.config_keys import generate_config
38 from rhodecode.lib import helpers as h
38 from rhodecode.lib import helpers as h
39 from rhodecode.lib.auth import (
39 from rhodecode.lib.auth import (
40 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
40 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
41 from rhodecode.lib.celerylib import tasks, run_task
41 from rhodecode.lib.celerylib import tasks, run_task
42 from rhodecode.lib.utils import repo2db_mapper
42 from rhodecode.lib.utils import repo2db_mapper
43 from rhodecode.lib.utils2 import str2bool, safe_unicode, AttributeDict
43 from rhodecode.lib.utils2 import str2bool, safe_unicode, AttributeDict
44 from rhodecode.lib.index import searcher_from_config
44 from rhodecode.lib.index import searcher_from_config
45
45
46 from rhodecode.model.db import RhodeCodeUi, Repository
46 from rhodecode.model.db import RhodeCodeUi, Repository
47 from rhodecode.model.forms import (ApplicationSettingsForm,
47 from rhodecode.model.forms import (ApplicationSettingsForm,
48 ApplicationUiSettingsForm, ApplicationVisualisationForm,
48 ApplicationUiSettingsForm, ApplicationVisualisationForm,
49 LabsSettingsForm, IssueTrackerPatternsForm)
49 LabsSettingsForm, IssueTrackerPatternsForm)
50 from rhodecode.model.repo_group import RepoGroupModel
50 from rhodecode.model.repo_group import RepoGroupModel
51
51
52 from rhodecode.model.scm import ScmModel
52 from rhodecode.model.scm import ScmModel
53 from rhodecode.model.notification import EmailNotificationModel
53 from rhodecode.model.notification import EmailNotificationModel
54 from rhodecode.model.meta import Session
54 from rhodecode.model.meta import Session
55 from rhodecode.model.settings import (
55 from rhodecode.model.settings import (
56 IssueTrackerSettingsModel, VcsSettingsModel, SettingNotFound,
56 IssueTrackerSettingsModel, VcsSettingsModel, SettingNotFound,
57 SettingsModel)
57 SettingsModel)
58
58
59
59
60 log = logging.getLogger(__name__)
60 log = logging.getLogger(__name__)
61
61
62
62
63 class AdminSettingsView(BaseAppView):
63 class AdminSettingsView(BaseAppView):
64
64
65 def load_default_context(self):
65 def load_default_context(self):
66 c = self._get_local_tmpl_context()
66 c = self._get_local_tmpl_context()
67 c.labs_active = str2bool(
67 c.labs_active = str2bool(
68 rhodecode.CONFIG.get('labs_settings_active', 'true'))
68 rhodecode.CONFIG.get('labs_settings_active', 'true'))
69 c.navlist = navigation_list(self.request)
69 c.navlist = navigation_list(self.request)
70
70
71 return c
71 return c
72
72
73 @classmethod
73 @classmethod
74 def _get_ui_settings(cls):
74 def _get_ui_settings(cls):
75 ret = RhodeCodeUi.query().all()
75 ret = RhodeCodeUi.query().all()
76
76
77 if not ret:
77 if not ret:
78 raise Exception('Could not get application ui settings !')
78 raise Exception('Could not get application ui settings !')
79 settings = {}
79 settings = {}
80 for each in ret:
80 for each in ret:
81 k = each.ui_key
81 k = each.ui_key
82 v = each.ui_value
82 v = each.ui_value
83 if k == '/':
83 if k == '/':
84 k = 'root_path'
84 k = 'root_path'
85
85
86 if k in ['push_ssl', 'publish', 'enabled']:
86 if k in ['push_ssl', 'publish', 'enabled']:
87 v = str2bool(v)
87 v = str2bool(v)
88
88
89 if k.find('.') != -1:
89 if k.find('.') != -1:
90 k = k.replace('.', '_')
90 k = k.replace('.', '_')
91
91
92 if each.ui_section in ['hooks', 'extensions']:
92 if each.ui_section in ['hooks', 'extensions']:
93 v = each.ui_active
93 v = each.ui_active
94
94
95 settings[each.ui_section + '_' + k] = v
95 settings[each.ui_section + '_' + k] = v
96 return settings
96 return settings
97
97
98 @classmethod
98 @classmethod
99 def _form_defaults(cls):
99 def _form_defaults(cls):
100 defaults = SettingsModel().get_all_settings()
100 defaults = SettingsModel().get_all_settings()
101 defaults.update(cls._get_ui_settings())
101 defaults.update(cls._get_ui_settings())
102
102
103 defaults.update({
103 defaults.update({
104 'new_svn_branch': '',
104 'new_svn_branch': '',
105 'new_svn_tag': '',
105 'new_svn_tag': '',
106 })
106 })
107 return defaults
107 return defaults
108
108
109 @LoginRequired()
109 @LoginRequired()
110 @HasPermissionAllDecorator('hg.admin')
110 @HasPermissionAllDecorator('hg.admin')
111 @view_config(
111 @view_config(
112 route_name='admin_settings_vcs', request_method='GET',
112 route_name='admin_settings_vcs', request_method='GET',
113 renderer='rhodecode:templates/admin/settings/settings.mako')
113 renderer='rhodecode:templates/admin/settings/settings.mako')
114 def settings_vcs(self):
114 def settings_vcs(self):
115 c = self.load_default_context()
115 c = self.load_default_context()
116 c.active = 'vcs'
116 c.active = 'vcs'
117 model = VcsSettingsModel()
117 model = VcsSettingsModel()
118 c.svn_branch_patterns = model.get_global_svn_branch_patterns()
118 c.svn_branch_patterns = model.get_global_svn_branch_patterns()
119 c.svn_tag_patterns = model.get_global_svn_tag_patterns()
119 c.svn_tag_patterns = model.get_global_svn_tag_patterns()
120
120
121 settings = self.request.registry.settings
121 settings = self.request.registry.settings
122 c.svn_proxy_generate_config = settings[generate_config]
122 c.svn_proxy_generate_config = settings[generate_config]
123
123
124 defaults = self._form_defaults()
124 defaults = self._form_defaults()
125
125
126 model.create_largeobjects_dirs_if_needed(defaults['paths_root_path'])
126 model.create_largeobjects_dirs_if_needed(defaults['paths_root_path'])
127
127
128 data = render('rhodecode:templates/admin/settings/settings.mako',
128 data = render('rhodecode:templates/admin/settings/settings.mako',
129 self._get_template_context(c), self.request)
129 self._get_template_context(c), self.request)
130 html = formencode.htmlfill.render(
130 html = formencode.htmlfill.render(
131 data,
131 data,
132 defaults=defaults,
132 defaults=defaults,
133 encoding="UTF-8",
133 encoding="UTF-8",
134 force_defaults=False
134 force_defaults=False
135 )
135 )
136 return Response(html)
136 return Response(html)
137
137
138 @LoginRequired()
138 @LoginRequired()
139 @HasPermissionAllDecorator('hg.admin')
139 @HasPermissionAllDecorator('hg.admin')
140 @CSRFRequired()
140 @CSRFRequired()
141 @view_config(
141 @view_config(
142 route_name='admin_settings_vcs_update', request_method='POST',
142 route_name='admin_settings_vcs_update', request_method='POST',
143 renderer='rhodecode:templates/admin/settings/settings.mako')
143 renderer='rhodecode:templates/admin/settings/settings.mako')
144 def settings_vcs_update(self):
144 def settings_vcs_update(self):
145 _ = self.request.translate
145 _ = self.request.translate
146 c = self.load_default_context()
146 c = self.load_default_context()
147 c.active = 'vcs'
147 c.active = 'vcs'
148
148
149 model = VcsSettingsModel()
149 model = VcsSettingsModel()
150 c.svn_branch_patterns = model.get_global_svn_branch_patterns()
150 c.svn_branch_patterns = model.get_global_svn_branch_patterns()
151 c.svn_tag_patterns = model.get_global_svn_tag_patterns()
151 c.svn_tag_patterns = model.get_global_svn_tag_patterns()
152
152
153 settings = self.request.registry.settings
153 settings = self.request.registry.settings
154 c.svn_proxy_generate_config = settings[generate_config]
154 c.svn_proxy_generate_config = settings[generate_config]
155
155
156 application_form = ApplicationUiSettingsForm(self.request.translate)()
156 application_form = ApplicationUiSettingsForm(self.request.translate)()
157
157
158 try:
158 try:
159 form_result = application_form.to_python(dict(self.request.POST))
159 form_result = application_form.to_python(dict(self.request.POST))
160 except formencode.Invalid as errors:
160 except formencode.Invalid as errors:
161 h.flash(
161 h.flash(
162 _("Some form inputs contain invalid data."),
162 _("Some form inputs contain invalid data."),
163 category='error')
163 category='error')
164 data = render('rhodecode:templates/admin/settings/settings.mako',
164 data = render('rhodecode:templates/admin/settings/settings.mako',
165 self._get_template_context(c), self.request)
165 self._get_template_context(c), self.request)
166 html = formencode.htmlfill.render(
166 html = formencode.htmlfill.render(
167 data,
167 data,
168 defaults=errors.value,
168 defaults=errors.value,
169 errors=errors.error_dict or {},
169 errors=errors.error_dict or {},
170 prefix_error=False,
170 prefix_error=False,
171 encoding="UTF-8",
171 encoding="UTF-8",
172 force_defaults=False
172 force_defaults=False
173 )
173 )
174 return Response(html)
174 return Response(html)
175
175
176 try:
176 try:
177 if c.visual.allow_repo_location_change:
177 if c.visual.allow_repo_location_change:
178 model.update_global_path_setting(
178 model.update_global_path_setting(
179 form_result['paths_root_path'])
179 form_result['paths_root_path'])
180
180
181 model.update_global_ssl_setting(form_result['web_push_ssl'])
181 model.update_global_ssl_setting(form_result['web_push_ssl'])
182 model.update_global_hook_settings(form_result)
182 model.update_global_hook_settings(form_result)
183
183
184 model.create_or_update_global_svn_settings(form_result)
184 model.create_or_update_global_svn_settings(form_result)
185 model.create_or_update_global_hg_settings(form_result)
185 model.create_or_update_global_hg_settings(form_result)
186 model.create_or_update_global_git_settings(form_result)
186 model.create_or_update_global_git_settings(form_result)
187 model.create_or_update_global_pr_settings(form_result)
187 model.create_or_update_global_pr_settings(form_result)
188 except Exception:
188 except Exception:
189 log.exception("Exception while updating settings")
189 log.exception("Exception while updating settings")
190 h.flash(_('Error occurred during updating '
190 h.flash(_('Error occurred during updating '
191 'application settings'), category='error')
191 'application settings'), category='error')
192 else:
192 else:
193 Session().commit()
193 Session().commit()
194 h.flash(_('Updated VCS settings'), category='success')
194 h.flash(_('Updated VCS settings'), category='success')
195 raise HTTPFound(h.route_path('admin_settings_vcs'))
195 raise HTTPFound(h.route_path('admin_settings_vcs'))
196
196
197 data = render('rhodecode:templates/admin/settings/settings.mako',
197 data = render('rhodecode:templates/admin/settings/settings.mako',
198 self._get_template_context(c), self.request)
198 self._get_template_context(c), self.request)
199 html = formencode.htmlfill.render(
199 html = formencode.htmlfill.render(
200 data,
200 data,
201 defaults=self._form_defaults(),
201 defaults=self._form_defaults(),
202 encoding="UTF-8",
202 encoding="UTF-8",
203 force_defaults=False
203 force_defaults=False
204 )
204 )
205 return Response(html)
205 return Response(html)
206
206
207 @LoginRequired()
207 @LoginRequired()
208 @HasPermissionAllDecorator('hg.admin')
208 @HasPermissionAllDecorator('hg.admin')
209 @CSRFRequired()
209 @CSRFRequired()
210 @view_config(
210 @view_config(
211 route_name='admin_settings_vcs_svn_pattern_delete', request_method='POST',
211 route_name='admin_settings_vcs_svn_pattern_delete', request_method='POST',
212 renderer='json_ext', xhr=True)
212 renderer='json_ext', xhr=True)
213 def settings_vcs_delete_svn_pattern(self):
213 def settings_vcs_delete_svn_pattern(self):
214 delete_pattern_id = self.request.POST.get('delete_svn_pattern')
214 delete_pattern_id = self.request.POST.get('delete_svn_pattern')
215 model = VcsSettingsModel()
215 model = VcsSettingsModel()
216 try:
216 try:
217 model.delete_global_svn_pattern(delete_pattern_id)
217 model.delete_global_svn_pattern(delete_pattern_id)
218 except SettingNotFound:
218 except SettingNotFound:
219 log.exception(
219 log.exception(
220 'Failed to delete svn_pattern with id %s', delete_pattern_id)
220 'Failed to delete svn_pattern with id %s', delete_pattern_id)
221 raise HTTPNotFound()
221 raise HTTPNotFound()
222
222
223 Session().commit()
223 Session().commit()
224 return True
224 return True
225
225
226 @LoginRequired()
226 @LoginRequired()
227 @HasPermissionAllDecorator('hg.admin')
227 @HasPermissionAllDecorator('hg.admin')
228 @view_config(
228 @view_config(
229 route_name='admin_settings_mapping', request_method='GET',
229 route_name='admin_settings_mapping', request_method='GET',
230 renderer='rhodecode:templates/admin/settings/settings.mako')
230 renderer='rhodecode:templates/admin/settings/settings.mako')
231 def settings_mapping(self):
231 def settings_mapping(self):
232 c = self.load_default_context()
232 c = self.load_default_context()
233 c.active = 'mapping'
233 c.active = 'mapping'
234
234
235 data = render('rhodecode:templates/admin/settings/settings.mako',
235 data = render('rhodecode:templates/admin/settings/settings.mako',
236 self._get_template_context(c), self.request)
236 self._get_template_context(c), self.request)
237 html = formencode.htmlfill.render(
237 html = formencode.htmlfill.render(
238 data,
238 data,
239 defaults=self._form_defaults(),
239 defaults=self._form_defaults(),
240 encoding="UTF-8",
240 encoding="UTF-8",
241 force_defaults=False
241 force_defaults=False
242 )
242 )
243 return Response(html)
243 return Response(html)
244
244
245 @LoginRequired()
245 @LoginRequired()
246 @HasPermissionAllDecorator('hg.admin')
246 @HasPermissionAllDecorator('hg.admin')
247 @CSRFRequired()
247 @CSRFRequired()
248 @view_config(
248 @view_config(
249 route_name='admin_settings_mapping_update', request_method='POST',
249 route_name='admin_settings_mapping_update', request_method='POST',
250 renderer='rhodecode:templates/admin/settings/settings.mako')
250 renderer='rhodecode:templates/admin/settings/settings.mako')
251 def settings_mapping_update(self):
251 def settings_mapping_update(self):
252 _ = self.request.translate
252 _ = self.request.translate
253 c = self.load_default_context()
253 c = self.load_default_context()
254 c.active = 'mapping'
254 c.active = 'mapping'
255 rm_obsolete = self.request.POST.get('destroy', False)
255 rm_obsolete = self.request.POST.get('destroy', False)
256 invalidate_cache = self.request.POST.get('invalidate', False)
256 invalidate_cache = self.request.POST.get('invalidate', False)
257 log.debug(
257 log.debug(
258 'rescanning repo location with destroy obsolete=%s', rm_obsolete)
258 'rescanning repo location with destroy obsolete=%s', rm_obsolete)
259
259
260 if invalidate_cache:
260 if invalidate_cache:
261 log.debug('invalidating all repositories cache')
261 log.debug('invalidating all repositories cache')
262 for repo in Repository.get_all():
262 for repo in Repository.get_all():
263 ScmModel().mark_for_invalidation(repo.repo_name, delete=True)
263 ScmModel().mark_for_invalidation(repo.repo_name, delete=True)
264
264
265 filesystem_repos = ScmModel().repo_scan()
265 filesystem_repos = ScmModel().repo_scan()
266 added, removed = repo2db_mapper(filesystem_repos, rm_obsolete)
266 added, removed = repo2db_mapper(filesystem_repos, rm_obsolete)
267 _repr = lambda l: ', '.join(map(safe_unicode, l)) or '-'
267 _repr = lambda l: ', '.join(map(safe_unicode, l)) or '-'
268 h.flash(_('Repositories successfully '
268 h.flash(_('Repositories successfully '
269 'rescanned added: %s ; removed: %s') %
269 'rescanned added: %s ; removed: %s') %
270 (_repr(added), _repr(removed)),
270 (_repr(added), _repr(removed)),
271 category='success')
271 category='success')
272 raise HTTPFound(h.route_path('admin_settings_mapping'))
272 raise HTTPFound(h.route_path('admin_settings_mapping'))
273
273
274 @LoginRequired()
274 @LoginRequired()
275 @HasPermissionAllDecorator('hg.admin')
275 @HasPermissionAllDecorator('hg.admin')
276 @view_config(
276 @view_config(
277 route_name='admin_settings', request_method='GET',
277 route_name='admin_settings', request_method='GET',
278 renderer='rhodecode:templates/admin/settings/settings.mako')
278 renderer='rhodecode:templates/admin/settings/settings.mako')
279 @view_config(
279 @view_config(
280 route_name='admin_settings_global', request_method='GET',
280 route_name='admin_settings_global', request_method='GET',
281 renderer='rhodecode:templates/admin/settings/settings.mako')
281 renderer='rhodecode:templates/admin/settings/settings.mako')
282 def settings_global(self):
282 def settings_global(self):
283 c = self.load_default_context()
283 c = self.load_default_context()
284 c.active = 'global'
284 c.active = 'global'
285 c.personal_repo_group_default_pattern = RepoGroupModel()\
285 c.personal_repo_group_default_pattern = RepoGroupModel()\
286 .get_personal_group_name_pattern()
286 .get_personal_group_name_pattern()
287
287
288 data = render('rhodecode:templates/admin/settings/settings.mako',
288 data = render('rhodecode:templates/admin/settings/settings.mako',
289 self._get_template_context(c), self.request)
289 self._get_template_context(c), self.request)
290 html = formencode.htmlfill.render(
290 html = formencode.htmlfill.render(
291 data,
291 data,
292 defaults=self._form_defaults(),
292 defaults=self._form_defaults(),
293 encoding="UTF-8",
293 encoding="UTF-8",
294 force_defaults=False
294 force_defaults=False
295 )
295 )
296 return Response(html)
296 return Response(html)
297
297
298 @LoginRequired()
298 @LoginRequired()
299 @HasPermissionAllDecorator('hg.admin')
299 @HasPermissionAllDecorator('hg.admin')
300 @CSRFRequired()
300 @CSRFRequired()
301 @view_config(
301 @view_config(
302 route_name='admin_settings_update', request_method='POST',
302 route_name='admin_settings_update', request_method='POST',
303 renderer='rhodecode:templates/admin/settings/settings.mako')
303 renderer='rhodecode:templates/admin/settings/settings.mako')
304 @view_config(
304 @view_config(
305 route_name='admin_settings_global_update', request_method='POST',
305 route_name='admin_settings_global_update', request_method='POST',
306 renderer='rhodecode:templates/admin/settings/settings.mako')
306 renderer='rhodecode:templates/admin/settings/settings.mako')
307 def settings_global_update(self):
307 def settings_global_update(self):
308 _ = self.request.translate
308 _ = self.request.translate
309 c = self.load_default_context()
309 c = self.load_default_context()
310 c.active = 'global'
310 c.active = 'global'
311 c.personal_repo_group_default_pattern = RepoGroupModel()\
311 c.personal_repo_group_default_pattern = RepoGroupModel()\
312 .get_personal_group_name_pattern()
312 .get_personal_group_name_pattern()
313 application_form = ApplicationSettingsForm(self.request.translate)()
313 application_form = ApplicationSettingsForm(self.request.translate)()
314 try:
314 try:
315 form_result = application_form.to_python(dict(self.request.POST))
315 form_result = application_form.to_python(dict(self.request.POST))
316 except formencode.Invalid as errors:
316 except formencode.Invalid as errors:
317 data = render('rhodecode:templates/admin/settings/settings.mako',
317 data = render('rhodecode:templates/admin/settings/settings.mako',
318 self._get_template_context(c), self.request)
318 self._get_template_context(c), self.request)
319 html = formencode.htmlfill.render(
319 html = formencode.htmlfill.render(
320 data,
320 data,
321 defaults=errors.value,
321 defaults=errors.value,
322 errors=errors.error_dict or {},
322 errors=errors.error_dict or {},
323 prefix_error=False,
323 prefix_error=False,
324 encoding="UTF-8",
324 encoding="UTF-8",
325 force_defaults=False
325 force_defaults=False
326 )
326 )
327 return Response(html)
327 return Response(html)
328
328
329 settings = [
329 settings = [
330 ('title', 'rhodecode_title', 'unicode'),
330 ('title', 'rhodecode_title', 'unicode'),
331 ('realm', 'rhodecode_realm', 'unicode'),
331 ('realm', 'rhodecode_realm', 'unicode'),
332 ('pre_code', 'rhodecode_pre_code', 'unicode'),
332 ('pre_code', 'rhodecode_pre_code', 'unicode'),
333 ('post_code', 'rhodecode_post_code', 'unicode'),
333 ('post_code', 'rhodecode_post_code', 'unicode'),
334 ('captcha_public_key', 'rhodecode_captcha_public_key', 'unicode'),
334 ('captcha_public_key', 'rhodecode_captcha_public_key', 'unicode'),
335 ('captcha_private_key', 'rhodecode_captcha_private_key', 'unicode'),
335 ('captcha_private_key', 'rhodecode_captcha_private_key', 'unicode'),
336 ('create_personal_repo_group', 'rhodecode_create_personal_repo_group', 'bool'),
336 ('create_personal_repo_group', 'rhodecode_create_personal_repo_group', 'bool'),
337 ('personal_repo_group_pattern', 'rhodecode_personal_repo_group_pattern', 'unicode'),
337 ('personal_repo_group_pattern', 'rhodecode_personal_repo_group_pattern', 'unicode'),
338 ]
338 ]
339 try:
339 try:
340 for setting, form_key, type_ in settings:
340 for setting, form_key, type_ in settings:
341 sett = SettingsModel().create_or_update_setting(
341 sett = SettingsModel().create_or_update_setting(
342 setting, form_result[form_key], type_)
342 setting, form_result[form_key], type_)
343 Session().add(sett)
343 Session().add(sett)
344
344
345 Session().commit()
345 Session().commit()
346 SettingsModel().invalidate_settings_cache()
346 SettingsModel().invalidate_settings_cache()
347 h.flash(_('Updated application settings'), category='success')
347 h.flash(_('Updated application settings'), category='success')
348 except Exception:
348 except Exception:
349 log.exception("Exception while updating application settings")
349 log.exception("Exception while updating application settings")
350 h.flash(
350 h.flash(
351 _('Error occurred during updating application settings'),
351 _('Error occurred during updating application settings'),
352 category='error')
352 category='error')
353
353
354 raise HTTPFound(h.route_path('admin_settings_global'))
354 raise HTTPFound(h.route_path('admin_settings_global'))
355
355
356 @LoginRequired()
356 @LoginRequired()
357 @HasPermissionAllDecorator('hg.admin')
357 @HasPermissionAllDecorator('hg.admin')
358 @view_config(
358 @view_config(
359 route_name='admin_settings_visual', request_method='GET',
359 route_name='admin_settings_visual', request_method='GET',
360 renderer='rhodecode:templates/admin/settings/settings.mako')
360 renderer='rhodecode:templates/admin/settings/settings.mako')
361 def settings_visual(self):
361 def settings_visual(self):
362 c = self.load_default_context()
362 c = self.load_default_context()
363 c.active = 'visual'
363 c.active = 'visual'
364
364
365 data = render('rhodecode:templates/admin/settings/settings.mako',
365 data = render('rhodecode:templates/admin/settings/settings.mako',
366 self._get_template_context(c), self.request)
366 self._get_template_context(c), self.request)
367 html = formencode.htmlfill.render(
367 html = formencode.htmlfill.render(
368 data,
368 data,
369 defaults=self._form_defaults(),
369 defaults=self._form_defaults(),
370 encoding="UTF-8",
370 encoding="UTF-8",
371 force_defaults=False
371 force_defaults=False
372 )
372 )
373 return Response(html)
373 return Response(html)
374
374
375 @LoginRequired()
375 @LoginRequired()
376 @HasPermissionAllDecorator('hg.admin')
376 @HasPermissionAllDecorator('hg.admin')
377 @CSRFRequired()
377 @CSRFRequired()
378 @view_config(
378 @view_config(
379 route_name='admin_settings_visual_update', request_method='POST',
379 route_name='admin_settings_visual_update', request_method='POST',
380 renderer='rhodecode:templates/admin/settings/settings.mako')
380 renderer='rhodecode:templates/admin/settings/settings.mako')
381 def settings_visual_update(self):
381 def settings_visual_update(self):
382 _ = self.request.translate
382 _ = self.request.translate
383 c = self.load_default_context()
383 c = self.load_default_context()
384 c.active = 'visual'
384 c.active = 'visual'
385 application_form = ApplicationVisualisationForm(self.request.translate)()
385 application_form = ApplicationVisualisationForm(self.request.translate)()
386 try:
386 try:
387 form_result = application_form.to_python(dict(self.request.POST))
387 form_result = application_form.to_python(dict(self.request.POST))
388 except formencode.Invalid as errors:
388 except formencode.Invalid as errors:
389 data = render('rhodecode:templates/admin/settings/settings.mako',
389 data = render('rhodecode:templates/admin/settings/settings.mako',
390 self._get_template_context(c), self.request)
390 self._get_template_context(c), self.request)
391 html = formencode.htmlfill.render(
391 html = formencode.htmlfill.render(
392 data,
392 data,
393 defaults=errors.value,
393 defaults=errors.value,
394 errors=errors.error_dict or {},
394 errors=errors.error_dict or {},
395 prefix_error=False,
395 prefix_error=False,
396 encoding="UTF-8",
396 encoding="UTF-8",
397 force_defaults=False
397 force_defaults=False
398 )
398 )
399 return Response(html)
399 return Response(html)
400
400
401 try:
401 try:
402 settings = [
402 settings = [
403 ('show_public_icon', 'rhodecode_show_public_icon', 'bool'),
403 ('show_public_icon', 'rhodecode_show_public_icon', 'bool'),
404 ('show_private_icon', 'rhodecode_show_private_icon', 'bool'),
404 ('show_private_icon', 'rhodecode_show_private_icon', 'bool'),
405 ('stylify_metatags', 'rhodecode_stylify_metatags', 'bool'),
405 ('stylify_metatags', 'rhodecode_stylify_metatags', 'bool'),
406 ('repository_fields', 'rhodecode_repository_fields', 'bool'),
406 ('repository_fields', 'rhodecode_repository_fields', 'bool'),
407 ('dashboard_items', 'rhodecode_dashboard_items', 'int'),
407 ('dashboard_items', 'rhodecode_dashboard_items', 'int'),
408 ('admin_grid_items', 'rhodecode_admin_grid_items', 'int'),
408 ('admin_grid_items', 'rhodecode_admin_grid_items', 'int'),
409 ('show_version', 'rhodecode_show_version', 'bool'),
409 ('show_version', 'rhodecode_show_version', 'bool'),
410 ('use_gravatar', 'rhodecode_use_gravatar', 'bool'),
410 ('use_gravatar', 'rhodecode_use_gravatar', 'bool'),
411 ('markup_renderer', 'rhodecode_markup_renderer', 'unicode'),
411 ('markup_renderer', 'rhodecode_markup_renderer', 'unicode'),
412 ('gravatar_url', 'rhodecode_gravatar_url', 'unicode'),
412 ('gravatar_url', 'rhodecode_gravatar_url', 'unicode'),
413 ('clone_uri_tmpl', 'rhodecode_clone_uri_tmpl', 'unicode'),
413 ('clone_uri_tmpl', 'rhodecode_clone_uri_tmpl', 'unicode'),
414 ('clone_uri_ssh_tmpl', 'rhodecode_clone_uri_ssh_tmpl', 'unicode'),
414 ('support_url', 'rhodecode_support_url', 'unicode'),
415 ('support_url', 'rhodecode_support_url', 'unicode'),
415 ('show_revision_number', 'rhodecode_show_revision_number', 'bool'),
416 ('show_revision_number', 'rhodecode_show_revision_number', 'bool'),
416 ('show_sha_length', 'rhodecode_show_sha_length', 'int'),
417 ('show_sha_length', 'rhodecode_show_sha_length', 'int'),
417 ]
418 ]
418 for setting, form_key, type_ in settings:
419 for setting, form_key, type_ in settings:
419 sett = SettingsModel().create_or_update_setting(
420 sett = SettingsModel().create_or_update_setting(
420 setting, form_result[form_key], type_)
421 setting, form_result[form_key], type_)
421 Session().add(sett)
422 Session().add(sett)
422
423
423 Session().commit()
424 Session().commit()
424 SettingsModel().invalidate_settings_cache()
425 SettingsModel().invalidate_settings_cache()
425 h.flash(_('Updated visualisation settings'), category='success')
426 h.flash(_('Updated visualisation settings'), category='success')
426 except Exception:
427 except Exception:
427 log.exception("Exception updating visualization settings")
428 log.exception("Exception updating visualization settings")
428 h.flash(_('Error occurred during updating '
429 h.flash(_('Error occurred during updating '
429 'visualisation settings'),
430 'visualisation settings'),
430 category='error')
431 category='error')
431
432
432 raise HTTPFound(h.route_path('admin_settings_visual'))
433 raise HTTPFound(h.route_path('admin_settings_visual'))
433
434
434 @LoginRequired()
435 @LoginRequired()
435 @HasPermissionAllDecorator('hg.admin')
436 @HasPermissionAllDecorator('hg.admin')
436 @view_config(
437 @view_config(
437 route_name='admin_settings_issuetracker', request_method='GET',
438 route_name='admin_settings_issuetracker', request_method='GET',
438 renderer='rhodecode:templates/admin/settings/settings.mako')
439 renderer='rhodecode:templates/admin/settings/settings.mako')
439 def settings_issuetracker(self):
440 def settings_issuetracker(self):
440 c = self.load_default_context()
441 c = self.load_default_context()
441 c.active = 'issuetracker'
442 c.active = 'issuetracker'
442 defaults = SettingsModel().get_all_settings()
443 defaults = SettingsModel().get_all_settings()
443
444
444 entry_key = 'rhodecode_issuetracker_pat_'
445 entry_key = 'rhodecode_issuetracker_pat_'
445
446
446 c.issuetracker_entries = {}
447 c.issuetracker_entries = {}
447 for k, v in defaults.items():
448 for k, v in defaults.items():
448 if k.startswith(entry_key):
449 if k.startswith(entry_key):
449 uid = k[len(entry_key):]
450 uid = k[len(entry_key):]
450 c.issuetracker_entries[uid] = None
451 c.issuetracker_entries[uid] = None
451
452
452 for uid in c.issuetracker_entries:
453 for uid in c.issuetracker_entries:
453 c.issuetracker_entries[uid] = AttributeDict({
454 c.issuetracker_entries[uid] = AttributeDict({
454 'pat': defaults.get('rhodecode_issuetracker_pat_' + uid),
455 'pat': defaults.get('rhodecode_issuetracker_pat_' + uid),
455 'url': defaults.get('rhodecode_issuetracker_url_' + uid),
456 'url': defaults.get('rhodecode_issuetracker_url_' + uid),
456 'pref': defaults.get('rhodecode_issuetracker_pref_' + uid),
457 'pref': defaults.get('rhodecode_issuetracker_pref_' + uid),
457 'desc': defaults.get('rhodecode_issuetracker_desc_' + uid),
458 'desc': defaults.get('rhodecode_issuetracker_desc_' + uid),
458 })
459 })
459
460
460 return self._get_template_context(c)
461 return self._get_template_context(c)
461
462
462 @LoginRequired()
463 @LoginRequired()
463 @HasPermissionAllDecorator('hg.admin')
464 @HasPermissionAllDecorator('hg.admin')
464 @CSRFRequired()
465 @CSRFRequired()
465 @view_config(
466 @view_config(
466 route_name='admin_settings_issuetracker_test', request_method='POST',
467 route_name='admin_settings_issuetracker_test', request_method='POST',
467 renderer='string', xhr=True)
468 renderer='string', xhr=True)
468 def settings_issuetracker_test(self):
469 def settings_issuetracker_test(self):
469 return h.urlify_commit_message(
470 return h.urlify_commit_message(
470 self.request.POST.get('test_text', ''),
471 self.request.POST.get('test_text', ''),
471 'repo_group/test_repo1')
472 'repo_group/test_repo1')
472
473
473 @LoginRequired()
474 @LoginRequired()
474 @HasPermissionAllDecorator('hg.admin')
475 @HasPermissionAllDecorator('hg.admin')
475 @CSRFRequired()
476 @CSRFRequired()
476 @view_config(
477 @view_config(
477 route_name='admin_settings_issuetracker_update', request_method='POST',
478 route_name='admin_settings_issuetracker_update', request_method='POST',
478 renderer='rhodecode:templates/admin/settings/settings.mako')
479 renderer='rhodecode:templates/admin/settings/settings.mako')
479 def settings_issuetracker_update(self):
480 def settings_issuetracker_update(self):
480 _ = self.request.translate
481 _ = self.request.translate
481 self.load_default_context()
482 self.load_default_context()
482 settings_model = IssueTrackerSettingsModel()
483 settings_model = IssueTrackerSettingsModel()
483
484
484 try:
485 try:
485 form = IssueTrackerPatternsForm(self.request.translate)()
486 form = IssueTrackerPatternsForm(self.request.translate)()
486 data = form.to_python(self.request.POST)
487 data = form.to_python(self.request.POST)
487 except formencode.Invalid as errors:
488 except formencode.Invalid as errors:
488 log.exception('Failed to add new pattern')
489 log.exception('Failed to add new pattern')
489 error = errors
490 error = errors
490 h.flash(_('Invalid issue tracker pattern: {}'.format(error)),
491 h.flash(_('Invalid issue tracker pattern: {}'.format(error)),
491 category='error')
492 category='error')
492 raise HTTPFound(h.route_path('admin_settings_issuetracker'))
493 raise HTTPFound(h.route_path('admin_settings_issuetracker'))
493
494
494 if data:
495 if data:
495 for uid in data.get('delete_patterns', []):
496 for uid in data.get('delete_patterns', []):
496 settings_model.delete_entries(uid)
497 settings_model.delete_entries(uid)
497
498
498 for pattern in data.get('patterns', []):
499 for pattern in data.get('patterns', []):
499 for setting, value, type_ in pattern:
500 for setting, value, type_ in pattern:
500 sett = settings_model.create_or_update_setting(
501 sett = settings_model.create_or_update_setting(
501 setting, value, type_)
502 setting, value, type_)
502 Session().add(sett)
503 Session().add(sett)
503
504
504 Session().commit()
505 Session().commit()
505
506
506 SettingsModel().invalidate_settings_cache()
507 SettingsModel().invalidate_settings_cache()
507 h.flash(_('Updated issue tracker entries'), category='success')
508 h.flash(_('Updated issue tracker entries'), category='success')
508 raise HTTPFound(h.route_path('admin_settings_issuetracker'))
509 raise HTTPFound(h.route_path('admin_settings_issuetracker'))
509
510
510 @LoginRequired()
511 @LoginRequired()
511 @HasPermissionAllDecorator('hg.admin')
512 @HasPermissionAllDecorator('hg.admin')
512 @CSRFRequired()
513 @CSRFRequired()
513 @view_config(
514 @view_config(
514 route_name='admin_settings_issuetracker_delete', request_method='POST',
515 route_name='admin_settings_issuetracker_delete', request_method='POST',
515 renderer='rhodecode:templates/admin/settings/settings.mako')
516 renderer='rhodecode:templates/admin/settings/settings.mako')
516 def settings_issuetracker_delete(self):
517 def settings_issuetracker_delete(self):
517 _ = self.request.translate
518 _ = self.request.translate
518 self.load_default_context()
519 self.load_default_context()
519 uid = self.request.POST.get('uid')
520 uid = self.request.POST.get('uid')
520 try:
521 try:
521 IssueTrackerSettingsModel().delete_entries(uid)
522 IssueTrackerSettingsModel().delete_entries(uid)
522 except Exception:
523 except Exception:
523 log.exception('Failed to delete issue tracker setting %s', uid)
524 log.exception('Failed to delete issue tracker setting %s', uid)
524 raise HTTPNotFound()
525 raise HTTPNotFound()
525 h.flash(_('Removed issue tracker entry'), category='success')
526 h.flash(_('Removed issue tracker entry'), category='success')
526 raise HTTPFound(h.route_path('admin_settings_issuetracker'))
527 raise HTTPFound(h.route_path('admin_settings_issuetracker'))
527
528
528 @LoginRequired()
529 @LoginRequired()
529 @HasPermissionAllDecorator('hg.admin')
530 @HasPermissionAllDecorator('hg.admin')
530 @view_config(
531 @view_config(
531 route_name='admin_settings_email', request_method='GET',
532 route_name='admin_settings_email', request_method='GET',
532 renderer='rhodecode:templates/admin/settings/settings.mako')
533 renderer='rhodecode:templates/admin/settings/settings.mako')
533 def settings_email(self):
534 def settings_email(self):
534 c = self.load_default_context()
535 c = self.load_default_context()
535 c.active = 'email'
536 c.active = 'email'
536 c.rhodecode_ini = rhodecode.CONFIG
537 c.rhodecode_ini = rhodecode.CONFIG
537
538
538 data = render('rhodecode:templates/admin/settings/settings.mako',
539 data = render('rhodecode:templates/admin/settings/settings.mako',
539 self._get_template_context(c), self.request)
540 self._get_template_context(c), self.request)
540 html = formencode.htmlfill.render(
541 html = formencode.htmlfill.render(
541 data,
542 data,
542 defaults=self._form_defaults(),
543 defaults=self._form_defaults(),
543 encoding="UTF-8",
544 encoding="UTF-8",
544 force_defaults=False
545 force_defaults=False
545 )
546 )
546 return Response(html)
547 return Response(html)
547
548
548 @LoginRequired()
549 @LoginRequired()
549 @HasPermissionAllDecorator('hg.admin')
550 @HasPermissionAllDecorator('hg.admin')
550 @CSRFRequired()
551 @CSRFRequired()
551 @view_config(
552 @view_config(
552 route_name='admin_settings_email_update', request_method='POST',
553 route_name='admin_settings_email_update', request_method='POST',
553 renderer='rhodecode:templates/admin/settings/settings.mako')
554 renderer='rhodecode:templates/admin/settings/settings.mako')
554 def settings_email_update(self):
555 def settings_email_update(self):
555 _ = self.request.translate
556 _ = self.request.translate
556 c = self.load_default_context()
557 c = self.load_default_context()
557 c.active = 'email'
558 c.active = 'email'
558
559
559 test_email = self.request.POST.get('test_email')
560 test_email = self.request.POST.get('test_email')
560
561
561 if not test_email:
562 if not test_email:
562 h.flash(_('Please enter email address'), category='error')
563 h.flash(_('Please enter email address'), category='error')
563 raise HTTPFound(h.route_path('admin_settings_email'))
564 raise HTTPFound(h.route_path('admin_settings_email'))
564
565
565 email_kwargs = {
566 email_kwargs = {
566 'date': datetime.datetime.now(),
567 'date': datetime.datetime.now(),
567 'user': c.rhodecode_user,
568 'user': c.rhodecode_user,
568 'rhodecode_version': c.rhodecode_version
569 'rhodecode_version': c.rhodecode_version
569 }
570 }
570
571
571 (subject, headers, email_body,
572 (subject, headers, email_body,
572 email_body_plaintext) = EmailNotificationModel().render_email(
573 email_body_plaintext) = EmailNotificationModel().render_email(
573 EmailNotificationModel.TYPE_EMAIL_TEST, **email_kwargs)
574 EmailNotificationModel.TYPE_EMAIL_TEST, **email_kwargs)
574
575
575 recipients = [test_email] if test_email else None
576 recipients = [test_email] if test_email else None
576
577
577 run_task(tasks.send_email, recipients, subject,
578 run_task(tasks.send_email, recipients, subject,
578 email_body_plaintext, email_body)
579 email_body_plaintext, email_body)
579
580
580 h.flash(_('Send email task created'), category='success')
581 h.flash(_('Send email task created'), category='success')
581 raise HTTPFound(h.route_path('admin_settings_email'))
582 raise HTTPFound(h.route_path('admin_settings_email'))
582
583
583 @LoginRequired()
584 @LoginRequired()
584 @HasPermissionAllDecorator('hg.admin')
585 @HasPermissionAllDecorator('hg.admin')
585 @view_config(
586 @view_config(
586 route_name='admin_settings_hooks', request_method='GET',
587 route_name='admin_settings_hooks', request_method='GET',
587 renderer='rhodecode:templates/admin/settings/settings.mako')
588 renderer='rhodecode:templates/admin/settings/settings.mako')
588 def settings_hooks(self):
589 def settings_hooks(self):
589 c = self.load_default_context()
590 c = self.load_default_context()
590 c.active = 'hooks'
591 c.active = 'hooks'
591
592
592 model = SettingsModel()
593 model = SettingsModel()
593 c.hooks = model.get_builtin_hooks()
594 c.hooks = model.get_builtin_hooks()
594 c.custom_hooks = model.get_custom_hooks()
595 c.custom_hooks = model.get_custom_hooks()
595
596
596 data = render('rhodecode:templates/admin/settings/settings.mako',
597 data = render('rhodecode:templates/admin/settings/settings.mako',
597 self._get_template_context(c), self.request)
598 self._get_template_context(c), self.request)
598 html = formencode.htmlfill.render(
599 html = formencode.htmlfill.render(
599 data,
600 data,
600 defaults=self._form_defaults(),
601 defaults=self._form_defaults(),
601 encoding="UTF-8",
602 encoding="UTF-8",
602 force_defaults=False
603 force_defaults=False
603 )
604 )
604 return Response(html)
605 return Response(html)
605
606
606 @LoginRequired()
607 @LoginRequired()
607 @HasPermissionAllDecorator('hg.admin')
608 @HasPermissionAllDecorator('hg.admin')
608 @CSRFRequired()
609 @CSRFRequired()
609 @view_config(
610 @view_config(
610 route_name='admin_settings_hooks_update', request_method='POST',
611 route_name='admin_settings_hooks_update', request_method='POST',
611 renderer='rhodecode:templates/admin/settings/settings.mako')
612 renderer='rhodecode:templates/admin/settings/settings.mako')
612 @view_config(
613 @view_config(
613 route_name='admin_settings_hooks_delete', request_method='POST',
614 route_name='admin_settings_hooks_delete', request_method='POST',
614 renderer='rhodecode:templates/admin/settings/settings.mako')
615 renderer='rhodecode:templates/admin/settings/settings.mako')
615 def settings_hooks_update(self):
616 def settings_hooks_update(self):
616 _ = self.request.translate
617 _ = self.request.translate
617 c = self.load_default_context()
618 c = self.load_default_context()
618 c.active = 'hooks'
619 c.active = 'hooks'
619 if c.visual.allow_custom_hooks_settings:
620 if c.visual.allow_custom_hooks_settings:
620 ui_key = self.request.POST.get('new_hook_ui_key')
621 ui_key = self.request.POST.get('new_hook_ui_key')
621 ui_value = self.request.POST.get('new_hook_ui_value')
622 ui_value = self.request.POST.get('new_hook_ui_value')
622
623
623 hook_id = self.request.POST.get('hook_id')
624 hook_id = self.request.POST.get('hook_id')
624 new_hook = False
625 new_hook = False
625
626
626 model = SettingsModel()
627 model = SettingsModel()
627 try:
628 try:
628 if ui_value and ui_key:
629 if ui_value and ui_key:
629 model.create_or_update_hook(ui_key, ui_value)
630 model.create_or_update_hook(ui_key, ui_value)
630 h.flash(_('Added new hook'), category='success')
631 h.flash(_('Added new hook'), category='success')
631 new_hook = True
632 new_hook = True
632 elif hook_id:
633 elif hook_id:
633 RhodeCodeUi.delete(hook_id)
634 RhodeCodeUi.delete(hook_id)
634 Session().commit()
635 Session().commit()
635
636
636 # check for edits
637 # check for edits
637 update = False
638 update = False
638 _d = self.request.POST.dict_of_lists()
639 _d = self.request.POST.dict_of_lists()
639 for k, v in zip(_d.get('hook_ui_key', []),
640 for k, v in zip(_d.get('hook_ui_key', []),
640 _d.get('hook_ui_value_new', [])):
641 _d.get('hook_ui_value_new', [])):
641 model.create_or_update_hook(k, v)
642 model.create_or_update_hook(k, v)
642 update = True
643 update = True
643
644
644 if update and not new_hook:
645 if update and not new_hook:
645 h.flash(_('Updated hooks'), category='success')
646 h.flash(_('Updated hooks'), category='success')
646 Session().commit()
647 Session().commit()
647 except Exception:
648 except Exception:
648 log.exception("Exception during hook creation")
649 log.exception("Exception during hook creation")
649 h.flash(_('Error occurred during hook creation'),
650 h.flash(_('Error occurred during hook creation'),
650 category='error')
651 category='error')
651
652
652 raise HTTPFound(h.route_path('admin_settings_hooks'))
653 raise HTTPFound(h.route_path('admin_settings_hooks'))
653
654
654 @LoginRequired()
655 @LoginRequired()
655 @HasPermissionAllDecorator('hg.admin')
656 @HasPermissionAllDecorator('hg.admin')
656 @view_config(
657 @view_config(
657 route_name='admin_settings_search', request_method='GET',
658 route_name='admin_settings_search', request_method='GET',
658 renderer='rhodecode:templates/admin/settings/settings.mako')
659 renderer='rhodecode:templates/admin/settings/settings.mako')
659 def settings_search(self):
660 def settings_search(self):
660 c = self.load_default_context()
661 c = self.load_default_context()
661 c.active = 'search'
662 c.active = 'search'
662
663
663 searcher = searcher_from_config(self.request.registry.settings)
664 searcher = searcher_from_config(self.request.registry.settings)
664 c.statistics = searcher.statistics(self.request.translate)
665 c.statistics = searcher.statistics(self.request.translate)
665
666
666 return self._get_template_context(c)
667 return self._get_template_context(c)
667
668
668 @LoginRequired()
669 @LoginRequired()
669 @HasPermissionAllDecorator('hg.admin')
670 @HasPermissionAllDecorator('hg.admin')
670 @view_config(
671 @view_config(
671 route_name='admin_settings_labs', request_method='GET',
672 route_name='admin_settings_labs', request_method='GET',
672 renderer='rhodecode:templates/admin/settings/settings.mako')
673 renderer='rhodecode:templates/admin/settings/settings.mako')
673 def settings_labs(self):
674 def settings_labs(self):
674 c = self.load_default_context()
675 c = self.load_default_context()
675 if not c.labs_active:
676 if not c.labs_active:
676 raise HTTPFound(h.route_path('admin_settings'))
677 raise HTTPFound(h.route_path('admin_settings'))
677
678
678 c.active = 'labs'
679 c.active = 'labs'
679 c.lab_settings = _LAB_SETTINGS
680 c.lab_settings = _LAB_SETTINGS
680
681
681 data = render('rhodecode:templates/admin/settings/settings.mako',
682 data = render('rhodecode:templates/admin/settings/settings.mako',
682 self._get_template_context(c), self.request)
683 self._get_template_context(c), self.request)
683 html = formencode.htmlfill.render(
684 html = formencode.htmlfill.render(
684 data,
685 data,
685 defaults=self._form_defaults(),
686 defaults=self._form_defaults(),
686 encoding="UTF-8",
687 encoding="UTF-8",
687 force_defaults=False
688 force_defaults=False
688 )
689 )
689 return Response(html)
690 return Response(html)
690
691
691 @LoginRequired()
692 @LoginRequired()
692 @HasPermissionAllDecorator('hg.admin')
693 @HasPermissionAllDecorator('hg.admin')
693 @CSRFRequired()
694 @CSRFRequired()
694 @view_config(
695 @view_config(
695 route_name='admin_settings_labs_update', request_method='POST',
696 route_name='admin_settings_labs_update', request_method='POST',
696 renderer='rhodecode:templates/admin/settings/settings.mako')
697 renderer='rhodecode:templates/admin/settings/settings.mako')
697 def settings_labs_update(self):
698 def settings_labs_update(self):
698 _ = self.request.translate
699 _ = self.request.translate
699 c = self.load_default_context()
700 c = self.load_default_context()
700 c.active = 'labs'
701 c.active = 'labs'
701
702
702 application_form = LabsSettingsForm(self.request.translate)()
703 application_form = LabsSettingsForm(self.request.translate)()
703 try:
704 try:
704 form_result = application_form.to_python(dict(self.request.POST))
705 form_result = application_form.to_python(dict(self.request.POST))
705 except formencode.Invalid as errors:
706 except formencode.Invalid as errors:
706 h.flash(
707 h.flash(
707 _('Some form inputs contain invalid data.'),
708 _('Some form inputs contain invalid data.'),
708 category='error')
709 category='error')
709 data = render('rhodecode:templates/admin/settings/settings.mako',
710 data = render('rhodecode:templates/admin/settings/settings.mako',
710 self._get_template_context(c), self.request)
711 self._get_template_context(c), self.request)
711 html = formencode.htmlfill.render(
712 html = formencode.htmlfill.render(
712 data,
713 data,
713 defaults=errors.value,
714 defaults=errors.value,
714 errors=errors.error_dict or {},
715 errors=errors.error_dict or {},
715 prefix_error=False,
716 prefix_error=False,
716 encoding="UTF-8",
717 encoding="UTF-8",
717 force_defaults=False
718 force_defaults=False
718 )
719 )
719 return Response(html)
720 return Response(html)
720
721
721 try:
722 try:
722 session = Session()
723 session = Session()
723 for setting in _LAB_SETTINGS:
724 for setting in _LAB_SETTINGS:
724 setting_name = setting.key[len('rhodecode_'):]
725 setting_name = setting.key[len('rhodecode_'):]
725 sett = SettingsModel().create_or_update_setting(
726 sett = SettingsModel().create_or_update_setting(
726 setting_name, form_result[setting.key], setting.type)
727 setting_name, form_result[setting.key], setting.type)
727 session.add(sett)
728 session.add(sett)
728
729
729 except Exception:
730 except Exception:
730 log.exception('Exception while updating lab settings')
731 log.exception('Exception while updating lab settings')
731 h.flash(_('Error occurred during updating labs settings'),
732 h.flash(_('Error occurred during updating labs settings'),
732 category='error')
733 category='error')
733 else:
734 else:
734 Session().commit()
735 Session().commit()
735 SettingsModel().invalidate_settings_cache()
736 SettingsModel().invalidate_settings_cache()
736 h.flash(_('Updated Labs settings'), category='success')
737 h.flash(_('Updated Labs settings'), category='success')
737 raise HTTPFound(h.route_path('admin_settings_labs'))
738 raise HTTPFound(h.route_path('admin_settings_labs'))
738
739
739 data = render('rhodecode:templates/admin/settings/settings.mako',
740 data = render('rhodecode:templates/admin/settings/settings.mako',
740 self._get_template_context(c), self.request)
741 self._get_template_context(c), self.request)
741 html = formencode.htmlfill.render(
742 html = formencode.htmlfill.render(
742 data,
743 data,
743 defaults=self._form_defaults(),
744 defaults=self._form_defaults(),
744 encoding="UTF-8",
745 encoding="UTF-8",
745 force_defaults=False
746 force_defaults=False
746 )
747 )
747 return Response(html)
748 return Response(html)
748
749
749
750
750 # :param key: name of the setting including the 'rhodecode_' prefix
751 # :param key: name of the setting including the 'rhodecode_' prefix
751 # :param type: the RhodeCodeSetting type to use.
752 # :param type: the RhodeCodeSetting type to use.
752 # :param group: the i18ned group in which we should dispaly this setting
753 # :param group: the i18ned group in which we should dispaly this setting
753 # :param label: the i18ned label we should display for this setting
754 # :param label: the i18ned label we should display for this setting
754 # :param help: the i18ned help we should dispaly for this setting
755 # :param help: the i18ned help we should dispaly for this setting
755 LabSetting = collections.namedtuple(
756 LabSetting = collections.namedtuple(
756 'LabSetting', ('key', 'type', 'group', 'label', 'help'))
757 'LabSetting', ('key', 'type', 'group', 'label', 'help'))
757
758
758
759
759 # This list has to be kept in sync with the form
760 # This list has to be kept in sync with the form
760 # rhodecode.model.forms.LabsSettingsForm.
761 # rhodecode.model.forms.LabsSettingsForm.
761 _LAB_SETTINGS = [
762 _LAB_SETTINGS = [
762
763
763 ]
764 ]
@@ -1,371 +1,375 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2018 RhodeCode GmbH
3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
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/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import logging
21 import logging
22 import string
22 import string
23
23
24 from pyramid.view import view_config
24 from pyramid.view import view_config
25 from beaker.cache import cache_region
25 from beaker.cache import cache_region
26
26
27 from rhodecode.controllers import utils
27 from rhodecode.controllers import utils
28 from rhodecode.apps._base import RepoAppView
28 from rhodecode.apps._base import RepoAppView
29 from rhodecode.config.conf import (LANGUAGES_EXTENSIONS_MAP)
29 from rhodecode.config.conf import (LANGUAGES_EXTENSIONS_MAP)
30 from rhodecode.lib import caches, helpers as h
30 from rhodecode.lib import caches, helpers as h
31 from rhodecode.lib.helpers import RepoPage
31 from rhodecode.lib.helpers import RepoPage
32 from rhodecode.lib.utils2 import safe_str, safe_int
32 from rhodecode.lib.utils2 import safe_str, safe_int
33 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
33 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
34 from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links
34 from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links
35 from rhodecode.lib.ext_json import json
35 from rhodecode.lib.ext_json import json
36 from rhodecode.lib.vcs.backends.base import EmptyCommit
36 from rhodecode.lib.vcs.backends.base import EmptyCommit
37 from rhodecode.lib.vcs.exceptions import CommitError, EmptyRepositoryError, \
37 from rhodecode.lib.vcs.exceptions import CommitError, EmptyRepositoryError, \
38 CommitDoesNotExistError
38 CommitDoesNotExistError
39 from rhodecode.model.db import Statistics, CacheKey, User
39 from rhodecode.model.db import Statistics, CacheKey, User
40 from rhodecode.model.meta import Session
40 from rhodecode.model.meta import Session
41 from rhodecode.model.repo import ReadmeFinder
41 from rhodecode.model.repo import ReadmeFinder
42 from rhodecode.model.scm import ScmModel
42 from rhodecode.model.scm import ScmModel
43
43
44 log = logging.getLogger(__name__)
44 log = logging.getLogger(__name__)
45
45
46
46
47 class RepoSummaryView(RepoAppView):
47 class RepoSummaryView(RepoAppView):
48
48
49 def load_default_context(self):
49 def load_default_context(self):
50 c = self._get_local_tmpl_context(include_app_defaults=True)
50 c = self._get_local_tmpl_context(include_app_defaults=True)
51
51
52 c.rhodecode_repo = None
52 c.rhodecode_repo = None
53 if not c.repository_requirements_missing:
53 if not c.repository_requirements_missing:
54 c.rhodecode_repo = self.rhodecode_vcs_repo
54 c.rhodecode_repo = self.rhodecode_vcs_repo
55
55
56
56
57 return c
57 return c
58
58
59 def _get_readme_data(self, db_repo, default_renderer):
59 def _get_readme_data(self, db_repo, default_renderer):
60 repo_name = db_repo.repo_name
60 repo_name = db_repo.repo_name
61 log.debug('Looking for README file')
61 log.debug('Looking for README file')
62
62
63 @cache_region('long_term')
63 @cache_region('long_term')
64 def _generate_readme(cache_key):
64 def _generate_readme(cache_key):
65 readme_data = None
65 readme_data = None
66 readme_node = None
66 readme_node = None
67 readme_filename = None
67 readme_filename = None
68 commit = self._get_landing_commit_or_none(db_repo)
68 commit = self._get_landing_commit_or_none(db_repo)
69 if commit:
69 if commit:
70 log.debug("Searching for a README file.")
70 log.debug("Searching for a README file.")
71 readme_node = ReadmeFinder(default_renderer).search(commit)
71 readme_node = ReadmeFinder(default_renderer).search(commit)
72 if readme_node:
72 if readme_node:
73 relative_urls = {
73 relative_urls = {
74 'raw': h.route_path(
74 'raw': h.route_path(
75 'repo_file_raw', repo_name=repo_name,
75 'repo_file_raw', repo_name=repo_name,
76 commit_id=commit.raw_id, f_path=readme_node.path),
76 commit_id=commit.raw_id, f_path=readme_node.path),
77 'standard': h.route_path(
77 'standard': h.route_path(
78 'repo_files', repo_name=repo_name,
78 'repo_files', repo_name=repo_name,
79 commit_id=commit.raw_id, f_path=readme_node.path),
79 commit_id=commit.raw_id, f_path=readme_node.path),
80 }
80 }
81 readme_data = self._render_readme_or_none(
81 readme_data = self._render_readme_or_none(
82 commit, readme_node, relative_urls)
82 commit, readme_node, relative_urls)
83 readme_filename = readme_node.path
83 readme_filename = readme_node.path
84 return readme_data, readme_filename
84 return readme_data, readme_filename
85
85
86 invalidator_context = CacheKey.repo_context_cache(
86 invalidator_context = CacheKey.repo_context_cache(
87 _generate_readme, repo_name, CacheKey.CACHE_TYPE_README)
87 _generate_readme, repo_name, CacheKey.CACHE_TYPE_README)
88
88
89 with invalidator_context as context:
89 with invalidator_context as context:
90 context.invalidate()
90 context.invalidate()
91 computed = context.compute()
91 computed = context.compute()
92
92
93 return computed
93 return computed
94
94
95 def _get_landing_commit_or_none(self, db_repo):
95 def _get_landing_commit_or_none(self, db_repo):
96 log.debug("Getting the landing commit.")
96 log.debug("Getting the landing commit.")
97 try:
97 try:
98 commit = db_repo.get_landing_commit()
98 commit = db_repo.get_landing_commit()
99 if not isinstance(commit, EmptyCommit):
99 if not isinstance(commit, EmptyCommit):
100 return commit
100 return commit
101 else:
101 else:
102 log.debug("Repository is empty, no README to render.")
102 log.debug("Repository is empty, no README to render.")
103 except CommitError:
103 except CommitError:
104 log.exception(
104 log.exception(
105 "Problem getting commit when trying to render the README.")
105 "Problem getting commit when trying to render the README.")
106
106
107 def _render_readme_or_none(self, commit, readme_node, relative_urls):
107 def _render_readme_or_none(self, commit, readme_node, relative_urls):
108 log.debug(
108 log.debug(
109 'Found README file `%s` rendering...', readme_node.path)
109 'Found README file `%s` rendering...', readme_node.path)
110 renderer = MarkupRenderer()
110 renderer = MarkupRenderer()
111 try:
111 try:
112 html_source = renderer.render(
112 html_source = renderer.render(
113 readme_node.content, filename=readme_node.path)
113 readme_node.content, filename=readme_node.path)
114 if relative_urls:
114 if relative_urls:
115 return relative_links(html_source, relative_urls)
115 return relative_links(html_source, relative_urls)
116 return html_source
116 return html_source
117 except Exception:
117 except Exception:
118 log.exception(
118 log.exception(
119 "Exception while trying to render the README")
119 "Exception while trying to render the README")
120
120
121 def _load_commits_context(self, c):
121 def _load_commits_context(self, c):
122 p = safe_int(self.request.GET.get('page'), 1)
122 p = safe_int(self.request.GET.get('page'), 1)
123 size = safe_int(self.request.GET.get('size'), 10)
123 size = safe_int(self.request.GET.get('size'), 10)
124
124
125 def url_generator(**kw):
125 def url_generator(**kw):
126 query_params = {
126 query_params = {
127 'size': size
127 'size': size
128 }
128 }
129 query_params.update(kw)
129 query_params.update(kw)
130 return h.route_path(
130 return h.route_path(
131 'repo_summary_commits',
131 'repo_summary_commits',
132 repo_name=c.rhodecode_db_repo.repo_name, _query=query_params)
132 repo_name=c.rhodecode_db_repo.repo_name, _query=query_params)
133
133
134 pre_load = ['author', 'branch', 'date', 'message']
134 pre_load = ['author', 'branch', 'date', 'message']
135 try:
135 try:
136 collection = self.rhodecode_vcs_repo.get_commits(pre_load=pre_load)
136 collection = self.rhodecode_vcs_repo.get_commits(pre_load=pre_load)
137 except EmptyRepositoryError:
137 except EmptyRepositoryError:
138 collection = self.rhodecode_vcs_repo
138 collection = self.rhodecode_vcs_repo
139
139
140 c.repo_commits = RepoPage(
140 c.repo_commits = RepoPage(
141 collection, page=p, items_per_page=size, url=url_generator)
141 collection, page=p, items_per_page=size, url=url_generator)
142 page_ids = [x.raw_id for x in c.repo_commits]
142 page_ids = [x.raw_id for x in c.repo_commits]
143 c.comments = self.db_repo.get_comments(page_ids)
143 c.comments = self.db_repo.get_comments(page_ids)
144 c.statuses = self.db_repo.statuses(page_ids)
144 c.statuses = self.db_repo.statuses(page_ids)
145
145
146 @LoginRequired()
146 @LoginRequired()
147 @HasRepoPermissionAnyDecorator(
147 @HasRepoPermissionAnyDecorator(
148 'repository.read', 'repository.write', 'repository.admin')
148 'repository.read', 'repository.write', 'repository.admin')
149 @view_config(
149 @view_config(
150 route_name='repo_summary_commits', request_method='GET',
150 route_name='repo_summary_commits', request_method='GET',
151 renderer='rhodecode:templates/summary/summary_commits.mako')
151 renderer='rhodecode:templates/summary/summary_commits.mako')
152 def summary_commits(self):
152 def summary_commits(self):
153 c = self.load_default_context()
153 c = self.load_default_context()
154 self._load_commits_context(c)
154 self._load_commits_context(c)
155 return self._get_template_context(c)
155 return self._get_template_context(c)
156
156
157 @LoginRequired()
157 @LoginRequired()
158 @HasRepoPermissionAnyDecorator(
158 @HasRepoPermissionAnyDecorator(
159 'repository.read', 'repository.write', 'repository.admin')
159 'repository.read', 'repository.write', 'repository.admin')
160 @view_config(
160 @view_config(
161 route_name='repo_summary', request_method='GET',
161 route_name='repo_summary', request_method='GET',
162 renderer='rhodecode:templates/summary/summary.mako')
162 renderer='rhodecode:templates/summary/summary.mako')
163 @view_config(
163 @view_config(
164 route_name='repo_summary_slash', request_method='GET',
164 route_name='repo_summary_slash', request_method='GET',
165 renderer='rhodecode:templates/summary/summary.mako')
165 renderer='rhodecode:templates/summary/summary.mako')
166 @view_config(
166 @view_config(
167 route_name='repo_summary_explicit', request_method='GET',
167 route_name='repo_summary_explicit', request_method='GET',
168 renderer='rhodecode:templates/summary/summary.mako')
168 renderer='rhodecode:templates/summary/summary.mako')
169 def summary(self):
169 def summary(self):
170 c = self.load_default_context()
170 c = self.load_default_context()
171
171
172 # Prepare the clone URL
172 # Prepare the clone URL
173 username = ''
173 username = ''
174 if self._rhodecode_user.username != User.DEFAULT_USER:
174 if self._rhodecode_user.username != User.DEFAULT_USER:
175 username = safe_str(self._rhodecode_user.username)
175 username = safe_str(self._rhodecode_user.username)
176
176
177 _def_clone_uri = _def_clone_uri_by_id = c.clone_uri_tmpl
177 _def_clone_uri = _def_clone_uri_id = c.clone_uri_tmpl
178 _def_clone_uri_ssh = c.clone_uri_ssh_tmpl
179
178 if '{repo}' in _def_clone_uri:
180 if '{repo}' in _def_clone_uri:
179 _def_clone_uri_by_id = _def_clone_uri.replace(
181 _def_clone_uri_id = _def_clone_uri.replace(
180 '{repo}', '_{repoid}')
182 '{repo}', '_{repoid}')
181 elif '{repoid}' in _def_clone_uri:
183 elif '{repoid}' in _def_clone_uri:
182 _def_clone_uri_by_id = _def_clone_uri.replace(
184 _def_clone_uri_id = _def_clone_uri.replace(
183 '_{repoid}', '{repo}')
185 '_{repoid}', '{repo}')
184
186
185 c.clone_repo_url = self.db_repo.clone_url(
187 c.clone_repo_url = self.db_repo.clone_url(
186 user=username, uri_tmpl=_def_clone_uri)
188 user=username, uri_tmpl=_def_clone_uri)
187 c.clone_repo_url_id = self.db_repo.clone_url(
189 c.clone_repo_url_id = self.db_repo.clone_url(
188 user=username, uri_tmpl=_def_clone_uri_by_id)
190 user=username, uri_tmpl=_def_clone_uri_id)
191 c.clone_repo_url_ssh = self.db_repo.clone_url(
192 uri_tmpl=_def_clone_uri_ssh, ssh=True)
189
193
190 # If enabled, get statistics data
194 # If enabled, get statistics data
191
195
192 c.show_stats = bool(self.db_repo.enable_statistics)
196 c.show_stats = bool(self.db_repo.enable_statistics)
193
197
194 stats = Session().query(Statistics) \
198 stats = Session().query(Statistics) \
195 .filter(Statistics.repository == self.db_repo) \
199 .filter(Statistics.repository == self.db_repo) \
196 .scalar()
200 .scalar()
197
201
198 c.stats_percentage = 0
202 c.stats_percentage = 0
199
203
200 if stats and stats.languages:
204 if stats and stats.languages:
201 c.no_data = False is self.db_repo.enable_statistics
205 c.no_data = False is self.db_repo.enable_statistics
202 lang_stats_d = json.loads(stats.languages)
206 lang_stats_d = json.loads(stats.languages)
203
207
204 # Sort first by decreasing count and second by the file extension,
208 # Sort first by decreasing count and second by the file extension,
205 # so we have a consistent output.
209 # so we have a consistent output.
206 lang_stats_items = sorted(lang_stats_d.iteritems(),
210 lang_stats_items = sorted(lang_stats_d.iteritems(),
207 key=lambda k: (-k[1], k[0]))[:10]
211 key=lambda k: (-k[1], k[0]))[:10]
208 lang_stats = [(x, {"count": y,
212 lang_stats = [(x, {"count": y,
209 "desc": LANGUAGES_EXTENSIONS_MAP.get(x)})
213 "desc": LANGUAGES_EXTENSIONS_MAP.get(x)})
210 for x, y in lang_stats_items]
214 for x, y in lang_stats_items]
211
215
212 c.trending_languages = json.dumps(lang_stats)
216 c.trending_languages = json.dumps(lang_stats)
213 else:
217 else:
214 c.no_data = True
218 c.no_data = True
215 c.trending_languages = json.dumps({})
219 c.trending_languages = json.dumps({})
216
220
217 scm_model = ScmModel()
221 scm_model = ScmModel()
218 c.enable_downloads = self.db_repo.enable_downloads
222 c.enable_downloads = self.db_repo.enable_downloads
219 c.repository_followers = scm_model.get_followers(self.db_repo)
223 c.repository_followers = scm_model.get_followers(self.db_repo)
220 c.repository_forks = scm_model.get_forks(self.db_repo)
224 c.repository_forks = scm_model.get_forks(self.db_repo)
221 c.repository_is_user_following = scm_model.is_following_repo(
225 c.repository_is_user_following = scm_model.is_following_repo(
222 self.db_repo_name, self._rhodecode_user.user_id)
226 self.db_repo_name, self._rhodecode_user.user_id)
223
227
224 # first interaction with the VCS instance after here...
228 # first interaction with the VCS instance after here...
225 if c.repository_requirements_missing:
229 if c.repository_requirements_missing:
226 self.request.override_renderer = \
230 self.request.override_renderer = \
227 'rhodecode:templates/summary/missing_requirements.mako'
231 'rhodecode:templates/summary/missing_requirements.mako'
228 return self._get_template_context(c)
232 return self._get_template_context(c)
229
233
230 c.readme_data, c.readme_file = \
234 c.readme_data, c.readme_file = \
231 self._get_readme_data(self.db_repo, c.visual.default_renderer)
235 self._get_readme_data(self.db_repo, c.visual.default_renderer)
232
236
233 # loads the summary commits template context
237 # loads the summary commits template context
234 self._load_commits_context(c)
238 self._load_commits_context(c)
235
239
236 return self._get_template_context(c)
240 return self._get_template_context(c)
237
241
238 def get_request_commit_id(self):
242 def get_request_commit_id(self):
239 return self.request.matchdict['commit_id']
243 return self.request.matchdict['commit_id']
240
244
241 @LoginRequired()
245 @LoginRequired()
242 @HasRepoPermissionAnyDecorator(
246 @HasRepoPermissionAnyDecorator(
243 'repository.read', 'repository.write', 'repository.admin')
247 'repository.read', 'repository.write', 'repository.admin')
244 @view_config(
248 @view_config(
245 route_name='repo_stats', request_method='GET',
249 route_name='repo_stats', request_method='GET',
246 renderer='json_ext')
250 renderer='json_ext')
247 def repo_stats(self):
251 def repo_stats(self):
248 commit_id = self.get_request_commit_id()
252 commit_id = self.get_request_commit_id()
249
253
250 _namespace = caches.get_repo_namespace_key(
254 _namespace = caches.get_repo_namespace_key(
251 caches.SUMMARY_STATS, self.db_repo_name)
255 caches.SUMMARY_STATS, self.db_repo_name)
252 show_stats = bool(self.db_repo.enable_statistics)
256 show_stats = bool(self.db_repo.enable_statistics)
253 cache_manager = caches.get_cache_manager(
257 cache_manager = caches.get_cache_manager(
254 'repo_cache_long', _namespace)
258 'repo_cache_long', _namespace)
255 _cache_key = caches.compute_key_from_params(
259 _cache_key = caches.compute_key_from_params(
256 self.db_repo_name, commit_id, show_stats)
260 self.db_repo_name, commit_id, show_stats)
257
261
258 def compute_stats():
262 def compute_stats():
259 code_stats = {}
263 code_stats = {}
260 size = 0
264 size = 0
261 try:
265 try:
262 scm_instance = self.db_repo.scm_instance()
266 scm_instance = self.db_repo.scm_instance()
263 commit = scm_instance.get_commit(commit_id)
267 commit = scm_instance.get_commit(commit_id)
264
268
265 for node in commit.get_filenodes_generator():
269 for node in commit.get_filenodes_generator():
266 size += node.size
270 size += node.size
267 if not show_stats:
271 if not show_stats:
268 continue
272 continue
269 ext = string.lower(node.extension)
273 ext = string.lower(node.extension)
270 ext_info = LANGUAGES_EXTENSIONS_MAP.get(ext)
274 ext_info = LANGUAGES_EXTENSIONS_MAP.get(ext)
271 if ext_info:
275 if ext_info:
272 if ext in code_stats:
276 if ext in code_stats:
273 code_stats[ext]['count'] += 1
277 code_stats[ext]['count'] += 1
274 else:
278 else:
275 code_stats[ext] = {"count": 1, "desc": ext_info}
279 code_stats[ext] = {"count": 1, "desc": ext_info}
276 except (EmptyRepositoryError, CommitDoesNotExistError):
280 except (EmptyRepositoryError, CommitDoesNotExistError):
277 pass
281 pass
278 return {'size': h.format_byte_size_binary(size),
282 return {'size': h.format_byte_size_binary(size),
279 'code_stats': code_stats}
283 'code_stats': code_stats}
280
284
281 stats = cache_manager.get(_cache_key, createfunc=compute_stats)
285 stats = cache_manager.get(_cache_key, createfunc=compute_stats)
282 return stats
286 return stats
283
287
284 @LoginRequired()
288 @LoginRequired()
285 @HasRepoPermissionAnyDecorator(
289 @HasRepoPermissionAnyDecorator(
286 'repository.read', 'repository.write', 'repository.admin')
290 'repository.read', 'repository.write', 'repository.admin')
287 @view_config(
291 @view_config(
288 route_name='repo_refs_data', request_method='GET',
292 route_name='repo_refs_data', request_method='GET',
289 renderer='json_ext')
293 renderer='json_ext')
290 def repo_refs_data(self):
294 def repo_refs_data(self):
291 _ = self.request.translate
295 _ = self.request.translate
292 self.load_default_context()
296 self.load_default_context()
293
297
294 repo = self.rhodecode_vcs_repo
298 repo = self.rhodecode_vcs_repo
295 refs_to_create = [
299 refs_to_create = [
296 (_("Branch"), repo.branches, 'branch'),
300 (_("Branch"), repo.branches, 'branch'),
297 (_("Tag"), repo.tags, 'tag'),
301 (_("Tag"), repo.tags, 'tag'),
298 (_("Bookmark"), repo.bookmarks, 'book'),
302 (_("Bookmark"), repo.bookmarks, 'book'),
299 ]
303 ]
300 res = self._create_reference_data(
304 res = self._create_reference_data(
301 repo, self.db_repo_name, refs_to_create)
305 repo, self.db_repo_name, refs_to_create)
302 data = {
306 data = {
303 'more': False,
307 'more': False,
304 'results': res
308 'results': res
305 }
309 }
306 return data
310 return data
307
311
308 @LoginRequired()
312 @LoginRequired()
309 @HasRepoPermissionAnyDecorator(
313 @HasRepoPermissionAnyDecorator(
310 'repository.read', 'repository.write', 'repository.admin')
314 'repository.read', 'repository.write', 'repository.admin')
311 @view_config(
315 @view_config(
312 route_name='repo_refs_changelog_data', request_method='GET',
316 route_name='repo_refs_changelog_data', request_method='GET',
313 renderer='json_ext')
317 renderer='json_ext')
314 def repo_refs_changelog_data(self):
318 def repo_refs_changelog_data(self):
315 _ = self.request.translate
319 _ = self.request.translate
316 self.load_default_context()
320 self.load_default_context()
317
321
318 repo = self.rhodecode_vcs_repo
322 repo = self.rhodecode_vcs_repo
319
323
320 refs_to_create = [
324 refs_to_create = [
321 (_("Branches"), repo.branches, 'branch'),
325 (_("Branches"), repo.branches, 'branch'),
322 (_("Closed branches"), repo.branches_closed, 'branch_closed'),
326 (_("Closed branches"), repo.branches_closed, 'branch_closed'),
323 # TODO: enable when vcs can handle bookmarks filters
327 # TODO: enable when vcs can handle bookmarks filters
324 # (_("Bookmarks"), repo.bookmarks, "book"),
328 # (_("Bookmarks"), repo.bookmarks, "book"),
325 ]
329 ]
326 res = self._create_reference_data(
330 res = self._create_reference_data(
327 repo, self.db_repo_name, refs_to_create)
331 repo, self.db_repo_name, refs_to_create)
328 data = {
332 data = {
329 'more': False,
333 'more': False,
330 'results': res
334 'results': res
331 }
335 }
332 return data
336 return data
333
337
334 def _create_reference_data(self, repo, full_repo_name, refs_to_create):
338 def _create_reference_data(self, repo, full_repo_name, refs_to_create):
335 format_ref_id = utils.get_format_ref_id(repo)
339 format_ref_id = utils.get_format_ref_id(repo)
336
340
337 result = []
341 result = []
338 for title, refs, ref_type in refs_to_create:
342 for title, refs, ref_type in refs_to_create:
339 if refs:
343 if refs:
340 result.append({
344 result.append({
341 'text': title,
345 'text': title,
342 'children': self._create_reference_items(
346 'children': self._create_reference_items(
343 repo, full_repo_name, refs, ref_type,
347 repo, full_repo_name, refs, ref_type,
344 format_ref_id),
348 format_ref_id),
345 })
349 })
346 return result
350 return result
347
351
348 def _create_reference_items(self, repo, full_repo_name, refs, ref_type,
352 def _create_reference_items(self, repo, full_repo_name, refs, ref_type,
349 format_ref_id):
353 format_ref_id):
350 result = []
354 result = []
351 is_svn = h.is_svn(repo)
355 is_svn = h.is_svn(repo)
352 for ref_name, raw_id in refs.iteritems():
356 for ref_name, raw_id in refs.iteritems():
353 files_url = self._create_files_url(
357 files_url = self._create_files_url(
354 repo, full_repo_name, ref_name, raw_id, is_svn)
358 repo, full_repo_name, ref_name, raw_id, is_svn)
355 result.append({
359 result.append({
356 'text': ref_name,
360 'text': ref_name,
357 'id': format_ref_id(ref_name, raw_id),
361 'id': format_ref_id(ref_name, raw_id),
358 'raw_id': raw_id,
362 'raw_id': raw_id,
359 'type': ref_type,
363 'type': ref_type,
360 'files_url': files_url,
364 'files_url': files_url,
361 })
365 })
362 return result
366 return result
363
367
364 def _create_files_url(self, repo, full_repo_name, ref_name, raw_id, is_svn):
368 def _create_files_url(self, repo, full_repo_name, ref_name, raw_id, is_svn):
365 use_commit_id = '/' in ref_name or is_svn
369 use_commit_id = '/' in ref_name or is_svn
366 return h.route_path(
370 return h.route_path(
367 'repo_files',
371 'repo_files',
368 repo_name=full_repo_name,
372 repo_name=full_repo_name,
369 f_path=ref_name if is_svn else '',
373 f_path=ref_name if is_svn else '',
370 commit_id=raw_id if use_commit_id else ref_name,
374 commit_id=raw_id if use_commit_id else ref_name,
371 _query=dict(at=ref_name))
375 _query=dict(at=ref_name))
@@ -1,542 +1,543 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2018 RhodeCode GmbH
3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
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/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 The base Controller API
22 The base Controller API
23 Provides the BaseController class for subclassing. And usage in different
23 Provides the BaseController class for subclassing. And usage in different
24 controllers
24 controllers
25 """
25 """
26
26
27 import logging
27 import logging
28 import socket
28 import socket
29
29
30 import markupsafe
30 import markupsafe
31 import ipaddress
31 import ipaddress
32
32
33 from paste.auth.basic import AuthBasicAuthenticator
33 from paste.auth.basic import AuthBasicAuthenticator
34 from paste.httpexceptions import HTTPUnauthorized, HTTPForbidden, get_exception
34 from paste.httpexceptions import HTTPUnauthorized, HTTPForbidden, get_exception
35 from paste.httpheaders import WWW_AUTHENTICATE, AUTHORIZATION
35 from paste.httpheaders import WWW_AUTHENTICATE, AUTHORIZATION
36
36
37 import rhodecode
37 import rhodecode
38 from rhodecode.authentication.base import VCS_TYPE
38 from rhodecode.authentication.base import VCS_TYPE
39 from rhodecode.lib import auth, utils2
39 from rhodecode.lib import auth, utils2
40 from rhodecode.lib import helpers as h
40 from rhodecode.lib import helpers as h
41 from rhodecode.lib.auth import AuthUser, CookieStoreWrapper
41 from rhodecode.lib.auth import AuthUser, CookieStoreWrapper
42 from rhodecode.lib.exceptions import UserCreationError
42 from rhodecode.lib.exceptions import UserCreationError
43 from rhodecode.lib.utils import (password_changed, get_enabled_hook_classes)
43 from rhodecode.lib.utils import (password_changed, get_enabled_hook_classes)
44 from rhodecode.lib.utils2 import (
44 from rhodecode.lib.utils2 import (
45 str2bool, safe_unicode, AttributeDict, safe_int, md5, aslist, safe_str)
45 str2bool, safe_unicode, AttributeDict, safe_int, md5, aslist, safe_str)
46 from rhodecode.model.db import Repository, User, ChangesetComment
46 from rhodecode.model.db import Repository, User, ChangesetComment
47 from rhodecode.model.notification import NotificationModel
47 from rhodecode.model.notification import NotificationModel
48 from rhodecode.model.settings import VcsSettingsModel, SettingsModel
48 from rhodecode.model.settings import VcsSettingsModel, SettingsModel
49
49
50 log = logging.getLogger(__name__)
50 log = logging.getLogger(__name__)
51
51
52
52
53 def _filter_proxy(ip):
53 def _filter_proxy(ip):
54 """
54 """
55 Passed in IP addresses in HEADERS can be in a special format of multiple
55 Passed in IP addresses in HEADERS can be in a special format of multiple
56 ips. Those comma separated IPs are passed from various proxies in the
56 ips. Those comma separated IPs are passed from various proxies in the
57 chain of request processing. The left-most being the original client.
57 chain of request processing. The left-most being the original client.
58 We only care about the first IP which came from the org. client.
58 We only care about the first IP which came from the org. client.
59
59
60 :param ip: ip string from headers
60 :param ip: ip string from headers
61 """
61 """
62 if ',' in ip:
62 if ',' in ip:
63 _ips = ip.split(',')
63 _ips = ip.split(',')
64 _first_ip = _ips[0].strip()
64 _first_ip = _ips[0].strip()
65 log.debug('Got multiple IPs %s, using %s', ','.join(_ips), _first_ip)
65 log.debug('Got multiple IPs %s, using %s', ','.join(_ips), _first_ip)
66 return _first_ip
66 return _first_ip
67 return ip
67 return ip
68
68
69
69
70 def _filter_port(ip):
70 def _filter_port(ip):
71 """
71 """
72 Removes a port from ip, there are 4 main cases to handle here.
72 Removes a port from ip, there are 4 main cases to handle here.
73 - ipv4 eg. 127.0.0.1
73 - ipv4 eg. 127.0.0.1
74 - ipv6 eg. ::1
74 - ipv6 eg. ::1
75 - ipv4+port eg. 127.0.0.1:8080
75 - ipv4+port eg. 127.0.0.1:8080
76 - ipv6+port eg. [::1]:8080
76 - ipv6+port eg. [::1]:8080
77
77
78 :param ip:
78 :param ip:
79 """
79 """
80 def is_ipv6(ip_addr):
80 def is_ipv6(ip_addr):
81 if hasattr(socket, 'inet_pton'):
81 if hasattr(socket, 'inet_pton'):
82 try:
82 try:
83 socket.inet_pton(socket.AF_INET6, ip_addr)
83 socket.inet_pton(socket.AF_INET6, ip_addr)
84 except socket.error:
84 except socket.error:
85 return False
85 return False
86 else:
86 else:
87 # fallback to ipaddress
87 # fallback to ipaddress
88 try:
88 try:
89 ipaddress.IPv6Address(safe_unicode(ip_addr))
89 ipaddress.IPv6Address(safe_unicode(ip_addr))
90 except Exception:
90 except Exception:
91 return False
91 return False
92 return True
92 return True
93
93
94 if ':' not in ip: # must be ipv4 pure ip
94 if ':' not in ip: # must be ipv4 pure ip
95 return ip
95 return ip
96
96
97 if '[' in ip and ']' in ip: # ipv6 with port
97 if '[' in ip and ']' in ip: # ipv6 with port
98 return ip.split(']')[0][1:].lower()
98 return ip.split(']')[0][1:].lower()
99
99
100 # must be ipv6 or ipv4 with port
100 # must be ipv6 or ipv4 with port
101 if is_ipv6(ip):
101 if is_ipv6(ip):
102 return ip
102 return ip
103 else:
103 else:
104 ip, _port = ip.split(':')[:2] # means ipv4+port
104 ip, _port = ip.split(':')[:2] # means ipv4+port
105 return ip
105 return ip
106
106
107
107
108 def get_ip_addr(environ):
108 def get_ip_addr(environ):
109 proxy_key = 'HTTP_X_REAL_IP'
109 proxy_key = 'HTTP_X_REAL_IP'
110 proxy_key2 = 'HTTP_X_FORWARDED_FOR'
110 proxy_key2 = 'HTTP_X_FORWARDED_FOR'
111 def_key = 'REMOTE_ADDR'
111 def_key = 'REMOTE_ADDR'
112 _filters = lambda x: _filter_port(_filter_proxy(x))
112 _filters = lambda x: _filter_port(_filter_proxy(x))
113
113
114 ip = environ.get(proxy_key)
114 ip = environ.get(proxy_key)
115 if ip:
115 if ip:
116 return _filters(ip)
116 return _filters(ip)
117
117
118 ip = environ.get(proxy_key2)
118 ip = environ.get(proxy_key2)
119 if ip:
119 if ip:
120 return _filters(ip)
120 return _filters(ip)
121
121
122 ip = environ.get(def_key, '0.0.0.0')
122 ip = environ.get(def_key, '0.0.0.0')
123 return _filters(ip)
123 return _filters(ip)
124
124
125
125
126 def get_server_ip_addr(environ, log_errors=True):
126 def get_server_ip_addr(environ, log_errors=True):
127 hostname = environ.get('SERVER_NAME')
127 hostname = environ.get('SERVER_NAME')
128 try:
128 try:
129 return socket.gethostbyname(hostname)
129 return socket.gethostbyname(hostname)
130 except Exception as e:
130 except Exception as e:
131 if log_errors:
131 if log_errors:
132 # in some cases this lookup is not possible, and we don't want to
132 # in some cases this lookup is not possible, and we don't want to
133 # make it an exception in logs
133 # make it an exception in logs
134 log.exception('Could not retrieve server ip address: %s', e)
134 log.exception('Could not retrieve server ip address: %s', e)
135 return hostname
135 return hostname
136
136
137
137
138 def get_server_port(environ):
138 def get_server_port(environ):
139 return environ.get('SERVER_PORT')
139 return environ.get('SERVER_PORT')
140
140
141
141
142 def get_access_path(environ):
142 def get_access_path(environ):
143 path = environ.get('PATH_INFO')
143 path = environ.get('PATH_INFO')
144 org_req = environ.get('pylons.original_request')
144 org_req = environ.get('pylons.original_request')
145 if org_req:
145 if org_req:
146 path = org_req.environ.get('PATH_INFO')
146 path = org_req.environ.get('PATH_INFO')
147 return path
147 return path
148
148
149
149
150 def get_user_agent(environ):
150 def get_user_agent(environ):
151 return environ.get('HTTP_USER_AGENT')
151 return environ.get('HTTP_USER_AGENT')
152
152
153
153
154 def vcs_operation_context(
154 def vcs_operation_context(
155 environ, repo_name, username, action, scm, check_locking=True,
155 environ, repo_name, username, action, scm, check_locking=True,
156 is_shadow_repo=False):
156 is_shadow_repo=False):
157 """
157 """
158 Generate the context for a vcs operation, e.g. push or pull.
158 Generate the context for a vcs operation, e.g. push or pull.
159
159
160 This context is passed over the layers so that hooks triggered by the
160 This context is passed over the layers so that hooks triggered by the
161 vcs operation know details like the user, the user's IP address etc.
161 vcs operation know details like the user, the user's IP address etc.
162
162
163 :param check_locking: Allows to switch of the computation of the locking
163 :param check_locking: Allows to switch of the computation of the locking
164 data. This serves mainly the need of the simplevcs middleware to be
164 data. This serves mainly the need of the simplevcs middleware to be
165 able to disable this for certain operations.
165 able to disable this for certain operations.
166
166
167 """
167 """
168 # Tri-state value: False: unlock, None: nothing, True: lock
168 # Tri-state value: False: unlock, None: nothing, True: lock
169 make_lock = None
169 make_lock = None
170 locked_by = [None, None, None]
170 locked_by = [None, None, None]
171 is_anonymous = username == User.DEFAULT_USER
171 is_anonymous = username == User.DEFAULT_USER
172 user = User.get_by_username(username)
172 user = User.get_by_username(username)
173 if not is_anonymous and check_locking:
173 if not is_anonymous and check_locking:
174 log.debug('Checking locking on repository "%s"', repo_name)
174 log.debug('Checking locking on repository "%s"', repo_name)
175 repo = Repository.get_by_repo_name(repo_name)
175 repo = Repository.get_by_repo_name(repo_name)
176 make_lock, __, locked_by = repo.get_locking_state(
176 make_lock, __, locked_by = repo.get_locking_state(
177 action, user.user_id)
177 action, user.user_id)
178 user_id = user.user_id
178 user_id = user.user_id
179 settings_model = VcsSettingsModel(repo=repo_name)
179 settings_model = VcsSettingsModel(repo=repo_name)
180 ui_settings = settings_model.get_ui_settings()
180 ui_settings = settings_model.get_ui_settings()
181
181
182 extras = {
182 extras = {
183 'ip': get_ip_addr(environ),
183 'ip': get_ip_addr(environ),
184 'username': username,
184 'username': username,
185 'user_id': user_id,
185 'user_id': user_id,
186 'action': action,
186 'action': action,
187 'repository': repo_name,
187 'repository': repo_name,
188 'scm': scm,
188 'scm': scm,
189 'config': rhodecode.CONFIG['__file__'],
189 'config': rhodecode.CONFIG['__file__'],
190 'make_lock': make_lock,
190 'make_lock': make_lock,
191 'locked_by': locked_by,
191 'locked_by': locked_by,
192 'server_url': utils2.get_server_url(environ),
192 'server_url': utils2.get_server_url(environ),
193 'user_agent': get_user_agent(environ),
193 'user_agent': get_user_agent(environ),
194 'hooks': get_enabled_hook_classes(ui_settings),
194 'hooks': get_enabled_hook_classes(ui_settings),
195 'is_shadow_repo': is_shadow_repo,
195 'is_shadow_repo': is_shadow_repo,
196 }
196 }
197 return extras
197 return extras
198
198
199
199
200 class BasicAuth(AuthBasicAuthenticator):
200 class BasicAuth(AuthBasicAuthenticator):
201
201
202 def __init__(self, realm, authfunc, registry, auth_http_code=None,
202 def __init__(self, realm, authfunc, registry, auth_http_code=None,
203 initial_call_detection=False, acl_repo_name=None):
203 initial_call_detection=False, acl_repo_name=None):
204 self.realm = realm
204 self.realm = realm
205 self.initial_call = initial_call_detection
205 self.initial_call = initial_call_detection
206 self.authfunc = authfunc
206 self.authfunc = authfunc
207 self.registry = registry
207 self.registry = registry
208 self.acl_repo_name = acl_repo_name
208 self.acl_repo_name = acl_repo_name
209 self._rc_auth_http_code = auth_http_code
209 self._rc_auth_http_code = auth_http_code
210
210
211 def _get_response_from_code(self, http_code):
211 def _get_response_from_code(self, http_code):
212 try:
212 try:
213 return get_exception(safe_int(http_code))
213 return get_exception(safe_int(http_code))
214 except Exception:
214 except Exception:
215 log.exception('Failed to fetch response for code %s' % http_code)
215 log.exception('Failed to fetch response for code %s' % http_code)
216 return HTTPForbidden
216 return HTTPForbidden
217
217
218 def get_rc_realm(self):
218 def get_rc_realm(self):
219 return safe_str(self.registry.rhodecode_settings.get('rhodecode_realm'))
219 return safe_str(self.registry.rhodecode_settings.get('rhodecode_realm'))
220
220
221 def build_authentication(self):
221 def build_authentication(self):
222 head = WWW_AUTHENTICATE.tuples('Basic realm="%s"' % self.realm)
222 head = WWW_AUTHENTICATE.tuples('Basic realm="%s"' % self.realm)
223 if self._rc_auth_http_code and not self.initial_call:
223 if self._rc_auth_http_code and not self.initial_call:
224 # return alternative HTTP code if alternative http return code
224 # return alternative HTTP code if alternative http return code
225 # is specified in RhodeCode config, but ONLY if it's not the
225 # is specified in RhodeCode config, but ONLY if it's not the
226 # FIRST call
226 # FIRST call
227 custom_response_klass = self._get_response_from_code(
227 custom_response_klass = self._get_response_from_code(
228 self._rc_auth_http_code)
228 self._rc_auth_http_code)
229 return custom_response_klass(headers=head)
229 return custom_response_klass(headers=head)
230 return HTTPUnauthorized(headers=head)
230 return HTTPUnauthorized(headers=head)
231
231
232 def authenticate(self, environ):
232 def authenticate(self, environ):
233 authorization = AUTHORIZATION(environ)
233 authorization = AUTHORIZATION(environ)
234 if not authorization:
234 if not authorization:
235 return self.build_authentication()
235 return self.build_authentication()
236 (authmeth, auth) = authorization.split(' ', 1)
236 (authmeth, auth) = authorization.split(' ', 1)
237 if 'basic' != authmeth.lower():
237 if 'basic' != authmeth.lower():
238 return self.build_authentication()
238 return self.build_authentication()
239 auth = auth.strip().decode('base64')
239 auth = auth.strip().decode('base64')
240 _parts = auth.split(':', 1)
240 _parts = auth.split(':', 1)
241 if len(_parts) == 2:
241 if len(_parts) == 2:
242 username, password = _parts
242 username, password = _parts
243 auth_data = self.authfunc(
243 auth_data = self.authfunc(
244 username, password, environ, VCS_TYPE,
244 username, password, environ, VCS_TYPE,
245 registry=self.registry, acl_repo_name=self.acl_repo_name)
245 registry=self.registry, acl_repo_name=self.acl_repo_name)
246 if auth_data:
246 if auth_data:
247 return {'username': username, 'auth_data': auth_data}
247 return {'username': username, 'auth_data': auth_data}
248 if username and password:
248 if username and password:
249 # we mark that we actually executed authentication once, at
249 # we mark that we actually executed authentication once, at
250 # that point we can use the alternative auth code
250 # that point we can use the alternative auth code
251 self.initial_call = False
251 self.initial_call = False
252
252
253 return self.build_authentication()
253 return self.build_authentication()
254
254
255 __call__ = authenticate
255 __call__ = authenticate
256
256
257
257
258 def calculate_version_hash(config):
258 def calculate_version_hash(config):
259 return md5(
259 return md5(
260 config.get('beaker.session.secret', '') +
260 config.get('beaker.session.secret', '') +
261 rhodecode.__version__)[:8]
261 rhodecode.__version__)[:8]
262
262
263
263
264 def get_current_lang(request):
264 def get_current_lang(request):
265 # NOTE(marcink): remove after pyramid move
265 # NOTE(marcink): remove after pyramid move
266 try:
266 try:
267 return translation.get_lang()[0]
267 return translation.get_lang()[0]
268 except:
268 except:
269 pass
269 pass
270
270
271 return getattr(request, '_LOCALE_', request.locale_name)
271 return getattr(request, '_LOCALE_', request.locale_name)
272
272
273
273
274 def attach_context_attributes(context, request, user_id):
274 def attach_context_attributes(context, request, user_id):
275 """
275 """
276 Attach variables into template context called `c`.
276 Attach variables into template context called `c`.
277 """
277 """
278 config = request.registry.settings
278 config = request.registry.settings
279
279
280
280
281 rc_config = SettingsModel().get_all_settings(cache=True)
281 rc_config = SettingsModel().get_all_settings(cache=True)
282
282
283 context.rhodecode_version = rhodecode.__version__
283 context.rhodecode_version = rhodecode.__version__
284 context.rhodecode_edition = config.get('rhodecode.edition')
284 context.rhodecode_edition = config.get('rhodecode.edition')
285 # unique secret + version does not leak the version but keep consistency
285 # unique secret + version does not leak the version but keep consistency
286 context.rhodecode_version_hash = calculate_version_hash(config)
286 context.rhodecode_version_hash = calculate_version_hash(config)
287
287
288 # Default language set for the incoming request
288 # Default language set for the incoming request
289 context.language = get_current_lang(request)
289 context.language = get_current_lang(request)
290
290
291 # Visual options
291 # Visual options
292 context.visual = AttributeDict({})
292 context.visual = AttributeDict({})
293
293
294 # DB stored Visual Items
294 # DB stored Visual Items
295 context.visual.show_public_icon = str2bool(
295 context.visual.show_public_icon = str2bool(
296 rc_config.get('rhodecode_show_public_icon'))
296 rc_config.get('rhodecode_show_public_icon'))
297 context.visual.show_private_icon = str2bool(
297 context.visual.show_private_icon = str2bool(
298 rc_config.get('rhodecode_show_private_icon'))
298 rc_config.get('rhodecode_show_private_icon'))
299 context.visual.stylify_metatags = str2bool(
299 context.visual.stylify_metatags = str2bool(
300 rc_config.get('rhodecode_stylify_metatags'))
300 rc_config.get('rhodecode_stylify_metatags'))
301 context.visual.dashboard_items = safe_int(
301 context.visual.dashboard_items = safe_int(
302 rc_config.get('rhodecode_dashboard_items', 100))
302 rc_config.get('rhodecode_dashboard_items', 100))
303 context.visual.admin_grid_items = safe_int(
303 context.visual.admin_grid_items = safe_int(
304 rc_config.get('rhodecode_admin_grid_items', 100))
304 rc_config.get('rhodecode_admin_grid_items', 100))
305 context.visual.repository_fields = str2bool(
305 context.visual.repository_fields = str2bool(
306 rc_config.get('rhodecode_repository_fields'))
306 rc_config.get('rhodecode_repository_fields'))
307 context.visual.show_version = str2bool(
307 context.visual.show_version = str2bool(
308 rc_config.get('rhodecode_show_version'))
308 rc_config.get('rhodecode_show_version'))
309 context.visual.use_gravatar = str2bool(
309 context.visual.use_gravatar = str2bool(
310 rc_config.get('rhodecode_use_gravatar'))
310 rc_config.get('rhodecode_use_gravatar'))
311 context.visual.gravatar_url = rc_config.get('rhodecode_gravatar_url')
311 context.visual.gravatar_url = rc_config.get('rhodecode_gravatar_url')
312 context.visual.default_renderer = rc_config.get(
312 context.visual.default_renderer = rc_config.get(
313 'rhodecode_markup_renderer', 'rst')
313 'rhodecode_markup_renderer', 'rst')
314 context.visual.comment_types = ChangesetComment.COMMENT_TYPES
314 context.visual.comment_types = ChangesetComment.COMMENT_TYPES
315 context.visual.rhodecode_support_url = \
315 context.visual.rhodecode_support_url = \
316 rc_config.get('rhodecode_support_url') or h.route_url('rhodecode_support')
316 rc_config.get('rhodecode_support_url') or h.route_url('rhodecode_support')
317
317
318 context.visual.affected_files_cut_off = 60
318 context.visual.affected_files_cut_off = 60
319
319
320 context.pre_code = rc_config.get('rhodecode_pre_code')
320 context.pre_code = rc_config.get('rhodecode_pre_code')
321 context.post_code = rc_config.get('rhodecode_post_code')
321 context.post_code = rc_config.get('rhodecode_post_code')
322 context.rhodecode_name = rc_config.get('rhodecode_title')
322 context.rhodecode_name = rc_config.get('rhodecode_title')
323 context.default_encodings = aslist(config.get('default_encoding'), sep=',')
323 context.default_encodings = aslist(config.get('default_encoding'), sep=',')
324 # if we have specified default_encoding in the request, it has more
324 # if we have specified default_encoding in the request, it has more
325 # priority
325 # priority
326 if request.GET.get('default_encoding'):
326 if request.GET.get('default_encoding'):
327 context.default_encodings.insert(0, request.GET.get('default_encoding'))
327 context.default_encodings.insert(0, request.GET.get('default_encoding'))
328 context.clone_uri_tmpl = rc_config.get('rhodecode_clone_uri_tmpl')
328 context.clone_uri_tmpl = rc_config.get('rhodecode_clone_uri_tmpl')
329 context.clone_uri_ssh_tmpl = rc_config.get('rhodecode_clone_uri_ssh_tmpl')
329
330
330 # INI stored
331 # INI stored
331 context.labs_active = str2bool(
332 context.labs_active = str2bool(
332 config.get('labs_settings_active', 'false'))
333 config.get('labs_settings_active', 'false'))
333 context.visual.allow_repo_location_change = str2bool(
334 context.visual.allow_repo_location_change = str2bool(
334 config.get('allow_repo_location_change', True))
335 config.get('allow_repo_location_change', True))
335 context.visual.allow_custom_hooks_settings = str2bool(
336 context.visual.allow_custom_hooks_settings = str2bool(
336 config.get('allow_custom_hooks_settings', True))
337 config.get('allow_custom_hooks_settings', True))
337 context.debug_style = str2bool(config.get('debug_style', False))
338 context.debug_style = str2bool(config.get('debug_style', False))
338
339
339 context.rhodecode_instanceid = config.get('instance_id')
340 context.rhodecode_instanceid = config.get('instance_id')
340
341
341 context.visual.cut_off_limit_diff = safe_int(
342 context.visual.cut_off_limit_diff = safe_int(
342 config.get('cut_off_limit_diff'))
343 config.get('cut_off_limit_diff'))
343 context.visual.cut_off_limit_file = safe_int(
344 context.visual.cut_off_limit_file = safe_int(
344 config.get('cut_off_limit_file'))
345 config.get('cut_off_limit_file'))
345
346
346 # AppEnlight
347 # AppEnlight
347 context.appenlight_enabled = str2bool(config.get('appenlight', 'false'))
348 context.appenlight_enabled = str2bool(config.get('appenlight', 'false'))
348 context.appenlight_api_public_key = config.get(
349 context.appenlight_api_public_key = config.get(
349 'appenlight.api_public_key', '')
350 'appenlight.api_public_key', '')
350 context.appenlight_server_url = config.get('appenlight.server_url', '')
351 context.appenlight_server_url = config.get('appenlight.server_url', '')
351
352
352 # JS template context
353 # JS template context
353 context.template_context = {
354 context.template_context = {
354 'repo_name': None,
355 'repo_name': None,
355 'repo_type': None,
356 'repo_type': None,
356 'repo_landing_commit': None,
357 'repo_landing_commit': None,
357 'rhodecode_user': {
358 'rhodecode_user': {
358 'username': None,
359 'username': None,
359 'email': None,
360 'email': None,
360 'notification_status': False
361 'notification_status': False
361 },
362 },
362 'visual': {
363 'visual': {
363 'default_renderer': None
364 'default_renderer': None
364 },
365 },
365 'commit_data': {
366 'commit_data': {
366 'commit_id': None
367 'commit_id': None
367 },
368 },
368 'pull_request_data': {'pull_request_id': None},
369 'pull_request_data': {'pull_request_id': None},
369 'timeago': {
370 'timeago': {
370 'refresh_time': 120 * 1000,
371 'refresh_time': 120 * 1000,
371 'cutoff_limit': 1000 * 60 * 60 * 24 * 7
372 'cutoff_limit': 1000 * 60 * 60 * 24 * 7
372 },
373 },
373 'pyramid_dispatch': {
374 'pyramid_dispatch': {
374
375
375 },
376 },
376 'extra': {'plugins': {}}
377 'extra': {'plugins': {}}
377 }
378 }
378 # END CONFIG VARS
379 # END CONFIG VARS
379
380
380 diffmode = 'sideside'
381 diffmode = 'sideside'
381 if request.GET.get('diffmode'):
382 if request.GET.get('diffmode'):
382 if request.GET['diffmode'] == 'unified':
383 if request.GET['diffmode'] == 'unified':
383 diffmode = 'unified'
384 diffmode = 'unified'
384 elif request.session.get('diffmode'):
385 elif request.session.get('diffmode'):
385 diffmode = request.session['diffmode']
386 diffmode = request.session['diffmode']
386
387
387 context.diffmode = diffmode
388 context.diffmode = diffmode
388
389
389 if request.session.get('diffmode') != diffmode:
390 if request.session.get('diffmode') != diffmode:
390 request.session['diffmode'] = diffmode
391 request.session['diffmode'] = diffmode
391
392
392 context.csrf_token = auth.get_csrf_token(session=request.session)
393 context.csrf_token = auth.get_csrf_token(session=request.session)
393 context.backends = rhodecode.BACKENDS.keys()
394 context.backends = rhodecode.BACKENDS.keys()
394 context.backends.sort()
395 context.backends.sort()
395 context.unread_notifications = NotificationModel().get_unread_cnt_for_user(user_id)
396 context.unread_notifications = NotificationModel().get_unread_cnt_for_user(user_id)
396
397
397 # web case
398 # web case
398 if hasattr(request, 'user'):
399 if hasattr(request, 'user'):
399 context.auth_user = request.user
400 context.auth_user = request.user
400 context.rhodecode_user = request.user
401 context.rhodecode_user = request.user
401
402
402 # api case
403 # api case
403 if hasattr(request, 'rpc_user'):
404 if hasattr(request, 'rpc_user'):
404 context.auth_user = request.rpc_user
405 context.auth_user = request.rpc_user
405 context.rhodecode_user = request.rpc_user
406 context.rhodecode_user = request.rpc_user
406
407
407 # attach the whole call context to the request
408 # attach the whole call context to the request
408 request.call_context = context
409 request.call_context = context
409
410
410
411
411 def get_auth_user(request):
412 def get_auth_user(request):
412 environ = request.environ
413 environ = request.environ
413 session = request.session
414 session = request.session
414
415
415 ip_addr = get_ip_addr(environ)
416 ip_addr = get_ip_addr(environ)
416 # make sure that we update permissions each time we call controller
417 # make sure that we update permissions each time we call controller
417 _auth_token = (request.GET.get('auth_token', '') or
418 _auth_token = (request.GET.get('auth_token', '') or
418 request.GET.get('api_key', ''))
419 request.GET.get('api_key', ''))
419
420
420 if _auth_token:
421 if _auth_token:
421 # when using API_KEY we assume user exists, and
422 # when using API_KEY we assume user exists, and
422 # doesn't need auth based on cookies.
423 # doesn't need auth based on cookies.
423 auth_user = AuthUser(api_key=_auth_token, ip_addr=ip_addr)
424 auth_user = AuthUser(api_key=_auth_token, ip_addr=ip_addr)
424 authenticated = False
425 authenticated = False
425 else:
426 else:
426 cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
427 cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
427 try:
428 try:
428 auth_user = AuthUser(user_id=cookie_store.get('user_id', None),
429 auth_user = AuthUser(user_id=cookie_store.get('user_id', None),
429 ip_addr=ip_addr)
430 ip_addr=ip_addr)
430 except UserCreationError as e:
431 except UserCreationError as e:
431 h.flash(e, 'error')
432 h.flash(e, 'error')
432 # container auth or other auth functions that create users
433 # container auth or other auth functions that create users
433 # on the fly can throw this exception signaling that there's
434 # on the fly can throw this exception signaling that there's
434 # issue with user creation, explanation should be provided
435 # issue with user creation, explanation should be provided
435 # in Exception itself. We then create a simple blank
436 # in Exception itself. We then create a simple blank
436 # AuthUser
437 # AuthUser
437 auth_user = AuthUser(ip_addr=ip_addr)
438 auth_user = AuthUser(ip_addr=ip_addr)
438
439
439 # in case someone changes a password for user it triggers session
440 # in case someone changes a password for user it triggers session
440 # flush and forces a re-login
441 # flush and forces a re-login
441 if password_changed(auth_user, session):
442 if password_changed(auth_user, session):
442 session.invalidate()
443 session.invalidate()
443 cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
444 cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
444 auth_user = AuthUser(ip_addr=ip_addr)
445 auth_user = AuthUser(ip_addr=ip_addr)
445
446
446 authenticated = cookie_store.get('is_authenticated')
447 authenticated = cookie_store.get('is_authenticated')
447
448
448 if not auth_user.is_authenticated and auth_user.is_user_object:
449 if not auth_user.is_authenticated and auth_user.is_user_object:
449 # user is not authenticated and not empty
450 # user is not authenticated and not empty
450 auth_user.set_authenticated(authenticated)
451 auth_user.set_authenticated(authenticated)
451
452
452 return auth_user
453 return auth_user
453
454
454
455
455 def h_filter(s):
456 def h_filter(s):
456 """
457 """
457 Custom filter for Mako templates. Mako by standard uses `markupsafe.escape`
458 Custom filter for Mako templates. Mako by standard uses `markupsafe.escape`
458 we wrap this with additional functionality that converts None to empty
459 we wrap this with additional functionality that converts None to empty
459 strings
460 strings
460 """
461 """
461 if s is None:
462 if s is None:
462 return markupsafe.Markup()
463 return markupsafe.Markup()
463 return markupsafe.escape(s)
464 return markupsafe.escape(s)
464
465
465
466
466 def add_events_routes(config):
467 def add_events_routes(config):
467 """
468 """
468 Adds routing that can be used in events. Because some events are triggered
469 Adds routing that can be used in events. Because some events are triggered
469 outside of pyramid context, we need to bootstrap request with some
470 outside of pyramid context, we need to bootstrap request with some
470 routing registered
471 routing registered
471 """
472 """
472
473
473 from rhodecode.apps._base import ADMIN_PREFIX
474 from rhodecode.apps._base import ADMIN_PREFIX
474
475
475 config.add_route(name='home', pattern='/')
476 config.add_route(name='home', pattern='/')
476
477
477 config.add_route(name='login', pattern=ADMIN_PREFIX + '/login')
478 config.add_route(name='login', pattern=ADMIN_PREFIX + '/login')
478 config.add_route(name='logout', pattern=ADMIN_PREFIX + '/logout')
479 config.add_route(name='logout', pattern=ADMIN_PREFIX + '/logout')
479 config.add_route(name='repo_summary', pattern='/{repo_name}')
480 config.add_route(name='repo_summary', pattern='/{repo_name}')
480 config.add_route(name='repo_summary_explicit', pattern='/{repo_name}/summary')
481 config.add_route(name='repo_summary_explicit', pattern='/{repo_name}/summary')
481 config.add_route(name='repo_group_home', pattern='/{repo_group_name}')
482 config.add_route(name='repo_group_home', pattern='/{repo_group_name}')
482
483
483 config.add_route(name='pullrequest_show',
484 config.add_route(name='pullrequest_show',
484 pattern='/{repo_name}/pull-request/{pull_request_id}')
485 pattern='/{repo_name}/pull-request/{pull_request_id}')
485 config.add_route(name='pull_requests_global',
486 config.add_route(name='pull_requests_global',
486 pattern='/pull-request/{pull_request_id}')
487 pattern='/pull-request/{pull_request_id}')
487 config.add_route(name='repo_commit',
488 config.add_route(name='repo_commit',
488 pattern='/{repo_name}/changeset/{commit_id}')
489 pattern='/{repo_name}/changeset/{commit_id}')
489
490
490 config.add_route(name='repo_files',
491 config.add_route(name='repo_files',
491 pattern='/{repo_name}/files/{commit_id}/{f_path}')
492 pattern='/{repo_name}/files/{commit_id}/{f_path}')
492
493
493
494
494 def bootstrap_config(request):
495 def bootstrap_config(request):
495 import pyramid.testing
496 import pyramid.testing
496 registry = pyramid.testing.Registry('RcTestRegistry')
497 registry = pyramid.testing.Registry('RcTestRegistry')
497
498
498 config = pyramid.testing.setUp(registry=registry, request=request)
499 config = pyramid.testing.setUp(registry=registry, request=request)
499
500
500 # allow pyramid lookup in testing
501 # allow pyramid lookup in testing
501 config.include('pyramid_mako')
502 config.include('pyramid_mako')
502 config.include('pyramid_beaker')
503 config.include('pyramid_beaker')
503 config.include('rhodecode.lib.caches')
504 config.include('rhodecode.lib.caches')
504
505
505 add_events_routes(config)
506 add_events_routes(config)
506
507
507 return config
508 return config
508
509
509
510
510 def bootstrap_request(**kwargs):
511 def bootstrap_request(**kwargs):
511 import pyramid.testing
512 import pyramid.testing
512
513
513 class TestRequest(pyramid.testing.DummyRequest):
514 class TestRequest(pyramid.testing.DummyRequest):
514 application_url = kwargs.pop('application_url', 'http://example.com')
515 application_url = kwargs.pop('application_url', 'http://example.com')
515 host = kwargs.pop('host', 'example.com:80')
516 host = kwargs.pop('host', 'example.com:80')
516 domain = kwargs.pop('domain', 'example.com')
517 domain = kwargs.pop('domain', 'example.com')
517
518
518 def translate(self, msg):
519 def translate(self, msg):
519 return msg
520 return msg
520
521
521 def plularize(self, singular, plural, n):
522 def plularize(self, singular, plural, n):
522 return singular
523 return singular
523
524
524 def get_partial_renderer(self, tmpl_name):
525 def get_partial_renderer(self, tmpl_name):
525
526
526 from rhodecode.lib.partial_renderer import get_partial_renderer
527 from rhodecode.lib.partial_renderer import get_partial_renderer
527 return get_partial_renderer(request=self, tmpl_name=tmpl_name)
528 return get_partial_renderer(request=self, tmpl_name=tmpl_name)
528
529
529 _call_context = {}
530 _call_context = {}
530 @property
531 @property
531 def call_context(self):
532 def call_context(self):
532 return self._call_context
533 return self._call_context
533
534
534 class TestDummySession(pyramid.testing.DummySession):
535 class TestDummySession(pyramid.testing.DummySession):
535 def save(*arg, **kw):
536 def save(*arg, **kw):
536 pass
537 pass
537
538
538 request = TestRequest(**kwargs)
539 request = TestRequest(**kwargs)
539 request.session = TestDummySession()
540 request.session = TestDummySession()
540
541
541 return request
542 return request
542
543
@@ -1,980 +1,984 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2011-2018 RhodeCode GmbH
3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
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/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21
21
22 """
22 """
23 Some simple helper functions
23 Some simple helper functions
24 """
24 """
25
25
26 import collections
26 import collections
27 import datetime
27 import datetime
28 import dateutil.relativedelta
28 import dateutil.relativedelta
29 import hashlib
29 import hashlib
30 import logging
30 import logging
31 import re
31 import re
32 import sys
32 import sys
33 import time
33 import time
34 import urllib
34 import urllib
35 import urlobject
35 import urlobject
36 import uuid
36 import uuid
37 import getpass
37
38
38 import pygments.lexers
39 import pygments.lexers
39 import sqlalchemy
40 import sqlalchemy
40 import sqlalchemy.engine.url
41 import sqlalchemy.engine.url
41 import sqlalchemy.exc
42 import sqlalchemy.exc
42 import sqlalchemy.sql
43 import sqlalchemy.sql
43 import webob
44 import webob
44 import pyramid.threadlocal
45 import pyramid.threadlocal
45
46
46 import rhodecode
47 import rhodecode
47 from rhodecode.translation import _, _pluralize
48 from rhodecode.translation import _, _pluralize
48
49
49
50
50 def md5(s):
51 def md5(s):
51 return hashlib.md5(s).hexdigest()
52 return hashlib.md5(s).hexdigest()
52
53
53
54
54 def md5_safe(s):
55 def md5_safe(s):
55 return md5(safe_str(s))
56 return md5(safe_str(s))
56
57
57
58
58 def __get_lem(extra_mapping=None):
59 def __get_lem(extra_mapping=None):
59 """
60 """
60 Get language extension map based on what's inside pygments lexers
61 Get language extension map based on what's inside pygments lexers
61 """
62 """
62 d = collections.defaultdict(lambda: [])
63 d = collections.defaultdict(lambda: [])
63
64
64 def __clean(s):
65 def __clean(s):
65 s = s.lstrip('*')
66 s = s.lstrip('*')
66 s = s.lstrip('.')
67 s = s.lstrip('.')
67
68
68 if s.find('[') != -1:
69 if s.find('[') != -1:
69 exts = []
70 exts = []
70 start, stop = s.find('['), s.find(']')
71 start, stop = s.find('['), s.find(']')
71
72
72 for suffix in s[start + 1:stop]:
73 for suffix in s[start + 1:stop]:
73 exts.append(s[:s.find('[')] + suffix)
74 exts.append(s[:s.find('[')] + suffix)
74 return [e.lower() for e in exts]
75 return [e.lower() for e in exts]
75 else:
76 else:
76 return [s.lower()]
77 return [s.lower()]
77
78
78 for lx, t in sorted(pygments.lexers.LEXERS.items()):
79 for lx, t in sorted(pygments.lexers.LEXERS.items()):
79 m = map(__clean, t[-2])
80 m = map(__clean, t[-2])
80 if m:
81 if m:
81 m = reduce(lambda x, y: x + y, m)
82 m = reduce(lambda x, y: x + y, m)
82 for ext in m:
83 for ext in m:
83 desc = lx.replace('Lexer', '')
84 desc = lx.replace('Lexer', '')
84 d[ext].append(desc)
85 d[ext].append(desc)
85
86
86 data = dict(d)
87 data = dict(d)
87
88
88 extra_mapping = extra_mapping or {}
89 extra_mapping = extra_mapping or {}
89 if extra_mapping:
90 if extra_mapping:
90 for k, v in extra_mapping.items():
91 for k, v in extra_mapping.items():
91 if k not in data:
92 if k not in data:
92 # register new mapping2lexer
93 # register new mapping2lexer
93 data[k] = [v]
94 data[k] = [v]
94
95
95 return data
96 return data
96
97
97
98
98 def str2bool(_str):
99 def str2bool(_str):
99 """
100 """
100 returns True/False value from given string, it tries to translate the
101 returns True/False value from given string, it tries to translate the
101 string into boolean
102 string into boolean
102
103
103 :param _str: string value to translate into boolean
104 :param _str: string value to translate into boolean
104 :rtype: boolean
105 :rtype: boolean
105 :returns: boolean from given string
106 :returns: boolean from given string
106 """
107 """
107 if _str is None:
108 if _str is None:
108 return False
109 return False
109 if _str in (True, False):
110 if _str in (True, False):
110 return _str
111 return _str
111 _str = str(_str).strip().lower()
112 _str = str(_str).strip().lower()
112 return _str in ('t', 'true', 'y', 'yes', 'on', '1')
113 return _str in ('t', 'true', 'y', 'yes', 'on', '1')
113
114
114
115
115 def aslist(obj, sep=None, strip=True):
116 def aslist(obj, sep=None, strip=True):
116 """
117 """
117 Returns given string separated by sep as list
118 Returns given string separated by sep as list
118
119
119 :param obj:
120 :param obj:
120 :param sep:
121 :param sep:
121 :param strip:
122 :param strip:
122 """
123 """
123 if isinstance(obj, (basestring,)):
124 if isinstance(obj, (basestring,)):
124 lst = obj.split(sep)
125 lst = obj.split(sep)
125 if strip:
126 if strip:
126 lst = [v.strip() for v in lst]
127 lst = [v.strip() for v in lst]
127 return lst
128 return lst
128 elif isinstance(obj, (list, tuple)):
129 elif isinstance(obj, (list, tuple)):
129 return obj
130 return obj
130 elif obj is None:
131 elif obj is None:
131 return []
132 return []
132 else:
133 else:
133 return [obj]
134 return [obj]
134
135
135
136
136 def convert_line_endings(line, mode):
137 def convert_line_endings(line, mode):
137 """
138 """
138 Converts a given line "line end" accordingly to given mode
139 Converts a given line "line end" accordingly to given mode
139
140
140 Available modes are::
141 Available modes are::
141 0 - Unix
142 0 - Unix
142 1 - Mac
143 1 - Mac
143 2 - DOS
144 2 - DOS
144
145
145 :param line: given line to convert
146 :param line: given line to convert
146 :param mode: mode to convert to
147 :param mode: mode to convert to
147 :rtype: str
148 :rtype: str
148 :return: converted line according to mode
149 :return: converted line according to mode
149 """
150 """
150 if mode == 0:
151 if mode == 0:
151 line = line.replace('\r\n', '\n')
152 line = line.replace('\r\n', '\n')
152 line = line.replace('\r', '\n')
153 line = line.replace('\r', '\n')
153 elif mode == 1:
154 elif mode == 1:
154 line = line.replace('\r\n', '\r')
155 line = line.replace('\r\n', '\r')
155 line = line.replace('\n', '\r')
156 line = line.replace('\n', '\r')
156 elif mode == 2:
157 elif mode == 2:
157 line = re.sub('\r(?!\n)|(?<!\r)\n', '\r\n', line)
158 line = re.sub('\r(?!\n)|(?<!\r)\n', '\r\n', line)
158 return line
159 return line
159
160
160
161
161 def detect_mode(line, default):
162 def detect_mode(line, default):
162 """
163 """
163 Detects line break for given line, if line break couldn't be found
164 Detects line break for given line, if line break couldn't be found
164 given default value is returned
165 given default value is returned
165
166
166 :param line: str line
167 :param line: str line
167 :param default: default
168 :param default: default
168 :rtype: int
169 :rtype: int
169 :return: value of line end on of 0 - Unix, 1 - Mac, 2 - DOS
170 :return: value of line end on of 0 - Unix, 1 - Mac, 2 - DOS
170 """
171 """
171 if line.endswith('\r\n'):
172 if line.endswith('\r\n'):
172 return 2
173 return 2
173 elif line.endswith('\n'):
174 elif line.endswith('\n'):
174 return 0
175 return 0
175 elif line.endswith('\r'):
176 elif line.endswith('\r'):
176 return 1
177 return 1
177 else:
178 else:
178 return default
179 return default
179
180
180
181
181 def safe_int(val, default=None):
182 def safe_int(val, default=None):
182 """
183 """
183 Returns int() of val if val is not convertable to int use default
184 Returns int() of val if val is not convertable to int use default
184 instead
185 instead
185
186
186 :param val:
187 :param val:
187 :param default:
188 :param default:
188 """
189 """
189
190
190 try:
191 try:
191 val = int(val)
192 val = int(val)
192 except (ValueError, TypeError):
193 except (ValueError, TypeError):
193 val = default
194 val = default
194
195
195 return val
196 return val
196
197
197
198
198 def safe_unicode(str_, from_encoding=None):
199 def safe_unicode(str_, from_encoding=None):
199 """
200 """
200 safe unicode function. Does few trick to turn str_ into unicode
201 safe unicode function. Does few trick to turn str_ into unicode
201
202
202 In case of UnicodeDecode error, we try to return it with encoding detected
203 In case of UnicodeDecode error, we try to return it with encoding detected
203 by chardet library if it fails fallback to unicode with errors replaced
204 by chardet library if it fails fallback to unicode with errors replaced
204
205
205 :param str_: string to decode
206 :param str_: string to decode
206 :rtype: unicode
207 :rtype: unicode
207 :returns: unicode object
208 :returns: unicode object
208 """
209 """
209 if isinstance(str_, unicode):
210 if isinstance(str_, unicode):
210 return str_
211 return str_
211
212
212 if not from_encoding:
213 if not from_encoding:
213 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
214 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
214 'utf8'), sep=',')
215 'utf8'), sep=',')
215 from_encoding = DEFAULT_ENCODINGS
216 from_encoding = DEFAULT_ENCODINGS
216
217
217 if not isinstance(from_encoding, (list, tuple)):
218 if not isinstance(from_encoding, (list, tuple)):
218 from_encoding = [from_encoding]
219 from_encoding = [from_encoding]
219
220
220 try:
221 try:
221 return unicode(str_)
222 return unicode(str_)
222 except UnicodeDecodeError:
223 except UnicodeDecodeError:
223 pass
224 pass
224
225
225 for enc in from_encoding:
226 for enc in from_encoding:
226 try:
227 try:
227 return unicode(str_, enc)
228 return unicode(str_, enc)
228 except UnicodeDecodeError:
229 except UnicodeDecodeError:
229 pass
230 pass
230
231
231 try:
232 try:
232 import chardet
233 import chardet
233 encoding = chardet.detect(str_)['encoding']
234 encoding = chardet.detect(str_)['encoding']
234 if encoding is None:
235 if encoding is None:
235 raise Exception()
236 raise Exception()
236 return str_.decode(encoding)
237 return str_.decode(encoding)
237 except (ImportError, UnicodeDecodeError, Exception):
238 except (ImportError, UnicodeDecodeError, Exception):
238 return unicode(str_, from_encoding[0], 'replace')
239 return unicode(str_, from_encoding[0], 'replace')
239
240
240
241
241 def safe_str(unicode_, to_encoding=None):
242 def safe_str(unicode_, to_encoding=None):
242 """
243 """
243 safe str function. Does few trick to turn unicode_ into string
244 safe str function. Does few trick to turn unicode_ into string
244
245
245 In case of UnicodeEncodeError, we try to return it with encoding detected
246 In case of UnicodeEncodeError, we try to return it with encoding detected
246 by chardet library if it fails fallback to string with errors replaced
247 by chardet library if it fails fallback to string with errors replaced
247
248
248 :param unicode_: unicode to encode
249 :param unicode_: unicode to encode
249 :rtype: str
250 :rtype: str
250 :returns: str object
251 :returns: str object
251 """
252 """
252
253
253 # if it's not basestr cast to str
254 # if it's not basestr cast to str
254 if not isinstance(unicode_, basestring):
255 if not isinstance(unicode_, basestring):
255 return str(unicode_)
256 return str(unicode_)
256
257
257 if isinstance(unicode_, str):
258 if isinstance(unicode_, str):
258 return unicode_
259 return unicode_
259
260
260 if not to_encoding:
261 if not to_encoding:
261 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
262 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
262 'utf8'), sep=',')
263 'utf8'), sep=',')
263 to_encoding = DEFAULT_ENCODINGS
264 to_encoding = DEFAULT_ENCODINGS
264
265
265 if not isinstance(to_encoding, (list, tuple)):
266 if not isinstance(to_encoding, (list, tuple)):
266 to_encoding = [to_encoding]
267 to_encoding = [to_encoding]
267
268
268 for enc in to_encoding:
269 for enc in to_encoding:
269 try:
270 try:
270 return unicode_.encode(enc)
271 return unicode_.encode(enc)
271 except UnicodeEncodeError:
272 except UnicodeEncodeError:
272 pass
273 pass
273
274
274 try:
275 try:
275 import chardet
276 import chardet
276 encoding = chardet.detect(unicode_)['encoding']
277 encoding = chardet.detect(unicode_)['encoding']
277 if encoding is None:
278 if encoding is None:
278 raise UnicodeEncodeError()
279 raise UnicodeEncodeError()
279
280
280 return unicode_.encode(encoding)
281 return unicode_.encode(encoding)
281 except (ImportError, UnicodeEncodeError):
282 except (ImportError, UnicodeEncodeError):
282 return unicode_.encode(to_encoding[0], 'replace')
283 return unicode_.encode(to_encoding[0], 'replace')
283
284
284
285
285 def remove_suffix(s, suffix):
286 def remove_suffix(s, suffix):
286 if s.endswith(suffix):
287 if s.endswith(suffix):
287 s = s[:-1 * len(suffix)]
288 s = s[:-1 * len(suffix)]
288 return s
289 return s
289
290
290
291
291 def remove_prefix(s, prefix):
292 def remove_prefix(s, prefix):
292 if s.startswith(prefix):
293 if s.startswith(prefix):
293 s = s[len(prefix):]
294 s = s[len(prefix):]
294 return s
295 return s
295
296
296
297
297 def find_calling_context(ignore_modules=None):
298 def find_calling_context(ignore_modules=None):
298 """
299 """
299 Look through the calling stack and return the frame which called
300 Look through the calling stack and return the frame which called
300 this function and is part of core module ( ie. rhodecode.* )
301 this function and is part of core module ( ie. rhodecode.* )
301
302
302 :param ignore_modules: list of modules to ignore eg. ['rhodecode.lib']
303 :param ignore_modules: list of modules to ignore eg. ['rhodecode.lib']
303 """
304 """
304
305
305 ignore_modules = ignore_modules or []
306 ignore_modules = ignore_modules or []
306
307
307 f = sys._getframe(2)
308 f = sys._getframe(2)
308 while f.f_back is not None:
309 while f.f_back is not None:
309 name = f.f_globals.get('__name__')
310 name = f.f_globals.get('__name__')
310 if name and name.startswith(__name__.split('.')[0]):
311 if name and name.startswith(__name__.split('.')[0]):
311 if name not in ignore_modules:
312 if name not in ignore_modules:
312 return f
313 return f
313 f = f.f_back
314 f = f.f_back
314 return None
315 return None
315
316
316
317
317 def ping_connection(connection, branch):
318 def ping_connection(connection, branch):
318 if branch:
319 if branch:
319 # "branch" refers to a sub-connection of a connection,
320 # "branch" refers to a sub-connection of a connection,
320 # we don't want to bother pinging on these.
321 # we don't want to bother pinging on these.
321 return
322 return
322
323
323 # turn off "close with result". This flag is only used with
324 # turn off "close with result". This flag is only used with
324 # "connectionless" execution, otherwise will be False in any case
325 # "connectionless" execution, otherwise will be False in any case
325 save_should_close_with_result = connection.should_close_with_result
326 save_should_close_with_result = connection.should_close_with_result
326 connection.should_close_with_result = False
327 connection.should_close_with_result = False
327
328
328 try:
329 try:
329 # run a SELECT 1. use a core select() so that
330 # run a SELECT 1. use a core select() so that
330 # the SELECT of a scalar value without a table is
331 # the SELECT of a scalar value without a table is
331 # appropriately formatted for the backend
332 # appropriately formatted for the backend
332 connection.scalar(sqlalchemy.sql.select([1]))
333 connection.scalar(sqlalchemy.sql.select([1]))
333 except sqlalchemy.exc.DBAPIError as err:
334 except sqlalchemy.exc.DBAPIError as err:
334 # catch SQLAlchemy's DBAPIError, which is a wrapper
335 # catch SQLAlchemy's DBAPIError, which is a wrapper
335 # for the DBAPI's exception. It includes a .connection_invalidated
336 # for the DBAPI's exception. It includes a .connection_invalidated
336 # attribute which specifies if this connection is a "disconnect"
337 # attribute which specifies if this connection is a "disconnect"
337 # condition, which is based on inspection of the original exception
338 # condition, which is based on inspection of the original exception
338 # by the dialect in use.
339 # by the dialect in use.
339 if err.connection_invalidated:
340 if err.connection_invalidated:
340 # run the same SELECT again - the connection will re-validate
341 # run the same SELECT again - the connection will re-validate
341 # itself and establish a new connection. The disconnect detection
342 # itself and establish a new connection. The disconnect detection
342 # here also causes the whole connection pool to be invalidated
343 # here also causes the whole connection pool to be invalidated
343 # so that all stale connections are discarded.
344 # so that all stale connections are discarded.
344 connection.scalar(sqlalchemy.sql.select([1]))
345 connection.scalar(sqlalchemy.sql.select([1]))
345 else:
346 else:
346 raise
347 raise
347 finally:
348 finally:
348 # restore "close with result"
349 # restore "close with result"
349 connection.should_close_with_result = save_should_close_with_result
350 connection.should_close_with_result = save_should_close_with_result
350
351
351
352
352 def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
353 def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
353 """Custom engine_from_config functions."""
354 """Custom engine_from_config functions."""
354 log = logging.getLogger('sqlalchemy.engine')
355 log = logging.getLogger('sqlalchemy.engine')
355 engine = sqlalchemy.engine_from_config(configuration, prefix, **kwargs)
356 engine = sqlalchemy.engine_from_config(configuration, prefix, **kwargs)
356
357
357 def color_sql(sql):
358 def color_sql(sql):
358 color_seq = '\033[1;33m' # This is yellow: code 33
359 color_seq = '\033[1;33m' # This is yellow: code 33
359 normal = '\x1b[0m'
360 normal = '\x1b[0m'
360 return ''.join([color_seq, sql, normal])
361 return ''.join([color_seq, sql, normal])
361
362
362 if configuration['debug']:
363 if configuration['debug']:
363 # attach events only for debug configuration
364 # attach events only for debug configuration
364
365
365 def before_cursor_execute(conn, cursor, statement,
366 def before_cursor_execute(conn, cursor, statement,
366 parameters, context, executemany):
367 parameters, context, executemany):
367 setattr(conn, 'query_start_time', time.time())
368 setattr(conn, 'query_start_time', time.time())
368 log.info(color_sql(">>>>> STARTING QUERY >>>>>"))
369 log.info(color_sql(">>>>> STARTING QUERY >>>>>"))
369 calling_context = find_calling_context(ignore_modules=[
370 calling_context = find_calling_context(ignore_modules=[
370 'rhodecode.lib.caching_query',
371 'rhodecode.lib.caching_query',
371 'rhodecode.model.settings',
372 'rhodecode.model.settings',
372 ])
373 ])
373 if calling_context:
374 if calling_context:
374 log.info(color_sql('call context %s:%s' % (
375 log.info(color_sql('call context %s:%s' % (
375 calling_context.f_code.co_filename,
376 calling_context.f_code.co_filename,
376 calling_context.f_lineno,
377 calling_context.f_lineno,
377 )))
378 )))
378
379
379 def after_cursor_execute(conn, cursor, statement,
380 def after_cursor_execute(conn, cursor, statement,
380 parameters, context, executemany):
381 parameters, context, executemany):
381 delattr(conn, 'query_start_time')
382 delattr(conn, 'query_start_time')
382
383
383 sqlalchemy.event.listen(engine, "engine_connect",
384 sqlalchemy.event.listen(engine, "engine_connect",
384 ping_connection)
385 ping_connection)
385 sqlalchemy.event.listen(engine, "before_cursor_execute",
386 sqlalchemy.event.listen(engine, "before_cursor_execute",
386 before_cursor_execute)
387 before_cursor_execute)
387 sqlalchemy.event.listen(engine, "after_cursor_execute",
388 sqlalchemy.event.listen(engine, "after_cursor_execute",
388 after_cursor_execute)
389 after_cursor_execute)
389
390
390 return engine
391 return engine
391
392
392
393
393 def get_encryption_key(config):
394 def get_encryption_key(config):
394 secret = config.get('rhodecode.encrypted_values.secret')
395 secret = config.get('rhodecode.encrypted_values.secret')
395 default = config['beaker.session.secret']
396 default = config['beaker.session.secret']
396 return secret or default
397 return secret or default
397
398
398
399
399 def age(prevdate, now=None, show_short_version=False, show_suffix=True,
400 def age(prevdate, now=None, show_short_version=False, show_suffix=True,
400 short_format=False):
401 short_format=False):
401 """
402 """
402 Turns a datetime into an age string.
403 Turns a datetime into an age string.
403 If show_short_version is True, this generates a shorter string with
404 If show_short_version is True, this generates a shorter string with
404 an approximate age; ex. '1 day ago', rather than '1 day and 23 hours ago'.
405 an approximate age; ex. '1 day ago', rather than '1 day and 23 hours ago'.
405
406
406 * IMPORTANT*
407 * IMPORTANT*
407 Code of this function is written in special way so it's easier to
408 Code of this function is written in special way so it's easier to
408 backport it to javascript. If you mean to update it, please also update
409 backport it to javascript. If you mean to update it, please also update
409 `jquery.timeago-extension.js` file
410 `jquery.timeago-extension.js` file
410
411
411 :param prevdate: datetime object
412 :param prevdate: datetime object
412 :param now: get current time, if not define we use
413 :param now: get current time, if not define we use
413 `datetime.datetime.now()`
414 `datetime.datetime.now()`
414 :param show_short_version: if it should approximate the date and
415 :param show_short_version: if it should approximate the date and
415 return a shorter string
416 return a shorter string
416 :param show_suffix:
417 :param show_suffix:
417 :param short_format: show short format, eg 2D instead of 2 days
418 :param short_format: show short format, eg 2D instead of 2 days
418 :rtype: unicode
419 :rtype: unicode
419 :returns: unicode words describing age
420 :returns: unicode words describing age
420 """
421 """
421
422
422 def _get_relative_delta(now, prevdate):
423 def _get_relative_delta(now, prevdate):
423 base = dateutil.relativedelta.relativedelta(now, prevdate)
424 base = dateutil.relativedelta.relativedelta(now, prevdate)
424 return {
425 return {
425 'year': base.years,
426 'year': base.years,
426 'month': base.months,
427 'month': base.months,
427 'day': base.days,
428 'day': base.days,
428 'hour': base.hours,
429 'hour': base.hours,
429 'minute': base.minutes,
430 'minute': base.minutes,
430 'second': base.seconds,
431 'second': base.seconds,
431 }
432 }
432
433
433 def _is_leap_year(year):
434 def _is_leap_year(year):
434 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
435 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
435
436
436 def get_month(prevdate):
437 def get_month(prevdate):
437 return prevdate.month
438 return prevdate.month
438
439
439 def get_year(prevdate):
440 def get_year(prevdate):
440 return prevdate.year
441 return prevdate.year
441
442
442 now = now or datetime.datetime.now()
443 now = now or datetime.datetime.now()
443 order = ['year', 'month', 'day', 'hour', 'minute', 'second']
444 order = ['year', 'month', 'day', 'hour', 'minute', 'second']
444 deltas = {}
445 deltas = {}
445 future = False
446 future = False
446
447
447 if prevdate > now:
448 if prevdate > now:
448 now_old = now
449 now_old = now
449 now = prevdate
450 now = prevdate
450 prevdate = now_old
451 prevdate = now_old
451 future = True
452 future = True
452 if future:
453 if future:
453 prevdate = prevdate.replace(microsecond=0)
454 prevdate = prevdate.replace(microsecond=0)
454 # Get date parts deltas
455 # Get date parts deltas
455 for part in order:
456 for part in order:
456 rel_delta = _get_relative_delta(now, prevdate)
457 rel_delta = _get_relative_delta(now, prevdate)
457 deltas[part] = rel_delta[part]
458 deltas[part] = rel_delta[part]
458
459
459 # Fix negative offsets (there is 1 second between 10:59:59 and 11:00:00,
460 # Fix negative offsets (there is 1 second between 10:59:59 and 11:00:00,
460 # not 1 hour, -59 minutes and -59 seconds)
461 # not 1 hour, -59 minutes and -59 seconds)
461 offsets = [[5, 60], [4, 60], [3, 24]]
462 offsets = [[5, 60], [4, 60], [3, 24]]
462 for element in offsets: # seconds, minutes, hours
463 for element in offsets: # seconds, minutes, hours
463 num = element[0]
464 num = element[0]
464 length = element[1]
465 length = element[1]
465
466
466 part = order[num]
467 part = order[num]
467 carry_part = order[num - 1]
468 carry_part = order[num - 1]
468
469
469 if deltas[part] < 0:
470 if deltas[part] < 0:
470 deltas[part] += length
471 deltas[part] += length
471 deltas[carry_part] -= 1
472 deltas[carry_part] -= 1
472
473
473 # Same thing for days except that the increment depends on the (variable)
474 # Same thing for days except that the increment depends on the (variable)
474 # number of days in the month
475 # number of days in the month
475 month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
476 month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
476 if deltas['day'] < 0:
477 if deltas['day'] < 0:
477 if get_month(prevdate) == 2 and _is_leap_year(get_year(prevdate)):
478 if get_month(prevdate) == 2 and _is_leap_year(get_year(prevdate)):
478 deltas['day'] += 29
479 deltas['day'] += 29
479 else:
480 else:
480 deltas['day'] += month_lengths[get_month(prevdate) - 1]
481 deltas['day'] += month_lengths[get_month(prevdate) - 1]
481
482
482 deltas['month'] -= 1
483 deltas['month'] -= 1
483
484
484 if deltas['month'] < 0:
485 if deltas['month'] < 0:
485 deltas['month'] += 12
486 deltas['month'] += 12
486 deltas['year'] -= 1
487 deltas['year'] -= 1
487
488
488 # Format the result
489 # Format the result
489 if short_format:
490 if short_format:
490 fmt_funcs = {
491 fmt_funcs = {
491 'year': lambda d: u'%dy' % d,
492 'year': lambda d: u'%dy' % d,
492 'month': lambda d: u'%dm' % d,
493 'month': lambda d: u'%dm' % d,
493 'day': lambda d: u'%dd' % d,
494 'day': lambda d: u'%dd' % d,
494 'hour': lambda d: u'%dh' % d,
495 'hour': lambda d: u'%dh' % d,
495 'minute': lambda d: u'%dmin' % d,
496 'minute': lambda d: u'%dmin' % d,
496 'second': lambda d: u'%dsec' % d,
497 'second': lambda d: u'%dsec' % d,
497 }
498 }
498 else:
499 else:
499 fmt_funcs = {
500 fmt_funcs = {
500 'year': lambda d: _pluralize(u'${num} year', u'${num} years', d, mapping={'num': d}).interpolate(),
501 'year': lambda d: _pluralize(u'${num} year', u'${num} years', d, mapping={'num': d}).interpolate(),
501 'month': lambda d: _pluralize(u'${num} month', u'${num} months', d, mapping={'num': d}).interpolate(),
502 'month': lambda d: _pluralize(u'${num} month', u'${num} months', d, mapping={'num': d}).interpolate(),
502 'day': lambda d: _pluralize(u'${num} day', u'${num} days', d, mapping={'num': d}).interpolate(),
503 'day': lambda d: _pluralize(u'${num} day', u'${num} days', d, mapping={'num': d}).interpolate(),
503 'hour': lambda d: _pluralize(u'${num} hour', u'${num} hours', d, mapping={'num': d}).interpolate(),
504 'hour': lambda d: _pluralize(u'${num} hour', u'${num} hours', d, mapping={'num': d}).interpolate(),
504 'minute': lambda d: _pluralize(u'${num} minute', u'${num} minutes', d, mapping={'num': d}).interpolate(),
505 'minute': lambda d: _pluralize(u'${num} minute', u'${num} minutes', d, mapping={'num': d}).interpolate(),
505 'second': lambda d: _pluralize(u'${num} second', u'${num} seconds', d, mapping={'num': d}).interpolate(),
506 'second': lambda d: _pluralize(u'${num} second', u'${num} seconds', d, mapping={'num': d}).interpolate(),
506 }
507 }
507
508
508 i = 0
509 i = 0
509 for part in order:
510 for part in order:
510 value = deltas[part]
511 value = deltas[part]
511 if value != 0:
512 if value != 0:
512
513
513 if i < 5:
514 if i < 5:
514 sub_part = order[i + 1]
515 sub_part = order[i + 1]
515 sub_value = deltas[sub_part]
516 sub_value = deltas[sub_part]
516 else:
517 else:
517 sub_value = 0
518 sub_value = 0
518
519
519 if sub_value == 0 or show_short_version:
520 if sub_value == 0 or show_short_version:
520 _val = fmt_funcs[part](value)
521 _val = fmt_funcs[part](value)
521 if future:
522 if future:
522 if show_suffix:
523 if show_suffix:
523 return _(u'in ${ago}', mapping={'ago': _val})
524 return _(u'in ${ago}', mapping={'ago': _val})
524 else:
525 else:
525 return _(_val)
526 return _(_val)
526
527
527 else:
528 else:
528 if show_suffix:
529 if show_suffix:
529 return _(u'${ago} ago', mapping={'ago': _val})
530 return _(u'${ago} ago', mapping={'ago': _val})
530 else:
531 else:
531 return _(_val)
532 return _(_val)
532
533
533 val = fmt_funcs[part](value)
534 val = fmt_funcs[part](value)
534 val_detail = fmt_funcs[sub_part](sub_value)
535 val_detail = fmt_funcs[sub_part](sub_value)
535 mapping = {'val': val, 'detail': val_detail}
536 mapping = {'val': val, 'detail': val_detail}
536
537
537 if short_format:
538 if short_format:
538 datetime_tmpl = _(u'${val}, ${detail}', mapping=mapping)
539 datetime_tmpl = _(u'${val}, ${detail}', mapping=mapping)
539 if show_suffix:
540 if show_suffix:
540 datetime_tmpl = _(u'${val}, ${detail} ago', mapping=mapping)
541 datetime_tmpl = _(u'${val}, ${detail} ago', mapping=mapping)
541 if future:
542 if future:
542 datetime_tmpl = _(u'in ${val}, ${detail}', mapping=mapping)
543 datetime_tmpl = _(u'in ${val}, ${detail}', mapping=mapping)
543 else:
544 else:
544 datetime_tmpl = _(u'${val} and ${detail}', mapping=mapping)
545 datetime_tmpl = _(u'${val} and ${detail}', mapping=mapping)
545 if show_suffix:
546 if show_suffix:
546 datetime_tmpl = _(u'${val} and ${detail} ago', mapping=mapping)
547 datetime_tmpl = _(u'${val} and ${detail} ago', mapping=mapping)
547 if future:
548 if future:
548 datetime_tmpl = _(u'in ${val} and ${detail}', mapping=mapping)
549 datetime_tmpl = _(u'in ${val} and ${detail}', mapping=mapping)
549
550
550 return datetime_tmpl
551 return datetime_tmpl
551 i += 1
552 i += 1
552 return _(u'just now')
553 return _(u'just now')
553
554
554
555
555 def cleaned_uri(uri):
556 def cleaned_uri(uri):
556 """
557 """
557 Quotes '[' and ']' from uri if there is only one of them.
558 Quotes '[' and ']' from uri if there is only one of them.
558 according to RFC3986 we cannot use such chars in uri
559 according to RFC3986 we cannot use such chars in uri
559 :param uri:
560 :param uri:
560 :return: uri without this chars
561 :return: uri without this chars
561 """
562 """
562 return urllib.quote(uri, safe='@$:/')
563 return urllib.quote(uri, safe='@$:/')
563
564
564
565
565 def uri_filter(uri):
566 def uri_filter(uri):
566 """
567 """
567 Removes user:password from given url string
568 Removes user:password from given url string
568
569
569 :param uri:
570 :param uri:
570 :rtype: unicode
571 :rtype: unicode
571 :returns: filtered list of strings
572 :returns: filtered list of strings
572 """
573 """
573 if not uri:
574 if not uri:
574 return ''
575 return ''
575
576
576 proto = ''
577 proto = ''
577
578
578 for pat in ('https://', 'http://'):
579 for pat in ('https://', 'http://'):
579 if uri.startswith(pat):
580 if uri.startswith(pat):
580 uri = uri[len(pat):]
581 uri = uri[len(pat):]
581 proto = pat
582 proto = pat
582 break
583 break
583
584
584 # remove passwords and username
585 # remove passwords and username
585 uri = uri[uri.find('@') + 1:]
586 uri = uri[uri.find('@') + 1:]
586
587
587 # get the port
588 # get the port
588 cred_pos = uri.find(':')
589 cred_pos = uri.find(':')
589 if cred_pos == -1:
590 if cred_pos == -1:
590 host, port = uri, None
591 host, port = uri, None
591 else:
592 else:
592 host, port = uri[:cred_pos], uri[cred_pos + 1:]
593 host, port = uri[:cred_pos], uri[cred_pos + 1:]
593
594
594 return filter(None, [proto, host, port])
595 return filter(None, [proto, host, port])
595
596
596
597
597 def credentials_filter(uri):
598 def credentials_filter(uri):
598 """
599 """
599 Returns a url with removed credentials
600 Returns a url with removed credentials
600
601
601 :param uri:
602 :param uri:
602 """
603 """
603
604
604 uri = uri_filter(uri)
605 uri = uri_filter(uri)
605 # check if we have port
606 # check if we have port
606 if len(uri) > 2 and uri[2]:
607 if len(uri) > 2 and uri[2]:
607 uri[2] = ':' + uri[2]
608 uri[2] = ':' + uri[2]
608
609
609 return ''.join(uri)
610 return ''.join(uri)
610
611
611
612
612 def get_clone_url(request, uri_tmpl, repo_name, repo_id, **override):
613 def get_clone_url(request, uri_tmpl, repo_name, repo_id, **override):
613 qualifed_home_url = request.route_url('home')
614 qualifed_home_url = request.route_url('home')
614 parsed_url = urlobject.URLObject(qualifed_home_url)
615 parsed_url = urlobject.URLObject(qualifed_home_url)
615 decoded_path = safe_unicode(urllib.unquote(parsed_url.path.rstrip('/')))
616 decoded_path = safe_unicode(urllib.unquote(parsed_url.path.rstrip('/')))
617
616 args = {
618 args = {
617 'scheme': parsed_url.scheme,
619 'scheme': parsed_url.scheme,
618 'user': '',
620 'user': '',
621 'sys_user': getpass.getuser(),
619 # path if we use proxy-prefix
622 # path if we use proxy-prefix
620 'netloc': parsed_url.netloc+decoded_path,
623 'netloc': parsed_url.netloc+decoded_path,
624 'hostname': parsed_url.hostname,
621 'prefix': decoded_path,
625 'prefix': decoded_path,
622 'repo': repo_name,
626 'repo': repo_name,
623 'repoid': str(repo_id)
627 'repoid': str(repo_id)
624 }
628 }
625 args.update(override)
629 args.update(override)
626 args['user'] = urllib.quote(safe_str(args['user']))
630 args['user'] = urllib.quote(safe_str(args['user']))
627
631
628 for k, v in args.items():
632 for k, v in args.items():
629 uri_tmpl = uri_tmpl.replace('{%s}' % k, v)
633 uri_tmpl = uri_tmpl.replace('{%s}' % k, v)
630
634
631 # remove leading @ sign if it's present. Case of empty user
635 # remove leading @ sign if it's present. Case of empty user
632 url_obj = urlobject.URLObject(uri_tmpl)
636 url_obj = urlobject.URLObject(uri_tmpl)
633 url = url_obj.with_netloc(url_obj.netloc.lstrip('@'))
637 url = url_obj.with_netloc(url_obj.netloc.lstrip('@'))
634
638
635 return safe_unicode(url)
639 return safe_unicode(url)
636
640
637
641
638 def get_commit_safe(repo, commit_id=None, commit_idx=None, pre_load=None):
642 def get_commit_safe(repo, commit_id=None, commit_idx=None, pre_load=None):
639 """
643 """
640 Safe version of get_commit if this commit doesn't exists for a
644 Safe version of get_commit if this commit doesn't exists for a
641 repository it returns a Dummy one instead
645 repository it returns a Dummy one instead
642
646
643 :param repo: repository instance
647 :param repo: repository instance
644 :param commit_id: commit id as str
648 :param commit_id: commit id as str
645 :param pre_load: optional list of commit attributes to load
649 :param pre_load: optional list of commit attributes to load
646 """
650 """
647 # TODO(skreft): remove these circular imports
651 # TODO(skreft): remove these circular imports
648 from rhodecode.lib.vcs.backends.base import BaseRepository, EmptyCommit
652 from rhodecode.lib.vcs.backends.base import BaseRepository, EmptyCommit
649 from rhodecode.lib.vcs.exceptions import RepositoryError
653 from rhodecode.lib.vcs.exceptions import RepositoryError
650 if not isinstance(repo, BaseRepository):
654 if not isinstance(repo, BaseRepository):
651 raise Exception('You must pass an Repository '
655 raise Exception('You must pass an Repository '
652 'object as first argument got %s', type(repo))
656 'object as first argument got %s', type(repo))
653
657
654 try:
658 try:
655 commit = repo.get_commit(
659 commit = repo.get_commit(
656 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
660 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
657 except (RepositoryError, LookupError):
661 except (RepositoryError, LookupError):
658 commit = EmptyCommit()
662 commit = EmptyCommit()
659 return commit
663 return commit
660
664
661
665
662 def datetime_to_time(dt):
666 def datetime_to_time(dt):
663 if dt:
667 if dt:
664 return time.mktime(dt.timetuple())
668 return time.mktime(dt.timetuple())
665
669
666
670
667 def time_to_datetime(tm):
671 def time_to_datetime(tm):
668 if tm:
672 if tm:
669 if isinstance(tm, basestring):
673 if isinstance(tm, basestring):
670 try:
674 try:
671 tm = float(tm)
675 tm = float(tm)
672 except ValueError:
676 except ValueError:
673 return
677 return
674 return datetime.datetime.fromtimestamp(tm)
678 return datetime.datetime.fromtimestamp(tm)
675
679
676
680
677 def time_to_utcdatetime(tm):
681 def time_to_utcdatetime(tm):
678 if tm:
682 if tm:
679 if isinstance(tm, basestring):
683 if isinstance(tm, basestring):
680 try:
684 try:
681 tm = float(tm)
685 tm = float(tm)
682 except ValueError:
686 except ValueError:
683 return
687 return
684 return datetime.datetime.utcfromtimestamp(tm)
688 return datetime.datetime.utcfromtimestamp(tm)
685
689
686
690
687 MENTIONS_REGEX = re.compile(
691 MENTIONS_REGEX = re.compile(
688 # ^@ or @ without any special chars in front
692 # ^@ or @ without any special chars in front
689 r'(?:^@|[^a-zA-Z0-9\-\_\.]@)'
693 r'(?:^@|[^a-zA-Z0-9\-\_\.]@)'
690 # main body starts with letter, then can be . - _
694 # main body starts with letter, then can be . - _
691 r'([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)',
695 r'([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)',
692 re.VERBOSE | re.MULTILINE)
696 re.VERBOSE | re.MULTILINE)
693
697
694
698
695 def extract_mentioned_users(s):
699 def extract_mentioned_users(s):
696 """
700 """
697 Returns unique usernames from given string s that have @mention
701 Returns unique usernames from given string s that have @mention
698
702
699 :param s: string to get mentions
703 :param s: string to get mentions
700 """
704 """
701 usrs = set()
705 usrs = set()
702 for username in MENTIONS_REGEX.findall(s):
706 for username in MENTIONS_REGEX.findall(s):
703 usrs.add(username)
707 usrs.add(username)
704
708
705 return sorted(list(usrs), key=lambda k: k.lower())
709 return sorted(list(usrs), key=lambda k: k.lower())
706
710
707
711
708 class StrictAttributeDict(dict):
712 class StrictAttributeDict(dict):
709 """
713 """
710 Strict Version of Attribute dict which raises an Attribute error when
714 Strict Version of Attribute dict which raises an Attribute error when
711 requested attribute is not set
715 requested attribute is not set
712 """
716 """
713 def __getattr__(self, attr):
717 def __getattr__(self, attr):
714 try:
718 try:
715 return self[attr]
719 return self[attr]
716 except KeyError:
720 except KeyError:
717 raise AttributeError('%s object has no attribute %s' % (
721 raise AttributeError('%s object has no attribute %s' % (
718 self.__class__, attr))
722 self.__class__, attr))
719 __setattr__ = dict.__setitem__
723 __setattr__ = dict.__setitem__
720 __delattr__ = dict.__delitem__
724 __delattr__ = dict.__delitem__
721
725
722
726
723 class AttributeDict(dict):
727 class AttributeDict(dict):
724 def __getattr__(self, attr):
728 def __getattr__(self, attr):
725 return self.get(attr, None)
729 return self.get(attr, None)
726 __setattr__ = dict.__setitem__
730 __setattr__ = dict.__setitem__
727 __delattr__ = dict.__delitem__
731 __delattr__ = dict.__delitem__
728
732
729
733
730 def fix_PATH(os_=None):
734 def fix_PATH(os_=None):
731 """
735 """
732 Get current active python path, and append it to PATH variable to fix
736 Get current active python path, and append it to PATH variable to fix
733 issues of subprocess calls and different python versions
737 issues of subprocess calls and different python versions
734 """
738 """
735 if os_ is None:
739 if os_ is None:
736 import os
740 import os
737 else:
741 else:
738 os = os_
742 os = os_
739
743
740 cur_path = os.path.split(sys.executable)[0]
744 cur_path = os.path.split(sys.executable)[0]
741 if not os.environ['PATH'].startswith(cur_path):
745 if not os.environ['PATH'].startswith(cur_path):
742 os.environ['PATH'] = '%s:%s' % (cur_path, os.environ['PATH'])
746 os.environ['PATH'] = '%s:%s' % (cur_path, os.environ['PATH'])
743
747
744
748
745 def obfuscate_url_pw(engine):
749 def obfuscate_url_pw(engine):
746 _url = engine or ''
750 _url = engine or ''
747 try:
751 try:
748 _url = sqlalchemy.engine.url.make_url(engine)
752 _url = sqlalchemy.engine.url.make_url(engine)
749 if _url.password:
753 if _url.password:
750 _url.password = 'XXXXX'
754 _url.password = 'XXXXX'
751 except Exception:
755 except Exception:
752 pass
756 pass
753 return unicode(_url)
757 return unicode(_url)
754
758
755
759
756 def get_server_url(environ):
760 def get_server_url(environ):
757 req = webob.Request(environ)
761 req = webob.Request(environ)
758 return req.host_url + req.script_name
762 return req.host_url + req.script_name
759
763
760
764
761 def unique_id(hexlen=32):
765 def unique_id(hexlen=32):
762 alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz"
766 alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz"
763 return suuid(truncate_to=hexlen, alphabet=alphabet)
767 return suuid(truncate_to=hexlen, alphabet=alphabet)
764
768
765
769
766 def suuid(url=None, truncate_to=22, alphabet=None):
770 def suuid(url=None, truncate_to=22, alphabet=None):
767 """
771 """
768 Generate and return a short URL safe UUID.
772 Generate and return a short URL safe UUID.
769
773
770 If the url parameter is provided, set the namespace to the provided
774 If the url parameter is provided, set the namespace to the provided
771 URL and generate a UUID.
775 URL and generate a UUID.
772
776
773 :param url to get the uuid for
777 :param url to get the uuid for
774 :truncate_to: truncate the basic 22 UUID to shorter version
778 :truncate_to: truncate the basic 22 UUID to shorter version
775
779
776 The IDs won't be universally unique any longer, but the probability of
780 The IDs won't be universally unique any longer, but the probability of
777 a collision will still be very low.
781 a collision will still be very low.
778 """
782 """
779 # Define our alphabet.
783 # Define our alphabet.
780 _ALPHABET = alphabet or "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
784 _ALPHABET = alphabet or "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
781
785
782 # If no URL is given, generate a random UUID.
786 # If no URL is given, generate a random UUID.
783 if url is None:
787 if url is None:
784 unique_id = uuid.uuid4().int
788 unique_id = uuid.uuid4().int
785 else:
789 else:
786 unique_id = uuid.uuid3(uuid.NAMESPACE_URL, url).int
790 unique_id = uuid.uuid3(uuid.NAMESPACE_URL, url).int
787
791
788 alphabet_length = len(_ALPHABET)
792 alphabet_length = len(_ALPHABET)
789 output = []
793 output = []
790 while unique_id > 0:
794 while unique_id > 0:
791 digit = unique_id % alphabet_length
795 digit = unique_id % alphabet_length
792 output.append(_ALPHABET[digit])
796 output.append(_ALPHABET[digit])
793 unique_id = int(unique_id / alphabet_length)
797 unique_id = int(unique_id / alphabet_length)
794 return "".join(output)[:truncate_to]
798 return "".join(output)[:truncate_to]
795
799
796
800
797 def get_current_rhodecode_user(request=None):
801 def get_current_rhodecode_user(request=None):
798 """
802 """
799 Gets rhodecode user from request
803 Gets rhodecode user from request
800 """
804 """
801 pyramid_request = request or pyramid.threadlocal.get_current_request()
805 pyramid_request = request or pyramid.threadlocal.get_current_request()
802
806
803 # web case
807 # web case
804 if pyramid_request and hasattr(pyramid_request, 'user'):
808 if pyramid_request and hasattr(pyramid_request, 'user'):
805 return pyramid_request.user
809 return pyramid_request.user
806
810
807 # api case
811 # api case
808 if pyramid_request and hasattr(pyramid_request, 'rpc_user'):
812 if pyramid_request and hasattr(pyramid_request, 'rpc_user'):
809 return pyramid_request.rpc_user
813 return pyramid_request.rpc_user
810
814
811 return None
815 return None
812
816
813
817
814 def action_logger_generic(action, namespace=''):
818 def action_logger_generic(action, namespace=''):
815 """
819 """
816 A generic logger for actions useful to the system overview, tries to find
820 A generic logger for actions useful to the system overview, tries to find
817 an acting user for the context of the call otherwise reports unknown user
821 an acting user for the context of the call otherwise reports unknown user
818
822
819 :param action: logging message eg 'comment 5 deleted'
823 :param action: logging message eg 'comment 5 deleted'
820 :param type: string
824 :param type: string
821
825
822 :param namespace: namespace of the logging message eg. 'repo.comments'
826 :param namespace: namespace of the logging message eg. 'repo.comments'
823 :param type: string
827 :param type: string
824
828
825 """
829 """
826
830
827 logger_name = 'rhodecode.actions'
831 logger_name = 'rhodecode.actions'
828
832
829 if namespace:
833 if namespace:
830 logger_name += '.' + namespace
834 logger_name += '.' + namespace
831
835
832 log = logging.getLogger(logger_name)
836 log = logging.getLogger(logger_name)
833
837
834 # get a user if we can
838 # get a user if we can
835 user = get_current_rhodecode_user()
839 user = get_current_rhodecode_user()
836
840
837 logfunc = log.info
841 logfunc = log.info
838
842
839 if not user:
843 if not user:
840 user = '<unknown user>'
844 user = '<unknown user>'
841 logfunc = log.warning
845 logfunc = log.warning
842
846
843 logfunc('Logging action by {}: {}'.format(user, action))
847 logfunc('Logging action by {}: {}'.format(user, action))
844
848
845
849
846 def escape_split(text, sep=',', maxsplit=-1):
850 def escape_split(text, sep=',', maxsplit=-1):
847 r"""
851 r"""
848 Allows for escaping of the separator: e.g. arg='foo\, bar'
852 Allows for escaping of the separator: e.g. arg='foo\, bar'
849
853
850 It should be noted that the way bash et. al. do command line parsing, those
854 It should be noted that the way bash et. al. do command line parsing, those
851 single quotes are required.
855 single quotes are required.
852 """
856 """
853 escaped_sep = r'\%s' % sep
857 escaped_sep = r'\%s' % sep
854
858
855 if escaped_sep not in text:
859 if escaped_sep not in text:
856 return text.split(sep, maxsplit)
860 return text.split(sep, maxsplit)
857
861
858 before, _mid, after = text.partition(escaped_sep)
862 before, _mid, after = text.partition(escaped_sep)
859 startlist = before.split(sep, maxsplit) # a regular split is fine here
863 startlist = before.split(sep, maxsplit) # a regular split is fine here
860 unfinished = startlist[-1]
864 unfinished = startlist[-1]
861 startlist = startlist[:-1]
865 startlist = startlist[:-1]
862
866
863 # recurse because there may be more escaped separators
867 # recurse because there may be more escaped separators
864 endlist = escape_split(after, sep, maxsplit)
868 endlist = escape_split(after, sep, maxsplit)
865
869
866 # finish building the escaped value. we use endlist[0] becaue the first
870 # finish building the escaped value. we use endlist[0] becaue the first
867 # part of the string sent in recursion is the rest of the escaped value.
871 # part of the string sent in recursion is the rest of the escaped value.
868 unfinished += sep + endlist[0]
872 unfinished += sep + endlist[0]
869
873
870 return startlist + [unfinished] + endlist[1:] # put together all the parts
874 return startlist + [unfinished] + endlist[1:] # put together all the parts
871
875
872
876
873 class OptionalAttr(object):
877 class OptionalAttr(object):
874 """
878 """
875 Special Optional Option that defines other attribute. Example::
879 Special Optional Option that defines other attribute. Example::
876
880
877 def test(apiuser, userid=Optional(OAttr('apiuser')):
881 def test(apiuser, userid=Optional(OAttr('apiuser')):
878 user = Optional.extract(userid)
882 user = Optional.extract(userid)
879 # calls
883 # calls
880
884
881 """
885 """
882
886
883 def __init__(self, attr_name):
887 def __init__(self, attr_name):
884 self.attr_name = attr_name
888 self.attr_name = attr_name
885
889
886 def __repr__(self):
890 def __repr__(self):
887 return '<OptionalAttr:%s>' % self.attr_name
891 return '<OptionalAttr:%s>' % self.attr_name
888
892
889 def __call__(self):
893 def __call__(self):
890 return self
894 return self
891
895
892
896
893 # alias
897 # alias
894 OAttr = OptionalAttr
898 OAttr = OptionalAttr
895
899
896
900
897 class Optional(object):
901 class Optional(object):
898 """
902 """
899 Defines an optional parameter::
903 Defines an optional parameter::
900
904
901 param = param.getval() if isinstance(param, Optional) else param
905 param = param.getval() if isinstance(param, Optional) else param
902 param = param() if isinstance(param, Optional) else param
906 param = param() if isinstance(param, Optional) else param
903
907
904 is equivalent of::
908 is equivalent of::
905
909
906 param = Optional.extract(param)
910 param = Optional.extract(param)
907
911
908 """
912 """
909
913
910 def __init__(self, type_):
914 def __init__(self, type_):
911 self.type_ = type_
915 self.type_ = type_
912
916
913 def __repr__(self):
917 def __repr__(self):
914 return '<Optional:%s>' % self.type_.__repr__()
918 return '<Optional:%s>' % self.type_.__repr__()
915
919
916 def __call__(self):
920 def __call__(self):
917 return self.getval()
921 return self.getval()
918
922
919 def getval(self):
923 def getval(self):
920 """
924 """
921 returns value from this Optional instance
925 returns value from this Optional instance
922 """
926 """
923 if isinstance(self.type_, OAttr):
927 if isinstance(self.type_, OAttr):
924 # use params name
928 # use params name
925 return self.type_.attr_name
929 return self.type_.attr_name
926 return self.type_
930 return self.type_
927
931
928 @classmethod
932 @classmethod
929 def extract(cls, val):
933 def extract(cls, val):
930 """
934 """
931 Extracts value from Optional() instance
935 Extracts value from Optional() instance
932
936
933 :param val:
937 :param val:
934 :return: original value if it's not Optional instance else
938 :return: original value if it's not Optional instance else
935 value of instance
939 value of instance
936 """
940 """
937 if isinstance(val, cls):
941 if isinstance(val, cls):
938 return val.getval()
942 return val.getval()
939 return val
943 return val
940
944
941
945
942 def glob2re(pat):
946 def glob2re(pat):
943 """
947 """
944 Translate a shell PATTERN to a regular expression.
948 Translate a shell PATTERN to a regular expression.
945
949
946 There is no way to quote meta-characters.
950 There is no way to quote meta-characters.
947 """
951 """
948
952
949 i, n = 0, len(pat)
953 i, n = 0, len(pat)
950 res = ''
954 res = ''
951 while i < n:
955 while i < n:
952 c = pat[i]
956 c = pat[i]
953 i = i+1
957 i = i+1
954 if c == '*':
958 if c == '*':
955 #res = res + '.*'
959 #res = res + '.*'
956 res = res + '[^/]*'
960 res = res + '[^/]*'
957 elif c == '?':
961 elif c == '?':
958 #res = res + '.'
962 #res = res + '.'
959 res = res + '[^/]'
963 res = res + '[^/]'
960 elif c == '[':
964 elif c == '[':
961 j = i
965 j = i
962 if j < n and pat[j] == '!':
966 if j < n and pat[j] == '!':
963 j = j+1
967 j = j+1
964 if j < n and pat[j] == ']':
968 if j < n and pat[j] == ']':
965 j = j+1
969 j = j+1
966 while j < n and pat[j] != ']':
970 while j < n and pat[j] != ']':
967 j = j+1
971 j = j+1
968 if j >= n:
972 if j >= n:
969 res = res + '\\['
973 res = res + '\\['
970 else:
974 else:
971 stuff = pat[i:j].replace('\\','\\\\')
975 stuff = pat[i:j].replace('\\','\\\\')
972 i = j+1
976 i = j+1
973 if stuff[0] == '!':
977 if stuff[0] == '!':
974 stuff = '^' + stuff[1:]
978 stuff = '^' + stuff[1:]
975 elif stuff[0] == '^':
979 elif stuff[0] == '^':
976 stuff = '\\' + stuff
980 stuff = '\\' + stuff
977 res = '%s[%s]' % (res, stuff)
981 res = '%s[%s]' % (res, stuff)
978 else:
982 else:
979 res = res + re.escape(c)
983 res = res + re.escape(c)
980 return res + '\Z(?ms)'
984 return res + '\Z(?ms)'
@@ -1,4453 +1,4463 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2018 RhodeCode GmbH
3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
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/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 Database Models for RhodeCode Enterprise
22 Database Models for RhodeCode Enterprise
23 """
23 """
24
24
25 import re
25 import re
26 import os
26 import os
27 import time
27 import time
28 import hashlib
28 import hashlib
29 import logging
29 import logging
30 import datetime
30 import datetime
31 import warnings
31 import warnings
32 import ipaddress
32 import ipaddress
33 import functools
33 import functools
34 import traceback
34 import traceback
35 import collections
35 import collections
36
36
37 from sqlalchemy import (
37 from sqlalchemy import (
38 or_, and_, not_, func, TypeDecorator, event,
38 or_, and_, not_, func, TypeDecorator, event,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 Text, Float, PickleType)
41 Text, Float, PickleType)
42 from sqlalchemy.sql.expression import true, false
42 from sqlalchemy.sql.expression import true, false
43 from sqlalchemy.sql.functions import coalesce, count # noqa
43 from sqlalchemy.sql.functions import coalesce, count # noqa
44 from sqlalchemy.orm import (
44 from sqlalchemy.orm import (
45 relationship, joinedload, class_mapper, validates, aliased)
45 relationship, joinedload, class_mapper, validates, aliased)
46 from sqlalchemy.ext.declarative import declared_attr
46 from sqlalchemy.ext.declarative import declared_attr
47 from sqlalchemy.ext.hybrid import hybrid_property
47 from sqlalchemy.ext.hybrid import hybrid_property
48 from sqlalchemy.exc import IntegrityError # noqa
48 from sqlalchemy.exc import IntegrityError # noqa
49 from sqlalchemy.dialects.mysql import LONGTEXT
49 from sqlalchemy.dialects.mysql import LONGTEXT
50 from beaker.cache import cache_region
50 from beaker.cache import cache_region
51 from zope.cachedescriptors.property import Lazy as LazyProperty
51 from zope.cachedescriptors.property import Lazy as LazyProperty
52
52
53 from pyramid.threadlocal import get_current_request
53 from pyramid.threadlocal import get_current_request
54
54
55 from rhodecode.translation import _
55 from rhodecode.translation import _
56 from rhodecode.lib.vcs import get_vcs_instance
56 from rhodecode.lib.vcs import get_vcs_instance
57 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
57 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
58 from rhodecode.lib.utils2 import (
58 from rhodecode.lib.utils2 import (
59 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
59 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
60 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
60 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
61 glob2re, StrictAttributeDict, cleaned_uri)
61 glob2re, StrictAttributeDict, cleaned_uri)
62 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
62 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
63 JsonRaw
63 JsonRaw
64 from rhodecode.lib.ext_json import json
64 from rhodecode.lib.ext_json import json
65 from rhodecode.lib.caching_query import FromCache
65 from rhodecode.lib.caching_query import FromCache
66 from rhodecode.lib.encrypt import AESCipher
66 from rhodecode.lib.encrypt import AESCipher
67
67
68 from rhodecode.model.meta import Base, Session
68 from rhodecode.model.meta import Base, Session
69
69
70 URL_SEP = '/'
70 URL_SEP = '/'
71 log = logging.getLogger(__name__)
71 log = logging.getLogger(__name__)
72
72
73 # =============================================================================
73 # =============================================================================
74 # BASE CLASSES
74 # BASE CLASSES
75 # =============================================================================
75 # =============================================================================
76
76
77 # this is propagated from .ini file rhodecode.encrypted_values.secret or
77 # this is propagated from .ini file rhodecode.encrypted_values.secret or
78 # beaker.session.secret if first is not set.
78 # beaker.session.secret if first is not set.
79 # and initialized at environment.py
79 # and initialized at environment.py
80 ENCRYPTION_KEY = None
80 ENCRYPTION_KEY = None
81
81
82 # used to sort permissions by types, '#' used here is not allowed to be in
82 # used to sort permissions by types, '#' used here is not allowed to be in
83 # usernames, and it's very early in sorted string.printable table.
83 # usernames, and it's very early in sorted string.printable table.
84 PERMISSION_TYPE_SORT = {
84 PERMISSION_TYPE_SORT = {
85 'admin': '####',
85 'admin': '####',
86 'write': '###',
86 'write': '###',
87 'read': '##',
87 'read': '##',
88 'none': '#',
88 'none': '#',
89 }
89 }
90
90
91
91
92 def display_user_sort(obj):
92 def display_user_sort(obj):
93 """
93 """
94 Sort function used to sort permissions in .permissions() function of
94 Sort function used to sort permissions in .permissions() function of
95 Repository, RepoGroup, UserGroup. Also it put the default user in front
95 Repository, RepoGroup, UserGroup. Also it put the default user in front
96 of all other resources
96 of all other resources
97 """
97 """
98
98
99 if obj.username == User.DEFAULT_USER:
99 if obj.username == User.DEFAULT_USER:
100 return '#####'
100 return '#####'
101 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
101 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
102 return prefix + obj.username
102 return prefix + obj.username
103
103
104
104
105 def display_user_group_sort(obj):
105 def display_user_group_sort(obj):
106 """
106 """
107 Sort function used to sort permissions in .permissions() function of
107 Sort function used to sort permissions in .permissions() function of
108 Repository, RepoGroup, UserGroup. Also it put the default user in front
108 Repository, RepoGroup, UserGroup. Also it put the default user in front
109 of all other resources
109 of all other resources
110 """
110 """
111
111
112 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
112 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
113 return prefix + obj.users_group_name
113 return prefix + obj.users_group_name
114
114
115
115
116 def _hash_key(k):
116 def _hash_key(k):
117 return md5_safe(k)
117 return md5_safe(k)
118
118
119
119
120 def in_filter_generator(qry, items, limit=500):
120 def in_filter_generator(qry, items, limit=500):
121 """
121 """
122 Splits IN() into multiple with OR
122 Splits IN() into multiple with OR
123 e.g.::
123 e.g.::
124 cnt = Repository.query().filter(
124 cnt = Repository.query().filter(
125 or_(
125 or_(
126 *in_filter_generator(Repository.repo_id, range(100000))
126 *in_filter_generator(Repository.repo_id, range(100000))
127 )).count()
127 )).count()
128 """
128 """
129 if not items:
129 if not items:
130 # empty list will cause empty query which might cause security issues
130 # empty list will cause empty query which might cause security issues
131 # this can lead to hidden unpleasant results
131 # this can lead to hidden unpleasant results
132 items = [-1]
132 items = [-1]
133
133
134 parts = []
134 parts = []
135 for chunk in xrange(0, len(items), limit):
135 for chunk in xrange(0, len(items), limit):
136 parts.append(
136 parts.append(
137 qry.in_(items[chunk: chunk + limit])
137 qry.in_(items[chunk: chunk + limit])
138 )
138 )
139
139
140 return parts
140 return parts
141
141
142
142
143 class EncryptedTextValue(TypeDecorator):
143 class EncryptedTextValue(TypeDecorator):
144 """
144 """
145 Special column for encrypted long text data, use like::
145 Special column for encrypted long text data, use like::
146
146
147 value = Column("encrypted_value", EncryptedValue(), nullable=False)
147 value = Column("encrypted_value", EncryptedValue(), nullable=False)
148
148
149 This column is intelligent so if value is in unencrypted form it return
149 This column is intelligent so if value is in unencrypted form it return
150 unencrypted form, but on save it always encrypts
150 unencrypted form, but on save it always encrypts
151 """
151 """
152 impl = Text
152 impl = Text
153
153
154 def process_bind_param(self, value, dialect):
154 def process_bind_param(self, value, dialect):
155 if not value:
155 if not value:
156 return value
156 return value
157 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
157 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
158 # protect against double encrypting if someone manually starts
158 # protect against double encrypting if someone manually starts
159 # doing
159 # doing
160 raise ValueError('value needs to be in unencrypted format, ie. '
160 raise ValueError('value needs to be in unencrypted format, ie. '
161 'not starting with enc$aes')
161 'not starting with enc$aes')
162 return 'enc$aes_hmac$%s' % AESCipher(
162 return 'enc$aes_hmac$%s' % AESCipher(
163 ENCRYPTION_KEY, hmac=True).encrypt(value)
163 ENCRYPTION_KEY, hmac=True).encrypt(value)
164
164
165 def process_result_value(self, value, dialect):
165 def process_result_value(self, value, dialect):
166 import rhodecode
166 import rhodecode
167
167
168 if not value:
168 if not value:
169 return value
169 return value
170
170
171 parts = value.split('$', 3)
171 parts = value.split('$', 3)
172 if not len(parts) == 3:
172 if not len(parts) == 3:
173 # probably not encrypted values
173 # probably not encrypted values
174 return value
174 return value
175 else:
175 else:
176 if parts[0] != 'enc':
176 if parts[0] != 'enc':
177 # parts ok but without our header ?
177 # parts ok but without our header ?
178 return value
178 return value
179 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
179 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
180 'rhodecode.encrypted_values.strict') or True)
180 'rhodecode.encrypted_values.strict') or True)
181 # at that stage we know it's our encryption
181 # at that stage we know it's our encryption
182 if parts[1] == 'aes':
182 if parts[1] == 'aes':
183 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
183 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
184 elif parts[1] == 'aes_hmac':
184 elif parts[1] == 'aes_hmac':
185 decrypted_data = AESCipher(
185 decrypted_data = AESCipher(
186 ENCRYPTION_KEY, hmac=True,
186 ENCRYPTION_KEY, hmac=True,
187 strict_verification=enc_strict_mode).decrypt(parts[2])
187 strict_verification=enc_strict_mode).decrypt(parts[2])
188 else:
188 else:
189 raise ValueError(
189 raise ValueError(
190 'Encryption type part is wrong, must be `aes` '
190 'Encryption type part is wrong, must be `aes` '
191 'or `aes_hmac`, got `%s` instead' % (parts[1]))
191 'or `aes_hmac`, got `%s` instead' % (parts[1]))
192 return decrypted_data
192 return decrypted_data
193
193
194
194
195 class BaseModel(object):
195 class BaseModel(object):
196 """
196 """
197 Base Model for all classes
197 Base Model for all classes
198 """
198 """
199
199
200 @classmethod
200 @classmethod
201 def _get_keys(cls):
201 def _get_keys(cls):
202 """return column names for this model """
202 """return column names for this model """
203 return class_mapper(cls).c.keys()
203 return class_mapper(cls).c.keys()
204
204
205 def get_dict(self):
205 def get_dict(self):
206 """
206 """
207 return dict with keys and values corresponding
207 return dict with keys and values corresponding
208 to this model data """
208 to this model data """
209
209
210 d = {}
210 d = {}
211 for k in self._get_keys():
211 for k in self._get_keys():
212 d[k] = getattr(self, k)
212 d[k] = getattr(self, k)
213
213
214 # also use __json__() if present to get additional fields
214 # also use __json__() if present to get additional fields
215 _json_attr = getattr(self, '__json__', None)
215 _json_attr = getattr(self, '__json__', None)
216 if _json_attr:
216 if _json_attr:
217 # update with attributes from __json__
217 # update with attributes from __json__
218 if callable(_json_attr):
218 if callable(_json_attr):
219 _json_attr = _json_attr()
219 _json_attr = _json_attr()
220 for k, val in _json_attr.iteritems():
220 for k, val in _json_attr.iteritems():
221 d[k] = val
221 d[k] = val
222 return d
222 return d
223
223
224 def get_appstruct(self):
224 def get_appstruct(self):
225 """return list with keys and values tuples corresponding
225 """return list with keys and values tuples corresponding
226 to this model data """
226 to this model data """
227
227
228 lst = []
228 lst = []
229 for k in self._get_keys():
229 for k in self._get_keys():
230 lst.append((k, getattr(self, k),))
230 lst.append((k, getattr(self, k),))
231 return lst
231 return lst
232
232
233 def populate_obj(self, populate_dict):
233 def populate_obj(self, populate_dict):
234 """populate model with data from given populate_dict"""
234 """populate model with data from given populate_dict"""
235
235
236 for k in self._get_keys():
236 for k in self._get_keys():
237 if k in populate_dict:
237 if k in populate_dict:
238 setattr(self, k, populate_dict[k])
238 setattr(self, k, populate_dict[k])
239
239
240 @classmethod
240 @classmethod
241 def query(cls):
241 def query(cls):
242 return Session().query(cls)
242 return Session().query(cls)
243
243
244 @classmethod
244 @classmethod
245 def get(cls, id_):
245 def get(cls, id_):
246 if id_:
246 if id_:
247 return cls.query().get(id_)
247 return cls.query().get(id_)
248
248
249 @classmethod
249 @classmethod
250 def get_or_404(cls, id_):
250 def get_or_404(cls, id_):
251 from pyramid.httpexceptions import HTTPNotFound
251 from pyramid.httpexceptions import HTTPNotFound
252
252
253 try:
253 try:
254 id_ = int(id_)
254 id_ = int(id_)
255 except (TypeError, ValueError):
255 except (TypeError, ValueError):
256 raise HTTPNotFound()
256 raise HTTPNotFound()
257
257
258 res = cls.query().get(id_)
258 res = cls.query().get(id_)
259 if not res:
259 if not res:
260 raise HTTPNotFound()
260 raise HTTPNotFound()
261 return res
261 return res
262
262
263 @classmethod
263 @classmethod
264 def getAll(cls):
264 def getAll(cls):
265 # deprecated and left for backward compatibility
265 # deprecated and left for backward compatibility
266 return cls.get_all()
266 return cls.get_all()
267
267
268 @classmethod
268 @classmethod
269 def get_all(cls):
269 def get_all(cls):
270 return cls.query().all()
270 return cls.query().all()
271
271
272 @classmethod
272 @classmethod
273 def delete(cls, id_):
273 def delete(cls, id_):
274 obj = cls.query().get(id_)
274 obj = cls.query().get(id_)
275 Session().delete(obj)
275 Session().delete(obj)
276
276
277 @classmethod
277 @classmethod
278 def identity_cache(cls, session, attr_name, value):
278 def identity_cache(cls, session, attr_name, value):
279 exist_in_session = []
279 exist_in_session = []
280 for (item_cls, pkey), instance in session.identity_map.items():
280 for (item_cls, pkey), instance in session.identity_map.items():
281 if cls == item_cls and getattr(instance, attr_name) == value:
281 if cls == item_cls and getattr(instance, attr_name) == value:
282 exist_in_session.append(instance)
282 exist_in_session.append(instance)
283 if exist_in_session:
283 if exist_in_session:
284 if len(exist_in_session) == 1:
284 if len(exist_in_session) == 1:
285 return exist_in_session[0]
285 return exist_in_session[0]
286 log.exception(
286 log.exception(
287 'multiple objects with attr %s and '
287 'multiple objects with attr %s and '
288 'value %s found with same name: %r',
288 'value %s found with same name: %r',
289 attr_name, value, exist_in_session)
289 attr_name, value, exist_in_session)
290
290
291 def __repr__(self):
291 def __repr__(self):
292 if hasattr(self, '__unicode__'):
292 if hasattr(self, '__unicode__'):
293 # python repr needs to return str
293 # python repr needs to return str
294 try:
294 try:
295 return safe_str(self.__unicode__())
295 return safe_str(self.__unicode__())
296 except UnicodeDecodeError:
296 except UnicodeDecodeError:
297 pass
297 pass
298 return '<DB:%s>' % (self.__class__.__name__)
298 return '<DB:%s>' % (self.__class__.__name__)
299
299
300
300
301 class RhodeCodeSetting(Base, BaseModel):
301 class RhodeCodeSetting(Base, BaseModel):
302 __tablename__ = 'rhodecode_settings'
302 __tablename__ = 'rhodecode_settings'
303 __table_args__ = (
303 __table_args__ = (
304 UniqueConstraint('app_settings_name'),
304 UniqueConstraint('app_settings_name'),
305 {'extend_existing': True, 'mysql_engine': 'InnoDB',
305 {'extend_existing': True, 'mysql_engine': 'InnoDB',
306 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
306 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
307 )
307 )
308
308
309 SETTINGS_TYPES = {
309 SETTINGS_TYPES = {
310 'str': safe_str,
310 'str': safe_str,
311 'int': safe_int,
311 'int': safe_int,
312 'unicode': safe_unicode,
312 'unicode': safe_unicode,
313 'bool': str2bool,
313 'bool': str2bool,
314 'list': functools.partial(aslist, sep=',')
314 'list': functools.partial(aslist, sep=',')
315 }
315 }
316 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
316 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
317 GLOBAL_CONF_KEY = 'app_settings'
317 GLOBAL_CONF_KEY = 'app_settings'
318
318
319 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
319 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
320 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
320 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
321 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
321 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
322 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
322 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
323
323
324 def __init__(self, key='', val='', type='unicode'):
324 def __init__(self, key='', val='', type='unicode'):
325 self.app_settings_name = key
325 self.app_settings_name = key
326 self.app_settings_type = type
326 self.app_settings_type = type
327 self.app_settings_value = val
327 self.app_settings_value = val
328
328
329 @validates('_app_settings_value')
329 @validates('_app_settings_value')
330 def validate_settings_value(self, key, val):
330 def validate_settings_value(self, key, val):
331 assert type(val) == unicode
331 assert type(val) == unicode
332 return val
332 return val
333
333
334 @hybrid_property
334 @hybrid_property
335 def app_settings_value(self):
335 def app_settings_value(self):
336 v = self._app_settings_value
336 v = self._app_settings_value
337 _type = self.app_settings_type
337 _type = self.app_settings_type
338 if _type:
338 if _type:
339 _type = self.app_settings_type.split('.')[0]
339 _type = self.app_settings_type.split('.')[0]
340 # decode the encrypted value
340 # decode the encrypted value
341 if 'encrypted' in self.app_settings_type:
341 if 'encrypted' in self.app_settings_type:
342 cipher = EncryptedTextValue()
342 cipher = EncryptedTextValue()
343 v = safe_unicode(cipher.process_result_value(v, None))
343 v = safe_unicode(cipher.process_result_value(v, None))
344
344
345 converter = self.SETTINGS_TYPES.get(_type) or \
345 converter = self.SETTINGS_TYPES.get(_type) or \
346 self.SETTINGS_TYPES['unicode']
346 self.SETTINGS_TYPES['unicode']
347 return converter(v)
347 return converter(v)
348
348
349 @app_settings_value.setter
349 @app_settings_value.setter
350 def app_settings_value(self, val):
350 def app_settings_value(self, val):
351 """
351 """
352 Setter that will always make sure we use unicode in app_settings_value
352 Setter that will always make sure we use unicode in app_settings_value
353
353
354 :param val:
354 :param val:
355 """
355 """
356 val = safe_unicode(val)
356 val = safe_unicode(val)
357 # encode the encrypted value
357 # encode the encrypted value
358 if 'encrypted' in self.app_settings_type:
358 if 'encrypted' in self.app_settings_type:
359 cipher = EncryptedTextValue()
359 cipher = EncryptedTextValue()
360 val = safe_unicode(cipher.process_bind_param(val, None))
360 val = safe_unicode(cipher.process_bind_param(val, None))
361 self._app_settings_value = val
361 self._app_settings_value = val
362
362
363 @hybrid_property
363 @hybrid_property
364 def app_settings_type(self):
364 def app_settings_type(self):
365 return self._app_settings_type
365 return self._app_settings_type
366
366
367 @app_settings_type.setter
367 @app_settings_type.setter
368 def app_settings_type(self, val):
368 def app_settings_type(self, val):
369 if val.split('.')[0] not in self.SETTINGS_TYPES:
369 if val.split('.')[0] not in self.SETTINGS_TYPES:
370 raise Exception('type must be one of %s got %s'
370 raise Exception('type must be one of %s got %s'
371 % (self.SETTINGS_TYPES.keys(), val))
371 % (self.SETTINGS_TYPES.keys(), val))
372 self._app_settings_type = val
372 self._app_settings_type = val
373
373
374 def __unicode__(self):
374 def __unicode__(self):
375 return u"<%s('%s:%s[%s]')>" % (
375 return u"<%s('%s:%s[%s]')>" % (
376 self.__class__.__name__,
376 self.__class__.__name__,
377 self.app_settings_name, self.app_settings_value,
377 self.app_settings_name, self.app_settings_value,
378 self.app_settings_type
378 self.app_settings_type
379 )
379 )
380
380
381
381
382 class RhodeCodeUi(Base, BaseModel):
382 class RhodeCodeUi(Base, BaseModel):
383 __tablename__ = 'rhodecode_ui'
383 __tablename__ = 'rhodecode_ui'
384 __table_args__ = (
384 __table_args__ = (
385 UniqueConstraint('ui_key'),
385 UniqueConstraint('ui_key'),
386 {'extend_existing': True, 'mysql_engine': 'InnoDB',
386 {'extend_existing': True, 'mysql_engine': 'InnoDB',
387 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
387 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
388 )
388 )
389
389
390 HOOK_REPO_SIZE = 'changegroup.repo_size'
390 HOOK_REPO_SIZE = 'changegroup.repo_size'
391 # HG
391 # HG
392 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
392 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
393 HOOK_PULL = 'outgoing.pull_logger'
393 HOOK_PULL = 'outgoing.pull_logger'
394 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
394 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
395 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
395 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
396 HOOK_PUSH = 'changegroup.push_logger'
396 HOOK_PUSH = 'changegroup.push_logger'
397 HOOK_PUSH_KEY = 'pushkey.key_push'
397 HOOK_PUSH_KEY = 'pushkey.key_push'
398
398
399 # TODO: johbo: Unify way how hooks are configured for git and hg,
399 # TODO: johbo: Unify way how hooks are configured for git and hg,
400 # git part is currently hardcoded.
400 # git part is currently hardcoded.
401
401
402 # SVN PATTERNS
402 # SVN PATTERNS
403 SVN_BRANCH_ID = 'vcs_svn_branch'
403 SVN_BRANCH_ID = 'vcs_svn_branch'
404 SVN_TAG_ID = 'vcs_svn_tag'
404 SVN_TAG_ID = 'vcs_svn_tag'
405
405
406 ui_id = Column(
406 ui_id = Column(
407 "ui_id", Integer(), nullable=False, unique=True, default=None,
407 "ui_id", Integer(), nullable=False, unique=True, default=None,
408 primary_key=True)
408 primary_key=True)
409 ui_section = Column(
409 ui_section = Column(
410 "ui_section", String(255), nullable=True, unique=None, default=None)
410 "ui_section", String(255), nullable=True, unique=None, default=None)
411 ui_key = Column(
411 ui_key = Column(
412 "ui_key", String(255), nullable=True, unique=None, default=None)
412 "ui_key", String(255), nullable=True, unique=None, default=None)
413 ui_value = Column(
413 ui_value = Column(
414 "ui_value", String(255), nullable=True, unique=None, default=None)
414 "ui_value", String(255), nullable=True, unique=None, default=None)
415 ui_active = Column(
415 ui_active = Column(
416 "ui_active", Boolean(), nullable=True, unique=None, default=True)
416 "ui_active", Boolean(), nullable=True, unique=None, default=True)
417
417
418 def __repr__(self):
418 def __repr__(self):
419 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
419 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
420 self.ui_key, self.ui_value)
420 self.ui_key, self.ui_value)
421
421
422
422
423 class RepoRhodeCodeSetting(Base, BaseModel):
423 class RepoRhodeCodeSetting(Base, BaseModel):
424 __tablename__ = 'repo_rhodecode_settings'
424 __tablename__ = 'repo_rhodecode_settings'
425 __table_args__ = (
425 __table_args__ = (
426 UniqueConstraint(
426 UniqueConstraint(
427 'app_settings_name', 'repository_id',
427 'app_settings_name', 'repository_id',
428 name='uq_repo_rhodecode_setting_name_repo_id'),
428 name='uq_repo_rhodecode_setting_name_repo_id'),
429 {'extend_existing': True, 'mysql_engine': 'InnoDB',
429 {'extend_existing': True, 'mysql_engine': 'InnoDB',
430 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
430 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
431 )
431 )
432
432
433 repository_id = Column(
433 repository_id = Column(
434 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
434 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
435 nullable=False)
435 nullable=False)
436 app_settings_id = Column(
436 app_settings_id = Column(
437 "app_settings_id", Integer(), nullable=False, unique=True,
437 "app_settings_id", Integer(), nullable=False, unique=True,
438 default=None, primary_key=True)
438 default=None, primary_key=True)
439 app_settings_name = Column(
439 app_settings_name = Column(
440 "app_settings_name", String(255), nullable=True, unique=None,
440 "app_settings_name", String(255), nullable=True, unique=None,
441 default=None)
441 default=None)
442 _app_settings_value = Column(
442 _app_settings_value = Column(
443 "app_settings_value", String(4096), nullable=True, unique=None,
443 "app_settings_value", String(4096), nullable=True, unique=None,
444 default=None)
444 default=None)
445 _app_settings_type = Column(
445 _app_settings_type = Column(
446 "app_settings_type", String(255), nullable=True, unique=None,
446 "app_settings_type", String(255), nullable=True, unique=None,
447 default=None)
447 default=None)
448
448
449 repository = relationship('Repository')
449 repository = relationship('Repository')
450
450
451 def __init__(self, repository_id, key='', val='', type='unicode'):
451 def __init__(self, repository_id, key='', val='', type='unicode'):
452 self.repository_id = repository_id
452 self.repository_id = repository_id
453 self.app_settings_name = key
453 self.app_settings_name = key
454 self.app_settings_type = type
454 self.app_settings_type = type
455 self.app_settings_value = val
455 self.app_settings_value = val
456
456
457 @validates('_app_settings_value')
457 @validates('_app_settings_value')
458 def validate_settings_value(self, key, val):
458 def validate_settings_value(self, key, val):
459 assert type(val) == unicode
459 assert type(val) == unicode
460 return val
460 return val
461
461
462 @hybrid_property
462 @hybrid_property
463 def app_settings_value(self):
463 def app_settings_value(self):
464 v = self._app_settings_value
464 v = self._app_settings_value
465 type_ = self.app_settings_type
465 type_ = self.app_settings_type
466 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
466 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
467 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
467 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
468 return converter(v)
468 return converter(v)
469
469
470 @app_settings_value.setter
470 @app_settings_value.setter
471 def app_settings_value(self, val):
471 def app_settings_value(self, val):
472 """
472 """
473 Setter that will always make sure we use unicode in app_settings_value
473 Setter that will always make sure we use unicode in app_settings_value
474
474
475 :param val:
475 :param val:
476 """
476 """
477 self._app_settings_value = safe_unicode(val)
477 self._app_settings_value = safe_unicode(val)
478
478
479 @hybrid_property
479 @hybrid_property
480 def app_settings_type(self):
480 def app_settings_type(self):
481 return self._app_settings_type
481 return self._app_settings_type
482
482
483 @app_settings_type.setter
483 @app_settings_type.setter
484 def app_settings_type(self, val):
484 def app_settings_type(self, val):
485 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
485 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
486 if val not in SETTINGS_TYPES:
486 if val not in SETTINGS_TYPES:
487 raise Exception('type must be one of %s got %s'
487 raise Exception('type must be one of %s got %s'
488 % (SETTINGS_TYPES.keys(), val))
488 % (SETTINGS_TYPES.keys(), val))
489 self._app_settings_type = val
489 self._app_settings_type = val
490
490
491 def __unicode__(self):
491 def __unicode__(self):
492 return u"<%s('%s:%s:%s[%s]')>" % (
492 return u"<%s('%s:%s:%s[%s]')>" % (
493 self.__class__.__name__, self.repository.repo_name,
493 self.__class__.__name__, self.repository.repo_name,
494 self.app_settings_name, self.app_settings_value,
494 self.app_settings_name, self.app_settings_value,
495 self.app_settings_type
495 self.app_settings_type
496 )
496 )
497
497
498
498
499 class RepoRhodeCodeUi(Base, BaseModel):
499 class RepoRhodeCodeUi(Base, BaseModel):
500 __tablename__ = 'repo_rhodecode_ui'
500 __tablename__ = 'repo_rhodecode_ui'
501 __table_args__ = (
501 __table_args__ = (
502 UniqueConstraint(
502 UniqueConstraint(
503 'repository_id', 'ui_section', 'ui_key',
503 'repository_id', 'ui_section', 'ui_key',
504 name='uq_repo_rhodecode_ui_repository_id_section_key'),
504 name='uq_repo_rhodecode_ui_repository_id_section_key'),
505 {'extend_existing': True, 'mysql_engine': 'InnoDB',
505 {'extend_existing': True, 'mysql_engine': 'InnoDB',
506 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
506 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
507 )
507 )
508
508
509 repository_id = Column(
509 repository_id = Column(
510 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
510 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
511 nullable=False)
511 nullable=False)
512 ui_id = Column(
512 ui_id = Column(
513 "ui_id", Integer(), nullable=False, unique=True, default=None,
513 "ui_id", Integer(), nullable=False, unique=True, default=None,
514 primary_key=True)
514 primary_key=True)
515 ui_section = Column(
515 ui_section = Column(
516 "ui_section", String(255), nullable=True, unique=None, default=None)
516 "ui_section", String(255), nullable=True, unique=None, default=None)
517 ui_key = Column(
517 ui_key = Column(
518 "ui_key", String(255), nullable=True, unique=None, default=None)
518 "ui_key", String(255), nullable=True, unique=None, default=None)
519 ui_value = Column(
519 ui_value = Column(
520 "ui_value", String(255), nullable=True, unique=None, default=None)
520 "ui_value", String(255), nullable=True, unique=None, default=None)
521 ui_active = Column(
521 ui_active = Column(
522 "ui_active", Boolean(), nullable=True, unique=None, default=True)
522 "ui_active", Boolean(), nullable=True, unique=None, default=True)
523
523
524 repository = relationship('Repository')
524 repository = relationship('Repository')
525
525
526 def __repr__(self):
526 def __repr__(self):
527 return '<%s[%s:%s]%s=>%s]>' % (
527 return '<%s[%s:%s]%s=>%s]>' % (
528 self.__class__.__name__, self.repository.repo_name,
528 self.__class__.__name__, self.repository.repo_name,
529 self.ui_section, self.ui_key, self.ui_value)
529 self.ui_section, self.ui_key, self.ui_value)
530
530
531
531
532 class User(Base, BaseModel):
532 class User(Base, BaseModel):
533 __tablename__ = 'users'
533 __tablename__ = 'users'
534 __table_args__ = (
534 __table_args__ = (
535 UniqueConstraint('username'), UniqueConstraint('email'),
535 UniqueConstraint('username'), UniqueConstraint('email'),
536 Index('u_username_idx', 'username'),
536 Index('u_username_idx', 'username'),
537 Index('u_email_idx', 'email'),
537 Index('u_email_idx', 'email'),
538 {'extend_existing': True, 'mysql_engine': 'InnoDB',
538 {'extend_existing': True, 'mysql_engine': 'InnoDB',
539 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
539 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
540 )
540 )
541 DEFAULT_USER = 'default'
541 DEFAULT_USER = 'default'
542 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
542 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
543 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
543 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
544
544
545 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
545 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
546 username = Column("username", String(255), nullable=True, unique=None, default=None)
546 username = Column("username", String(255), nullable=True, unique=None, default=None)
547 password = Column("password", String(255), nullable=True, unique=None, default=None)
547 password = Column("password", String(255), nullable=True, unique=None, default=None)
548 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
548 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
549 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
549 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
550 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
550 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
551 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
551 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
552 _email = Column("email", String(255), nullable=True, unique=None, default=None)
552 _email = Column("email", String(255), nullable=True, unique=None, default=None)
553 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
553 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
554 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
554 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
555
555
556 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
556 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
557 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
557 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
558 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
558 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
559 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
559 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
560 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
560 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
561 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
561 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
562
562
563 user_log = relationship('UserLog')
563 user_log = relationship('UserLog')
564 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
564 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
565
565
566 repositories = relationship('Repository')
566 repositories = relationship('Repository')
567 repository_groups = relationship('RepoGroup')
567 repository_groups = relationship('RepoGroup')
568 user_groups = relationship('UserGroup')
568 user_groups = relationship('UserGroup')
569
569
570 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
570 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
571 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
571 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
572
572
573 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
573 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
574 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
574 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
575 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
575 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
576
576
577 group_member = relationship('UserGroupMember', cascade='all')
577 group_member = relationship('UserGroupMember', cascade='all')
578
578
579 notifications = relationship('UserNotification', cascade='all')
579 notifications = relationship('UserNotification', cascade='all')
580 # notifications assigned to this user
580 # notifications assigned to this user
581 user_created_notifications = relationship('Notification', cascade='all')
581 user_created_notifications = relationship('Notification', cascade='all')
582 # comments created by this user
582 # comments created by this user
583 user_comments = relationship('ChangesetComment', cascade='all')
583 user_comments = relationship('ChangesetComment', cascade='all')
584 # user profile extra info
584 # user profile extra info
585 user_emails = relationship('UserEmailMap', cascade='all')
585 user_emails = relationship('UserEmailMap', cascade='all')
586 user_ip_map = relationship('UserIpMap', cascade='all')
586 user_ip_map = relationship('UserIpMap', cascade='all')
587 user_auth_tokens = relationship('UserApiKeys', cascade='all')
587 user_auth_tokens = relationship('UserApiKeys', cascade='all')
588 user_ssh_keys = relationship('UserSshKeys', cascade='all')
588 user_ssh_keys = relationship('UserSshKeys', cascade='all')
589
589
590 # gists
590 # gists
591 user_gists = relationship('Gist', cascade='all')
591 user_gists = relationship('Gist', cascade='all')
592 # user pull requests
592 # user pull requests
593 user_pull_requests = relationship('PullRequest', cascade='all')
593 user_pull_requests = relationship('PullRequest', cascade='all')
594 # external identities
594 # external identities
595 extenal_identities = relationship(
595 extenal_identities = relationship(
596 'ExternalIdentity',
596 'ExternalIdentity',
597 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
597 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
598 cascade='all')
598 cascade='all')
599 # review rules
599 # review rules
600 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
600 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
601
601
602 def __unicode__(self):
602 def __unicode__(self):
603 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
603 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
604 self.user_id, self.username)
604 self.user_id, self.username)
605
605
606 @hybrid_property
606 @hybrid_property
607 def email(self):
607 def email(self):
608 return self._email
608 return self._email
609
609
610 @email.setter
610 @email.setter
611 def email(self, val):
611 def email(self, val):
612 self._email = val.lower() if val else None
612 self._email = val.lower() if val else None
613
613
614 @hybrid_property
614 @hybrid_property
615 def first_name(self):
615 def first_name(self):
616 from rhodecode.lib import helpers as h
616 from rhodecode.lib import helpers as h
617 if self.name:
617 if self.name:
618 return h.escape(self.name)
618 return h.escape(self.name)
619 return self.name
619 return self.name
620
620
621 @hybrid_property
621 @hybrid_property
622 def last_name(self):
622 def last_name(self):
623 from rhodecode.lib import helpers as h
623 from rhodecode.lib import helpers as h
624 if self.lastname:
624 if self.lastname:
625 return h.escape(self.lastname)
625 return h.escape(self.lastname)
626 return self.lastname
626 return self.lastname
627
627
628 @hybrid_property
628 @hybrid_property
629 def api_key(self):
629 def api_key(self):
630 """
630 """
631 Fetch if exist an auth-token with role ALL connected to this user
631 Fetch if exist an auth-token with role ALL connected to this user
632 """
632 """
633 user_auth_token = UserApiKeys.query()\
633 user_auth_token = UserApiKeys.query()\
634 .filter(UserApiKeys.user_id == self.user_id)\
634 .filter(UserApiKeys.user_id == self.user_id)\
635 .filter(or_(UserApiKeys.expires == -1,
635 .filter(or_(UserApiKeys.expires == -1,
636 UserApiKeys.expires >= time.time()))\
636 UserApiKeys.expires >= time.time()))\
637 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
637 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
638 if user_auth_token:
638 if user_auth_token:
639 user_auth_token = user_auth_token.api_key
639 user_auth_token = user_auth_token.api_key
640
640
641 return user_auth_token
641 return user_auth_token
642
642
643 @api_key.setter
643 @api_key.setter
644 def api_key(self, val):
644 def api_key(self, val):
645 # don't allow to set API key this is deprecated for now
645 # don't allow to set API key this is deprecated for now
646 self._api_key = None
646 self._api_key = None
647
647
648 @property
648 @property
649 def reviewer_pull_requests(self):
649 def reviewer_pull_requests(self):
650 return PullRequestReviewers.query() \
650 return PullRequestReviewers.query() \
651 .options(joinedload(PullRequestReviewers.pull_request)) \
651 .options(joinedload(PullRequestReviewers.pull_request)) \
652 .filter(PullRequestReviewers.user_id == self.user_id) \
652 .filter(PullRequestReviewers.user_id == self.user_id) \
653 .all()
653 .all()
654
654
655 @property
655 @property
656 def firstname(self):
656 def firstname(self):
657 # alias for future
657 # alias for future
658 return self.name
658 return self.name
659
659
660 @property
660 @property
661 def emails(self):
661 def emails(self):
662 other = UserEmailMap.query()\
662 other = UserEmailMap.query()\
663 .filter(UserEmailMap.user == self) \
663 .filter(UserEmailMap.user == self) \
664 .order_by(UserEmailMap.email_id.asc()) \
664 .order_by(UserEmailMap.email_id.asc()) \
665 .all()
665 .all()
666 return [self.email] + [x.email for x in other]
666 return [self.email] + [x.email for x in other]
667
667
668 @property
668 @property
669 def auth_tokens(self):
669 def auth_tokens(self):
670 auth_tokens = self.get_auth_tokens()
670 auth_tokens = self.get_auth_tokens()
671 return [x.api_key for x in auth_tokens]
671 return [x.api_key for x in auth_tokens]
672
672
673 def get_auth_tokens(self):
673 def get_auth_tokens(self):
674 return UserApiKeys.query()\
674 return UserApiKeys.query()\
675 .filter(UserApiKeys.user == self)\
675 .filter(UserApiKeys.user == self)\
676 .order_by(UserApiKeys.user_api_key_id.asc())\
676 .order_by(UserApiKeys.user_api_key_id.asc())\
677 .all()
677 .all()
678
678
679 @LazyProperty
679 @LazyProperty
680 def feed_token(self):
680 def feed_token(self):
681 return self.get_feed_token()
681 return self.get_feed_token()
682
682
683 def get_feed_token(self, cache=True):
683 def get_feed_token(self, cache=True):
684 feed_tokens = UserApiKeys.query()\
684 feed_tokens = UserApiKeys.query()\
685 .filter(UserApiKeys.user == self)\
685 .filter(UserApiKeys.user == self)\
686 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
686 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
687 if cache:
687 if cache:
688 feed_tokens = feed_tokens.options(
688 feed_tokens = feed_tokens.options(
689 FromCache("long_term", "get_user_feed_token_%s" % self.user_id))
689 FromCache("long_term", "get_user_feed_token_%s" % self.user_id))
690
690
691 feed_tokens = feed_tokens.all()
691 feed_tokens = feed_tokens.all()
692 if feed_tokens:
692 if feed_tokens:
693 return feed_tokens[0].api_key
693 return feed_tokens[0].api_key
694 return 'NO_FEED_TOKEN_AVAILABLE'
694 return 'NO_FEED_TOKEN_AVAILABLE'
695
695
696 @classmethod
696 @classmethod
697 def get(cls, user_id, cache=False):
697 def get(cls, user_id, cache=False):
698 if not user_id:
698 if not user_id:
699 return
699 return
700
700
701 user = cls.query()
701 user = cls.query()
702 if cache:
702 if cache:
703 user = user.options(
703 user = user.options(
704 FromCache("sql_cache_short", "get_users_%s" % user_id))
704 FromCache("sql_cache_short", "get_users_%s" % user_id))
705 return user.get(user_id)
705 return user.get(user_id)
706
706
707 @classmethod
707 @classmethod
708 def extra_valid_auth_tokens(cls, user, role=None):
708 def extra_valid_auth_tokens(cls, user, role=None):
709 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
709 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
710 .filter(or_(UserApiKeys.expires == -1,
710 .filter(or_(UserApiKeys.expires == -1,
711 UserApiKeys.expires >= time.time()))
711 UserApiKeys.expires >= time.time()))
712 if role:
712 if role:
713 tokens = tokens.filter(or_(UserApiKeys.role == role,
713 tokens = tokens.filter(or_(UserApiKeys.role == role,
714 UserApiKeys.role == UserApiKeys.ROLE_ALL))
714 UserApiKeys.role == UserApiKeys.ROLE_ALL))
715 return tokens.all()
715 return tokens.all()
716
716
717 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
717 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
718 from rhodecode.lib import auth
718 from rhodecode.lib import auth
719
719
720 log.debug('Trying to authenticate user: %s via auth-token, '
720 log.debug('Trying to authenticate user: %s via auth-token, '
721 'and roles: %s', self, roles)
721 'and roles: %s', self, roles)
722
722
723 if not auth_token:
723 if not auth_token:
724 return False
724 return False
725
725
726 crypto_backend = auth.crypto_backend()
726 crypto_backend = auth.crypto_backend()
727
727
728 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
728 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
729 tokens_q = UserApiKeys.query()\
729 tokens_q = UserApiKeys.query()\
730 .filter(UserApiKeys.user_id == self.user_id)\
730 .filter(UserApiKeys.user_id == self.user_id)\
731 .filter(or_(UserApiKeys.expires == -1,
731 .filter(or_(UserApiKeys.expires == -1,
732 UserApiKeys.expires >= time.time()))
732 UserApiKeys.expires >= time.time()))
733
733
734 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
734 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
735
735
736 plain_tokens = []
736 plain_tokens = []
737 hash_tokens = []
737 hash_tokens = []
738
738
739 for token in tokens_q.all():
739 for token in tokens_q.all():
740 # verify scope first
740 # verify scope first
741 if token.repo_id:
741 if token.repo_id:
742 # token has a scope, we need to verify it
742 # token has a scope, we need to verify it
743 if scope_repo_id != token.repo_id:
743 if scope_repo_id != token.repo_id:
744 log.debug(
744 log.debug(
745 'Scope mismatch: token has a set repo scope: %s, '
745 'Scope mismatch: token has a set repo scope: %s, '
746 'and calling scope is:%s, skipping further checks',
746 'and calling scope is:%s, skipping further checks',
747 token.repo, scope_repo_id)
747 token.repo, scope_repo_id)
748 # token has a scope, and it doesn't match, skip token
748 # token has a scope, and it doesn't match, skip token
749 continue
749 continue
750
750
751 if token.api_key.startswith(crypto_backend.ENC_PREF):
751 if token.api_key.startswith(crypto_backend.ENC_PREF):
752 hash_tokens.append(token.api_key)
752 hash_tokens.append(token.api_key)
753 else:
753 else:
754 plain_tokens.append(token.api_key)
754 plain_tokens.append(token.api_key)
755
755
756 is_plain_match = auth_token in plain_tokens
756 is_plain_match = auth_token in plain_tokens
757 if is_plain_match:
757 if is_plain_match:
758 return True
758 return True
759
759
760 for hashed in hash_tokens:
760 for hashed in hash_tokens:
761 # TODO(marcink): this is expensive to calculate, but most secure
761 # TODO(marcink): this is expensive to calculate, but most secure
762 match = crypto_backend.hash_check(auth_token, hashed)
762 match = crypto_backend.hash_check(auth_token, hashed)
763 if match:
763 if match:
764 return True
764 return True
765
765
766 return False
766 return False
767
767
768 @property
768 @property
769 def ip_addresses(self):
769 def ip_addresses(self):
770 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
770 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
771 return [x.ip_addr for x in ret]
771 return [x.ip_addr for x in ret]
772
772
773 @property
773 @property
774 def username_and_name(self):
774 def username_and_name(self):
775 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
775 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
776
776
777 @property
777 @property
778 def username_or_name_or_email(self):
778 def username_or_name_or_email(self):
779 full_name = self.full_name if self.full_name is not ' ' else None
779 full_name = self.full_name if self.full_name is not ' ' else None
780 return self.username or full_name or self.email
780 return self.username or full_name or self.email
781
781
782 @property
782 @property
783 def full_name(self):
783 def full_name(self):
784 return '%s %s' % (self.first_name, self.last_name)
784 return '%s %s' % (self.first_name, self.last_name)
785
785
786 @property
786 @property
787 def full_name_or_username(self):
787 def full_name_or_username(self):
788 return ('%s %s' % (self.first_name, self.last_name)
788 return ('%s %s' % (self.first_name, self.last_name)
789 if (self.first_name and self.last_name) else self.username)
789 if (self.first_name and self.last_name) else self.username)
790
790
791 @property
791 @property
792 def full_contact(self):
792 def full_contact(self):
793 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
793 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
794
794
795 @property
795 @property
796 def short_contact(self):
796 def short_contact(self):
797 return '%s %s' % (self.first_name, self.last_name)
797 return '%s %s' % (self.first_name, self.last_name)
798
798
799 @property
799 @property
800 def is_admin(self):
800 def is_admin(self):
801 return self.admin
801 return self.admin
802
802
803 def AuthUser(self, **kwargs):
803 def AuthUser(self, **kwargs):
804 """
804 """
805 Returns instance of AuthUser for this user
805 Returns instance of AuthUser for this user
806 """
806 """
807 from rhodecode.lib.auth import AuthUser
807 from rhodecode.lib.auth import AuthUser
808 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
808 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
809
809
810 @hybrid_property
810 @hybrid_property
811 def user_data(self):
811 def user_data(self):
812 if not self._user_data:
812 if not self._user_data:
813 return {}
813 return {}
814
814
815 try:
815 try:
816 return json.loads(self._user_data)
816 return json.loads(self._user_data)
817 except TypeError:
817 except TypeError:
818 return {}
818 return {}
819
819
820 @user_data.setter
820 @user_data.setter
821 def user_data(self, val):
821 def user_data(self, val):
822 if not isinstance(val, dict):
822 if not isinstance(val, dict):
823 raise Exception('user_data must be dict, got %s' % type(val))
823 raise Exception('user_data must be dict, got %s' % type(val))
824 try:
824 try:
825 self._user_data = json.dumps(val)
825 self._user_data = json.dumps(val)
826 except Exception:
826 except Exception:
827 log.error(traceback.format_exc())
827 log.error(traceback.format_exc())
828
828
829 @classmethod
829 @classmethod
830 def get_by_username(cls, username, case_insensitive=False,
830 def get_by_username(cls, username, case_insensitive=False,
831 cache=False, identity_cache=False):
831 cache=False, identity_cache=False):
832 session = Session()
832 session = Session()
833
833
834 if case_insensitive:
834 if case_insensitive:
835 q = cls.query().filter(
835 q = cls.query().filter(
836 func.lower(cls.username) == func.lower(username))
836 func.lower(cls.username) == func.lower(username))
837 else:
837 else:
838 q = cls.query().filter(cls.username == username)
838 q = cls.query().filter(cls.username == username)
839
839
840 if cache:
840 if cache:
841 if identity_cache:
841 if identity_cache:
842 val = cls.identity_cache(session, 'username', username)
842 val = cls.identity_cache(session, 'username', username)
843 if val:
843 if val:
844 return val
844 return val
845 else:
845 else:
846 cache_key = "get_user_by_name_%s" % _hash_key(username)
846 cache_key = "get_user_by_name_%s" % _hash_key(username)
847 q = q.options(
847 q = q.options(
848 FromCache("sql_cache_short", cache_key))
848 FromCache("sql_cache_short", cache_key))
849
849
850 return q.scalar()
850 return q.scalar()
851
851
852 @classmethod
852 @classmethod
853 def get_by_auth_token(cls, auth_token, cache=False):
853 def get_by_auth_token(cls, auth_token, cache=False):
854 q = UserApiKeys.query()\
854 q = UserApiKeys.query()\
855 .filter(UserApiKeys.api_key == auth_token)\
855 .filter(UserApiKeys.api_key == auth_token)\
856 .filter(or_(UserApiKeys.expires == -1,
856 .filter(or_(UserApiKeys.expires == -1,
857 UserApiKeys.expires >= time.time()))
857 UserApiKeys.expires >= time.time()))
858 if cache:
858 if cache:
859 q = q.options(
859 q = q.options(
860 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
860 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
861
861
862 match = q.first()
862 match = q.first()
863 if match:
863 if match:
864 return match.user
864 return match.user
865
865
866 @classmethod
866 @classmethod
867 def get_by_email(cls, email, case_insensitive=False, cache=False):
867 def get_by_email(cls, email, case_insensitive=False, cache=False):
868
868
869 if case_insensitive:
869 if case_insensitive:
870 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
870 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
871
871
872 else:
872 else:
873 q = cls.query().filter(cls.email == email)
873 q = cls.query().filter(cls.email == email)
874
874
875 email_key = _hash_key(email)
875 email_key = _hash_key(email)
876 if cache:
876 if cache:
877 q = q.options(
877 q = q.options(
878 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
878 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
879
879
880 ret = q.scalar()
880 ret = q.scalar()
881 if ret is None:
881 if ret is None:
882 q = UserEmailMap.query()
882 q = UserEmailMap.query()
883 # try fetching in alternate email map
883 # try fetching in alternate email map
884 if case_insensitive:
884 if case_insensitive:
885 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
885 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
886 else:
886 else:
887 q = q.filter(UserEmailMap.email == email)
887 q = q.filter(UserEmailMap.email == email)
888 q = q.options(joinedload(UserEmailMap.user))
888 q = q.options(joinedload(UserEmailMap.user))
889 if cache:
889 if cache:
890 q = q.options(
890 q = q.options(
891 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
891 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
892 ret = getattr(q.scalar(), 'user', None)
892 ret = getattr(q.scalar(), 'user', None)
893
893
894 return ret
894 return ret
895
895
896 @classmethod
896 @classmethod
897 def get_from_cs_author(cls, author):
897 def get_from_cs_author(cls, author):
898 """
898 """
899 Tries to get User objects out of commit author string
899 Tries to get User objects out of commit author string
900
900
901 :param author:
901 :param author:
902 """
902 """
903 from rhodecode.lib.helpers import email, author_name
903 from rhodecode.lib.helpers import email, author_name
904 # Valid email in the attribute passed, see if they're in the system
904 # Valid email in the attribute passed, see if they're in the system
905 _email = email(author)
905 _email = email(author)
906 if _email:
906 if _email:
907 user = cls.get_by_email(_email, case_insensitive=True)
907 user = cls.get_by_email(_email, case_insensitive=True)
908 if user:
908 if user:
909 return user
909 return user
910 # Maybe we can match by username?
910 # Maybe we can match by username?
911 _author = author_name(author)
911 _author = author_name(author)
912 user = cls.get_by_username(_author, case_insensitive=True)
912 user = cls.get_by_username(_author, case_insensitive=True)
913 if user:
913 if user:
914 return user
914 return user
915
915
916 def update_userdata(self, **kwargs):
916 def update_userdata(self, **kwargs):
917 usr = self
917 usr = self
918 old = usr.user_data
918 old = usr.user_data
919 old.update(**kwargs)
919 old.update(**kwargs)
920 usr.user_data = old
920 usr.user_data = old
921 Session().add(usr)
921 Session().add(usr)
922 log.debug('updated userdata with ', kwargs)
922 log.debug('updated userdata with ', kwargs)
923
923
924 def update_lastlogin(self):
924 def update_lastlogin(self):
925 """Update user lastlogin"""
925 """Update user lastlogin"""
926 self.last_login = datetime.datetime.now()
926 self.last_login = datetime.datetime.now()
927 Session().add(self)
927 Session().add(self)
928 log.debug('updated user %s lastlogin', self.username)
928 log.debug('updated user %s lastlogin', self.username)
929
929
930 def update_lastactivity(self):
930 def update_lastactivity(self):
931 """Update user lastactivity"""
931 """Update user lastactivity"""
932 self.last_activity = datetime.datetime.now()
932 self.last_activity = datetime.datetime.now()
933 Session().add(self)
933 Session().add(self)
934 log.debug('updated user `%s` last activity', self.username)
934 log.debug('updated user `%s` last activity', self.username)
935
935
936 def update_password(self, new_password):
936 def update_password(self, new_password):
937 from rhodecode.lib.auth import get_crypt_password
937 from rhodecode.lib.auth import get_crypt_password
938
938
939 self.password = get_crypt_password(new_password)
939 self.password = get_crypt_password(new_password)
940 Session().add(self)
940 Session().add(self)
941
941
942 @classmethod
942 @classmethod
943 def get_first_super_admin(cls):
943 def get_first_super_admin(cls):
944 user = User.query().filter(User.admin == true()).first()
944 user = User.query().filter(User.admin == true()).first()
945 if user is None:
945 if user is None:
946 raise Exception('FATAL: Missing administrative account!')
946 raise Exception('FATAL: Missing administrative account!')
947 return user
947 return user
948
948
949 @classmethod
949 @classmethod
950 def get_all_super_admins(cls):
950 def get_all_super_admins(cls):
951 """
951 """
952 Returns all admin accounts sorted by username
952 Returns all admin accounts sorted by username
953 """
953 """
954 return User.query().filter(User.admin == true())\
954 return User.query().filter(User.admin == true())\
955 .order_by(User.username.asc()).all()
955 .order_by(User.username.asc()).all()
956
956
957 @classmethod
957 @classmethod
958 def get_default_user(cls, cache=False, refresh=False):
958 def get_default_user(cls, cache=False, refresh=False):
959 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
959 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
960 if user is None:
960 if user is None:
961 raise Exception('FATAL: Missing default account!')
961 raise Exception('FATAL: Missing default account!')
962 if refresh:
962 if refresh:
963 # The default user might be based on outdated state which
963 # The default user might be based on outdated state which
964 # has been loaded from the cache.
964 # has been loaded from the cache.
965 # A call to refresh() ensures that the
965 # A call to refresh() ensures that the
966 # latest state from the database is used.
966 # latest state from the database is used.
967 Session().refresh(user)
967 Session().refresh(user)
968 return user
968 return user
969
969
970 def _get_default_perms(self, user, suffix=''):
970 def _get_default_perms(self, user, suffix=''):
971 from rhodecode.model.permission import PermissionModel
971 from rhodecode.model.permission import PermissionModel
972 return PermissionModel().get_default_perms(user.user_perms, suffix)
972 return PermissionModel().get_default_perms(user.user_perms, suffix)
973
973
974 def get_default_perms(self, suffix=''):
974 def get_default_perms(self, suffix=''):
975 return self._get_default_perms(self, suffix)
975 return self._get_default_perms(self, suffix)
976
976
977 def get_api_data(self, include_secrets=False, details='full'):
977 def get_api_data(self, include_secrets=False, details='full'):
978 """
978 """
979 Common function for generating user related data for API
979 Common function for generating user related data for API
980
980
981 :param include_secrets: By default secrets in the API data will be replaced
981 :param include_secrets: By default secrets in the API data will be replaced
982 by a placeholder value to prevent exposing this data by accident. In case
982 by a placeholder value to prevent exposing this data by accident. In case
983 this data shall be exposed, set this flag to ``True``.
983 this data shall be exposed, set this flag to ``True``.
984
984
985 :param details: details can be 'basic|full' basic gives only a subset of
985 :param details: details can be 'basic|full' basic gives only a subset of
986 the available user information that includes user_id, name and emails.
986 the available user information that includes user_id, name and emails.
987 """
987 """
988 user = self
988 user = self
989 user_data = self.user_data
989 user_data = self.user_data
990 data = {
990 data = {
991 'user_id': user.user_id,
991 'user_id': user.user_id,
992 'username': user.username,
992 'username': user.username,
993 'firstname': user.name,
993 'firstname': user.name,
994 'lastname': user.lastname,
994 'lastname': user.lastname,
995 'email': user.email,
995 'email': user.email,
996 'emails': user.emails,
996 'emails': user.emails,
997 }
997 }
998 if details == 'basic':
998 if details == 'basic':
999 return data
999 return data
1000
1000
1001 auth_token_length = 40
1001 auth_token_length = 40
1002 auth_token_replacement = '*' * auth_token_length
1002 auth_token_replacement = '*' * auth_token_length
1003
1003
1004 extras = {
1004 extras = {
1005 'auth_tokens': [auth_token_replacement],
1005 'auth_tokens': [auth_token_replacement],
1006 'active': user.active,
1006 'active': user.active,
1007 'admin': user.admin,
1007 'admin': user.admin,
1008 'extern_type': user.extern_type,
1008 'extern_type': user.extern_type,
1009 'extern_name': user.extern_name,
1009 'extern_name': user.extern_name,
1010 'last_login': user.last_login,
1010 'last_login': user.last_login,
1011 'last_activity': user.last_activity,
1011 'last_activity': user.last_activity,
1012 'ip_addresses': user.ip_addresses,
1012 'ip_addresses': user.ip_addresses,
1013 'language': user_data.get('language')
1013 'language': user_data.get('language')
1014 }
1014 }
1015 data.update(extras)
1015 data.update(extras)
1016
1016
1017 if include_secrets:
1017 if include_secrets:
1018 data['auth_tokens'] = user.auth_tokens
1018 data['auth_tokens'] = user.auth_tokens
1019 return data
1019 return data
1020
1020
1021 def __json__(self):
1021 def __json__(self):
1022 data = {
1022 data = {
1023 'full_name': self.full_name,
1023 'full_name': self.full_name,
1024 'full_name_or_username': self.full_name_or_username,
1024 'full_name_or_username': self.full_name_or_username,
1025 'short_contact': self.short_contact,
1025 'short_contact': self.short_contact,
1026 'full_contact': self.full_contact,
1026 'full_contact': self.full_contact,
1027 }
1027 }
1028 data.update(self.get_api_data())
1028 data.update(self.get_api_data())
1029 return data
1029 return data
1030
1030
1031
1031
1032 class UserApiKeys(Base, BaseModel):
1032 class UserApiKeys(Base, BaseModel):
1033 __tablename__ = 'user_api_keys'
1033 __tablename__ = 'user_api_keys'
1034 __table_args__ = (
1034 __table_args__ = (
1035 Index('uak_api_key_idx', 'api_key', unique=True),
1035 Index('uak_api_key_idx', 'api_key', unique=True),
1036 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1036 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1037 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1037 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1038 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1038 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1039 )
1039 )
1040 __mapper_args__ = {}
1040 __mapper_args__ = {}
1041
1041
1042 # ApiKey role
1042 # ApiKey role
1043 ROLE_ALL = 'token_role_all'
1043 ROLE_ALL = 'token_role_all'
1044 ROLE_HTTP = 'token_role_http'
1044 ROLE_HTTP = 'token_role_http'
1045 ROLE_VCS = 'token_role_vcs'
1045 ROLE_VCS = 'token_role_vcs'
1046 ROLE_API = 'token_role_api'
1046 ROLE_API = 'token_role_api'
1047 ROLE_FEED = 'token_role_feed'
1047 ROLE_FEED = 'token_role_feed'
1048 ROLE_PASSWORD_RESET = 'token_password_reset'
1048 ROLE_PASSWORD_RESET = 'token_password_reset'
1049
1049
1050 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1050 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1051
1051
1052 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1052 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1053 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1053 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1054 api_key = Column("api_key", String(255), nullable=False, unique=True)
1054 api_key = Column("api_key", String(255), nullable=False, unique=True)
1055 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1055 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1056 expires = Column('expires', Float(53), nullable=False)
1056 expires = Column('expires', Float(53), nullable=False)
1057 role = Column('role', String(255), nullable=True)
1057 role = Column('role', String(255), nullable=True)
1058 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1058 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1059
1059
1060 # scope columns
1060 # scope columns
1061 repo_id = Column(
1061 repo_id = Column(
1062 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1062 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1063 nullable=True, unique=None, default=None)
1063 nullable=True, unique=None, default=None)
1064 repo = relationship('Repository', lazy='joined')
1064 repo = relationship('Repository', lazy='joined')
1065
1065
1066 repo_group_id = Column(
1066 repo_group_id = Column(
1067 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1067 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1068 nullable=True, unique=None, default=None)
1068 nullable=True, unique=None, default=None)
1069 repo_group = relationship('RepoGroup', lazy='joined')
1069 repo_group = relationship('RepoGroup', lazy='joined')
1070
1070
1071 user = relationship('User', lazy='joined')
1071 user = relationship('User', lazy='joined')
1072
1072
1073 def __unicode__(self):
1073 def __unicode__(self):
1074 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1074 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1075
1075
1076 def __json__(self):
1076 def __json__(self):
1077 data = {
1077 data = {
1078 'auth_token': self.api_key,
1078 'auth_token': self.api_key,
1079 'role': self.role,
1079 'role': self.role,
1080 'scope': self.scope_humanized,
1080 'scope': self.scope_humanized,
1081 'expired': self.expired
1081 'expired': self.expired
1082 }
1082 }
1083 return data
1083 return data
1084
1084
1085 def get_api_data(self, include_secrets=False):
1085 def get_api_data(self, include_secrets=False):
1086 data = self.__json__()
1086 data = self.__json__()
1087 if include_secrets:
1087 if include_secrets:
1088 return data
1088 return data
1089 else:
1089 else:
1090 data['auth_token'] = self.token_obfuscated
1090 data['auth_token'] = self.token_obfuscated
1091 return data
1091 return data
1092
1092
1093 @hybrid_property
1093 @hybrid_property
1094 def description_safe(self):
1094 def description_safe(self):
1095 from rhodecode.lib import helpers as h
1095 from rhodecode.lib import helpers as h
1096 return h.escape(self.description)
1096 return h.escape(self.description)
1097
1097
1098 @property
1098 @property
1099 def expired(self):
1099 def expired(self):
1100 if self.expires == -1:
1100 if self.expires == -1:
1101 return False
1101 return False
1102 return time.time() > self.expires
1102 return time.time() > self.expires
1103
1103
1104 @classmethod
1104 @classmethod
1105 def _get_role_name(cls, role):
1105 def _get_role_name(cls, role):
1106 return {
1106 return {
1107 cls.ROLE_ALL: _('all'),
1107 cls.ROLE_ALL: _('all'),
1108 cls.ROLE_HTTP: _('http/web interface'),
1108 cls.ROLE_HTTP: _('http/web interface'),
1109 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1109 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1110 cls.ROLE_API: _('api calls'),
1110 cls.ROLE_API: _('api calls'),
1111 cls.ROLE_FEED: _('feed access'),
1111 cls.ROLE_FEED: _('feed access'),
1112 }.get(role, role)
1112 }.get(role, role)
1113
1113
1114 @property
1114 @property
1115 def role_humanized(self):
1115 def role_humanized(self):
1116 return self._get_role_name(self.role)
1116 return self._get_role_name(self.role)
1117
1117
1118 def _get_scope(self):
1118 def _get_scope(self):
1119 if self.repo:
1119 if self.repo:
1120 return repr(self.repo)
1120 return repr(self.repo)
1121 if self.repo_group:
1121 if self.repo_group:
1122 return repr(self.repo_group) + ' (recursive)'
1122 return repr(self.repo_group) + ' (recursive)'
1123 return 'global'
1123 return 'global'
1124
1124
1125 @property
1125 @property
1126 def scope_humanized(self):
1126 def scope_humanized(self):
1127 return self._get_scope()
1127 return self._get_scope()
1128
1128
1129 @property
1129 @property
1130 def token_obfuscated(self):
1130 def token_obfuscated(self):
1131 if self.api_key:
1131 if self.api_key:
1132 return self.api_key[:4] + "****"
1132 return self.api_key[:4] + "****"
1133
1133
1134
1134
1135 class UserEmailMap(Base, BaseModel):
1135 class UserEmailMap(Base, BaseModel):
1136 __tablename__ = 'user_email_map'
1136 __tablename__ = 'user_email_map'
1137 __table_args__ = (
1137 __table_args__ = (
1138 Index('uem_email_idx', 'email'),
1138 Index('uem_email_idx', 'email'),
1139 UniqueConstraint('email'),
1139 UniqueConstraint('email'),
1140 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1140 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1141 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1141 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1142 )
1142 )
1143 __mapper_args__ = {}
1143 __mapper_args__ = {}
1144
1144
1145 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1145 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1146 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1146 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1147 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1147 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1148 user = relationship('User', lazy='joined')
1148 user = relationship('User', lazy='joined')
1149
1149
1150 @validates('_email')
1150 @validates('_email')
1151 def validate_email(self, key, email):
1151 def validate_email(self, key, email):
1152 # check if this email is not main one
1152 # check if this email is not main one
1153 main_email = Session().query(User).filter(User.email == email).scalar()
1153 main_email = Session().query(User).filter(User.email == email).scalar()
1154 if main_email is not None:
1154 if main_email is not None:
1155 raise AttributeError('email %s is present is user table' % email)
1155 raise AttributeError('email %s is present is user table' % email)
1156 return email
1156 return email
1157
1157
1158 @hybrid_property
1158 @hybrid_property
1159 def email(self):
1159 def email(self):
1160 return self._email
1160 return self._email
1161
1161
1162 @email.setter
1162 @email.setter
1163 def email(self, val):
1163 def email(self, val):
1164 self._email = val.lower() if val else None
1164 self._email = val.lower() if val else None
1165
1165
1166
1166
1167 class UserIpMap(Base, BaseModel):
1167 class UserIpMap(Base, BaseModel):
1168 __tablename__ = 'user_ip_map'
1168 __tablename__ = 'user_ip_map'
1169 __table_args__ = (
1169 __table_args__ = (
1170 UniqueConstraint('user_id', 'ip_addr'),
1170 UniqueConstraint('user_id', 'ip_addr'),
1171 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1171 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1172 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1172 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1173 )
1173 )
1174 __mapper_args__ = {}
1174 __mapper_args__ = {}
1175
1175
1176 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1176 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1177 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1177 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1178 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1178 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1179 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1179 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1180 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1180 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1181 user = relationship('User', lazy='joined')
1181 user = relationship('User', lazy='joined')
1182
1182
1183 @hybrid_property
1183 @hybrid_property
1184 def description_safe(self):
1184 def description_safe(self):
1185 from rhodecode.lib import helpers as h
1185 from rhodecode.lib import helpers as h
1186 return h.escape(self.description)
1186 return h.escape(self.description)
1187
1187
1188 @classmethod
1188 @classmethod
1189 def _get_ip_range(cls, ip_addr):
1189 def _get_ip_range(cls, ip_addr):
1190 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1190 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1191 return [str(net.network_address), str(net.broadcast_address)]
1191 return [str(net.network_address), str(net.broadcast_address)]
1192
1192
1193 def __json__(self):
1193 def __json__(self):
1194 return {
1194 return {
1195 'ip_addr': self.ip_addr,
1195 'ip_addr': self.ip_addr,
1196 'ip_range': self._get_ip_range(self.ip_addr),
1196 'ip_range': self._get_ip_range(self.ip_addr),
1197 }
1197 }
1198
1198
1199 def __unicode__(self):
1199 def __unicode__(self):
1200 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1200 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1201 self.user_id, self.ip_addr)
1201 self.user_id, self.ip_addr)
1202
1202
1203
1203
1204 class UserSshKeys(Base, BaseModel):
1204 class UserSshKeys(Base, BaseModel):
1205 __tablename__ = 'user_ssh_keys'
1205 __tablename__ = 'user_ssh_keys'
1206 __table_args__ = (
1206 __table_args__ = (
1207 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1207 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1208
1208
1209 UniqueConstraint('ssh_key_fingerprint'),
1209 UniqueConstraint('ssh_key_fingerprint'),
1210
1210
1211 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1211 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1212 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1212 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1213 )
1213 )
1214 __mapper_args__ = {}
1214 __mapper_args__ = {}
1215
1215
1216 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1216 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1217 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1217 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1218 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1218 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1219
1219
1220 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1220 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1221
1221
1222 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1222 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1223 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1223 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1224 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1224 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1225
1225
1226 user = relationship('User', lazy='joined')
1226 user = relationship('User', lazy='joined')
1227
1227
1228 def __json__(self):
1228 def __json__(self):
1229 data = {
1229 data = {
1230 'ssh_fingerprint': self.ssh_key_fingerprint,
1230 'ssh_fingerprint': self.ssh_key_fingerprint,
1231 'description': self.description,
1231 'description': self.description,
1232 'created_on': self.created_on
1232 'created_on': self.created_on
1233 }
1233 }
1234 return data
1234 return data
1235
1235
1236 def get_api_data(self):
1236 def get_api_data(self):
1237 data = self.__json__()
1237 data = self.__json__()
1238 return data
1238 return data
1239
1239
1240
1240
1241 class UserLog(Base, BaseModel):
1241 class UserLog(Base, BaseModel):
1242 __tablename__ = 'user_logs'
1242 __tablename__ = 'user_logs'
1243 __table_args__ = (
1243 __table_args__ = (
1244 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1244 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1245 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1245 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1246 )
1246 )
1247 VERSION_1 = 'v1'
1247 VERSION_1 = 'v1'
1248 VERSION_2 = 'v2'
1248 VERSION_2 = 'v2'
1249 VERSIONS = [VERSION_1, VERSION_2]
1249 VERSIONS = [VERSION_1, VERSION_2]
1250
1250
1251 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1251 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1252 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1252 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1253 username = Column("username", String(255), nullable=True, unique=None, default=None)
1253 username = Column("username", String(255), nullable=True, unique=None, default=None)
1254 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1254 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1255 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1255 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1256 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1256 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1257 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1257 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1258 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1258 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1259
1259
1260 version = Column("version", String(255), nullable=True, default=VERSION_1)
1260 version = Column("version", String(255), nullable=True, default=VERSION_1)
1261 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1261 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1262 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1262 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1263
1263
1264 def __unicode__(self):
1264 def __unicode__(self):
1265 return u"<%s('id:%s:%s')>" % (
1265 return u"<%s('id:%s:%s')>" % (
1266 self.__class__.__name__, self.repository_name, self.action)
1266 self.__class__.__name__, self.repository_name, self.action)
1267
1267
1268 def __json__(self):
1268 def __json__(self):
1269 return {
1269 return {
1270 'user_id': self.user_id,
1270 'user_id': self.user_id,
1271 'username': self.username,
1271 'username': self.username,
1272 'repository_id': self.repository_id,
1272 'repository_id': self.repository_id,
1273 'repository_name': self.repository_name,
1273 'repository_name': self.repository_name,
1274 'user_ip': self.user_ip,
1274 'user_ip': self.user_ip,
1275 'action_date': self.action_date,
1275 'action_date': self.action_date,
1276 'action': self.action,
1276 'action': self.action,
1277 }
1277 }
1278
1278
1279 @hybrid_property
1279 @hybrid_property
1280 def entry_id(self):
1280 def entry_id(self):
1281 return self.user_log_id
1281 return self.user_log_id
1282
1282
1283 @property
1283 @property
1284 def action_as_day(self):
1284 def action_as_day(self):
1285 return datetime.date(*self.action_date.timetuple()[:3])
1285 return datetime.date(*self.action_date.timetuple()[:3])
1286
1286
1287 user = relationship('User')
1287 user = relationship('User')
1288 repository = relationship('Repository', cascade='')
1288 repository = relationship('Repository', cascade='')
1289
1289
1290
1290
1291 class UserGroup(Base, BaseModel):
1291 class UserGroup(Base, BaseModel):
1292 __tablename__ = 'users_groups'
1292 __tablename__ = 'users_groups'
1293 __table_args__ = (
1293 __table_args__ = (
1294 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1294 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1295 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1295 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1296 )
1296 )
1297
1297
1298 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1298 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1299 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1299 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1300 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1300 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1301 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1301 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1302 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1302 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1303 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1303 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1304 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1304 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1305 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1305 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1306
1306
1307 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1307 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1308 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1308 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1309 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1309 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1310 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1310 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1311 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1311 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1312 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1312 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1313
1313
1314 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1314 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1315 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1315 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1316
1316
1317 @classmethod
1317 @classmethod
1318 def _load_group_data(cls, column):
1318 def _load_group_data(cls, column):
1319 if not column:
1319 if not column:
1320 return {}
1320 return {}
1321
1321
1322 try:
1322 try:
1323 return json.loads(column) or {}
1323 return json.loads(column) or {}
1324 except TypeError:
1324 except TypeError:
1325 return {}
1325 return {}
1326
1326
1327 @hybrid_property
1327 @hybrid_property
1328 def description_safe(self):
1328 def description_safe(self):
1329 from rhodecode.lib import helpers as h
1329 from rhodecode.lib import helpers as h
1330 return h.escape(self.user_group_description)
1330 return h.escape(self.user_group_description)
1331
1331
1332 @hybrid_property
1332 @hybrid_property
1333 def group_data(self):
1333 def group_data(self):
1334 return self._load_group_data(self._group_data)
1334 return self._load_group_data(self._group_data)
1335
1335
1336 @group_data.expression
1336 @group_data.expression
1337 def group_data(self, **kwargs):
1337 def group_data(self, **kwargs):
1338 return self._group_data
1338 return self._group_data
1339
1339
1340 @group_data.setter
1340 @group_data.setter
1341 def group_data(self, val):
1341 def group_data(self, val):
1342 try:
1342 try:
1343 self._group_data = json.dumps(val)
1343 self._group_data = json.dumps(val)
1344 except Exception:
1344 except Exception:
1345 log.error(traceback.format_exc())
1345 log.error(traceback.format_exc())
1346
1346
1347 def __unicode__(self):
1347 def __unicode__(self):
1348 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1348 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1349 self.users_group_id,
1349 self.users_group_id,
1350 self.users_group_name)
1350 self.users_group_name)
1351
1351
1352 @classmethod
1352 @classmethod
1353 def get_by_group_name(cls, group_name, cache=False,
1353 def get_by_group_name(cls, group_name, cache=False,
1354 case_insensitive=False):
1354 case_insensitive=False):
1355 if case_insensitive:
1355 if case_insensitive:
1356 q = cls.query().filter(func.lower(cls.users_group_name) ==
1356 q = cls.query().filter(func.lower(cls.users_group_name) ==
1357 func.lower(group_name))
1357 func.lower(group_name))
1358
1358
1359 else:
1359 else:
1360 q = cls.query().filter(cls.users_group_name == group_name)
1360 q = cls.query().filter(cls.users_group_name == group_name)
1361 if cache:
1361 if cache:
1362 q = q.options(
1362 q = q.options(
1363 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1363 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1364 return q.scalar()
1364 return q.scalar()
1365
1365
1366 @classmethod
1366 @classmethod
1367 def get(cls, user_group_id, cache=False):
1367 def get(cls, user_group_id, cache=False):
1368 if not user_group_id:
1368 if not user_group_id:
1369 return
1369 return
1370
1370
1371 user_group = cls.query()
1371 user_group = cls.query()
1372 if cache:
1372 if cache:
1373 user_group = user_group.options(
1373 user_group = user_group.options(
1374 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1374 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1375 return user_group.get(user_group_id)
1375 return user_group.get(user_group_id)
1376
1376
1377 def permissions(self, with_admins=True, with_owner=True):
1377 def permissions(self, with_admins=True, with_owner=True):
1378 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1378 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1379 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1379 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1380 joinedload(UserUserGroupToPerm.user),
1380 joinedload(UserUserGroupToPerm.user),
1381 joinedload(UserUserGroupToPerm.permission),)
1381 joinedload(UserUserGroupToPerm.permission),)
1382
1382
1383 # get owners and admins and permissions. We do a trick of re-writing
1383 # get owners and admins and permissions. We do a trick of re-writing
1384 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1384 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1385 # has a global reference and changing one object propagates to all
1385 # has a global reference and changing one object propagates to all
1386 # others. This means if admin is also an owner admin_row that change
1386 # others. This means if admin is also an owner admin_row that change
1387 # would propagate to both objects
1387 # would propagate to both objects
1388 perm_rows = []
1388 perm_rows = []
1389 for _usr in q.all():
1389 for _usr in q.all():
1390 usr = AttributeDict(_usr.user.get_dict())
1390 usr = AttributeDict(_usr.user.get_dict())
1391 usr.permission = _usr.permission.permission_name
1391 usr.permission = _usr.permission.permission_name
1392 perm_rows.append(usr)
1392 perm_rows.append(usr)
1393
1393
1394 # filter the perm rows by 'default' first and then sort them by
1394 # filter the perm rows by 'default' first and then sort them by
1395 # admin,write,read,none permissions sorted again alphabetically in
1395 # admin,write,read,none permissions sorted again alphabetically in
1396 # each group
1396 # each group
1397 perm_rows = sorted(perm_rows, key=display_user_sort)
1397 perm_rows = sorted(perm_rows, key=display_user_sort)
1398
1398
1399 _admin_perm = 'usergroup.admin'
1399 _admin_perm = 'usergroup.admin'
1400 owner_row = []
1400 owner_row = []
1401 if with_owner:
1401 if with_owner:
1402 usr = AttributeDict(self.user.get_dict())
1402 usr = AttributeDict(self.user.get_dict())
1403 usr.owner_row = True
1403 usr.owner_row = True
1404 usr.permission = _admin_perm
1404 usr.permission = _admin_perm
1405 owner_row.append(usr)
1405 owner_row.append(usr)
1406
1406
1407 super_admin_rows = []
1407 super_admin_rows = []
1408 if with_admins:
1408 if with_admins:
1409 for usr in User.get_all_super_admins():
1409 for usr in User.get_all_super_admins():
1410 # if this admin is also owner, don't double the record
1410 # if this admin is also owner, don't double the record
1411 if usr.user_id == owner_row[0].user_id:
1411 if usr.user_id == owner_row[0].user_id:
1412 owner_row[0].admin_row = True
1412 owner_row[0].admin_row = True
1413 else:
1413 else:
1414 usr = AttributeDict(usr.get_dict())
1414 usr = AttributeDict(usr.get_dict())
1415 usr.admin_row = True
1415 usr.admin_row = True
1416 usr.permission = _admin_perm
1416 usr.permission = _admin_perm
1417 super_admin_rows.append(usr)
1417 super_admin_rows.append(usr)
1418
1418
1419 return super_admin_rows + owner_row + perm_rows
1419 return super_admin_rows + owner_row + perm_rows
1420
1420
1421 def permission_user_groups(self):
1421 def permission_user_groups(self):
1422 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1422 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1423 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1423 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1424 joinedload(UserGroupUserGroupToPerm.target_user_group),
1424 joinedload(UserGroupUserGroupToPerm.target_user_group),
1425 joinedload(UserGroupUserGroupToPerm.permission),)
1425 joinedload(UserGroupUserGroupToPerm.permission),)
1426
1426
1427 perm_rows = []
1427 perm_rows = []
1428 for _user_group in q.all():
1428 for _user_group in q.all():
1429 usr = AttributeDict(_user_group.user_group.get_dict())
1429 usr = AttributeDict(_user_group.user_group.get_dict())
1430 usr.permission = _user_group.permission.permission_name
1430 usr.permission = _user_group.permission.permission_name
1431 perm_rows.append(usr)
1431 perm_rows.append(usr)
1432
1432
1433 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1433 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1434 return perm_rows
1434 return perm_rows
1435
1435
1436 def _get_default_perms(self, user_group, suffix=''):
1436 def _get_default_perms(self, user_group, suffix=''):
1437 from rhodecode.model.permission import PermissionModel
1437 from rhodecode.model.permission import PermissionModel
1438 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1438 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1439
1439
1440 def get_default_perms(self, suffix=''):
1440 def get_default_perms(self, suffix=''):
1441 return self._get_default_perms(self, suffix)
1441 return self._get_default_perms(self, suffix)
1442
1442
1443 def get_api_data(self, with_group_members=True, include_secrets=False):
1443 def get_api_data(self, with_group_members=True, include_secrets=False):
1444 """
1444 """
1445 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1445 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1446 basically forwarded.
1446 basically forwarded.
1447
1447
1448 """
1448 """
1449 user_group = self
1449 user_group = self
1450 data = {
1450 data = {
1451 'users_group_id': user_group.users_group_id,
1451 'users_group_id': user_group.users_group_id,
1452 'group_name': user_group.users_group_name,
1452 'group_name': user_group.users_group_name,
1453 'group_description': user_group.user_group_description,
1453 'group_description': user_group.user_group_description,
1454 'active': user_group.users_group_active,
1454 'active': user_group.users_group_active,
1455 'owner': user_group.user.username,
1455 'owner': user_group.user.username,
1456 'owner_email': user_group.user.email,
1456 'owner_email': user_group.user.email,
1457 }
1457 }
1458
1458
1459 if with_group_members:
1459 if with_group_members:
1460 users = []
1460 users = []
1461 for user in user_group.members:
1461 for user in user_group.members:
1462 user = user.user
1462 user = user.user
1463 users.append(user.get_api_data(include_secrets=include_secrets))
1463 users.append(user.get_api_data(include_secrets=include_secrets))
1464 data['users'] = users
1464 data['users'] = users
1465
1465
1466 return data
1466 return data
1467
1467
1468
1468
1469 class UserGroupMember(Base, BaseModel):
1469 class UserGroupMember(Base, BaseModel):
1470 __tablename__ = 'users_groups_members'
1470 __tablename__ = 'users_groups_members'
1471 __table_args__ = (
1471 __table_args__ = (
1472 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1472 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1473 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1473 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1474 )
1474 )
1475
1475
1476 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1476 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1477 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1477 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1478 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1478 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1479
1479
1480 user = relationship('User', lazy='joined')
1480 user = relationship('User', lazy='joined')
1481 users_group = relationship('UserGroup')
1481 users_group = relationship('UserGroup')
1482
1482
1483 def __init__(self, gr_id='', u_id=''):
1483 def __init__(self, gr_id='', u_id=''):
1484 self.users_group_id = gr_id
1484 self.users_group_id = gr_id
1485 self.user_id = u_id
1485 self.user_id = u_id
1486
1486
1487
1487
1488 class RepositoryField(Base, BaseModel):
1488 class RepositoryField(Base, BaseModel):
1489 __tablename__ = 'repositories_fields'
1489 __tablename__ = 'repositories_fields'
1490 __table_args__ = (
1490 __table_args__ = (
1491 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1491 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1492 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1492 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1493 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1493 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1494 )
1494 )
1495 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1495 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1496
1496
1497 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1497 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1498 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1498 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1499 field_key = Column("field_key", String(250))
1499 field_key = Column("field_key", String(250))
1500 field_label = Column("field_label", String(1024), nullable=False)
1500 field_label = Column("field_label", String(1024), nullable=False)
1501 field_value = Column("field_value", String(10000), nullable=False)
1501 field_value = Column("field_value", String(10000), nullable=False)
1502 field_desc = Column("field_desc", String(1024), nullable=False)
1502 field_desc = Column("field_desc", String(1024), nullable=False)
1503 field_type = Column("field_type", String(255), nullable=False, unique=None)
1503 field_type = Column("field_type", String(255), nullable=False, unique=None)
1504 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1504 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1505
1505
1506 repository = relationship('Repository')
1506 repository = relationship('Repository')
1507
1507
1508 @property
1508 @property
1509 def field_key_prefixed(self):
1509 def field_key_prefixed(self):
1510 return 'ex_%s' % self.field_key
1510 return 'ex_%s' % self.field_key
1511
1511
1512 @classmethod
1512 @classmethod
1513 def un_prefix_key(cls, key):
1513 def un_prefix_key(cls, key):
1514 if key.startswith(cls.PREFIX):
1514 if key.startswith(cls.PREFIX):
1515 return key[len(cls.PREFIX):]
1515 return key[len(cls.PREFIX):]
1516 return key
1516 return key
1517
1517
1518 @classmethod
1518 @classmethod
1519 def get_by_key_name(cls, key, repo):
1519 def get_by_key_name(cls, key, repo):
1520 row = cls.query()\
1520 row = cls.query()\
1521 .filter(cls.repository == repo)\
1521 .filter(cls.repository == repo)\
1522 .filter(cls.field_key == key).scalar()
1522 .filter(cls.field_key == key).scalar()
1523 return row
1523 return row
1524
1524
1525
1525
1526 class Repository(Base, BaseModel):
1526 class Repository(Base, BaseModel):
1527 __tablename__ = 'repositories'
1527 __tablename__ = 'repositories'
1528 __table_args__ = (
1528 __table_args__ = (
1529 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1529 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1530 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1530 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1531 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1531 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1532 )
1532 )
1533 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1533 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1534 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1534 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1535 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1535
1536
1536 STATE_CREATED = 'repo_state_created'
1537 STATE_CREATED = 'repo_state_created'
1537 STATE_PENDING = 'repo_state_pending'
1538 STATE_PENDING = 'repo_state_pending'
1538 STATE_ERROR = 'repo_state_error'
1539 STATE_ERROR = 'repo_state_error'
1539
1540
1540 LOCK_AUTOMATIC = 'lock_auto'
1541 LOCK_AUTOMATIC = 'lock_auto'
1541 LOCK_API = 'lock_api'
1542 LOCK_API = 'lock_api'
1542 LOCK_WEB = 'lock_web'
1543 LOCK_WEB = 'lock_web'
1543 LOCK_PULL = 'lock_pull'
1544 LOCK_PULL = 'lock_pull'
1544
1545
1545 NAME_SEP = URL_SEP
1546 NAME_SEP = URL_SEP
1546
1547
1547 repo_id = Column(
1548 repo_id = Column(
1548 "repo_id", Integer(), nullable=False, unique=True, default=None,
1549 "repo_id", Integer(), nullable=False, unique=True, default=None,
1549 primary_key=True)
1550 primary_key=True)
1550 _repo_name = Column(
1551 _repo_name = Column(
1551 "repo_name", Text(), nullable=False, default=None)
1552 "repo_name", Text(), nullable=False, default=None)
1552 _repo_name_hash = Column(
1553 _repo_name_hash = Column(
1553 "repo_name_hash", String(255), nullable=False, unique=True)
1554 "repo_name_hash", String(255), nullable=False, unique=True)
1554 repo_state = Column("repo_state", String(255), nullable=True)
1555 repo_state = Column("repo_state", String(255), nullable=True)
1555
1556
1556 clone_uri = Column(
1557 clone_uri = Column(
1557 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1558 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1558 default=None)
1559 default=None)
1559 repo_type = Column(
1560 repo_type = Column(
1560 "repo_type", String(255), nullable=False, unique=False, default=None)
1561 "repo_type", String(255), nullable=False, unique=False, default=None)
1561 user_id = Column(
1562 user_id = Column(
1562 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1563 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1563 unique=False, default=None)
1564 unique=False, default=None)
1564 private = Column(
1565 private = Column(
1565 "private", Boolean(), nullable=True, unique=None, default=None)
1566 "private", Boolean(), nullable=True, unique=None, default=None)
1566 enable_statistics = Column(
1567 enable_statistics = Column(
1567 "statistics", Boolean(), nullable=True, unique=None, default=True)
1568 "statistics", Boolean(), nullable=True, unique=None, default=True)
1568 enable_downloads = Column(
1569 enable_downloads = Column(
1569 "downloads", Boolean(), nullable=True, unique=None, default=True)
1570 "downloads", Boolean(), nullable=True, unique=None, default=True)
1570 description = Column(
1571 description = Column(
1571 "description", String(10000), nullable=True, unique=None, default=None)
1572 "description", String(10000), nullable=True, unique=None, default=None)
1572 created_on = Column(
1573 created_on = Column(
1573 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1574 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1574 default=datetime.datetime.now)
1575 default=datetime.datetime.now)
1575 updated_on = Column(
1576 updated_on = Column(
1576 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1577 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1577 default=datetime.datetime.now)
1578 default=datetime.datetime.now)
1578 _landing_revision = Column(
1579 _landing_revision = Column(
1579 "landing_revision", String(255), nullable=False, unique=False,
1580 "landing_revision", String(255), nullable=False, unique=False,
1580 default=None)
1581 default=None)
1581 enable_locking = Column(
1582 enable_locking = Column(
1582 "enable_locking", Boolean(), nullable=False, unique=None,
1583 "enable_locking", Boolean(), nullable=False, unique=None,
1583 default=False)
1584 default=False)
1584 _locked = Column(
1585 _locked = Column(
1585 "locked", String(255), nullable=True, unique=False, default=None)
1586 "locked", String(255), nullable=True, unique=False, default=None)
1586 _changeset_cache = Column(
1587 _changeset_cache = Column(
1587 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1588 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1588
1589
1589 fork_id = Column(
1590 fork_id = Column(
1590 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1591 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1591 nullable=True, unique=False, default=None)
1592 nullable=True, unique=False, default=None)
1592 group_id = Column(
1593 group_id = Column(
1593 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1594 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1594 unique=False, default=None)
1595 unique=False, default=None)
1595
1596
1596 user = relationship('User', lazy='joined')
1597 user = relationship('User', lazy='joined')
1597 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1598 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1598 group = relationship('RepoGroup', lazy='joined')
1599 group = relationship('RepoGroup', lazy='joined')
1599 repo_to_perm = relationship(
1600 repo_to_perm = relationship(
1600 'UserRepoToPerm', cascade='all',
1601 'UserRepoToPerm', cascade='all',
1601 order_by='UserRepoToPerm.repo_to_perm_id')
1602 order_by='UserRepoToPerm.repo_to_perm_id')
1602 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1603 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1603 stats = relationship('Statistics', cascade='all', uselist=False)
1604 stats = relationship('Statistics', cascade='all', uselist=False)
1604
1605
1605 followers = relationship(
1606 followers = relationship(
1606 'UserFollowing',
1607 'UserFollowing',
1607 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1608 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1608 cascade='all')
1609 cascade='all')
1609 extra_fields = relationship(
1610 extra_fields = relationship(
1610 'RepositoryField', cascade="all, delete, delete-orphan")
1611 'RepositoryField', cascade="all, delete, delete-orphan")
1611 logs = relationship('UserLog')
1612 logs = relationship('UserLog')
1612 comments = relationship(
1613 comments = relationship(
1613 'ChangesetComment', cascade="all, delete, delete-orphan")
1614 'ChangesetComment', cascade="all, delete, delete-orphan")
1614 pull_requests_source = relationship(
1615 pull_requests_source = relationship(
1615 'PullRequest',
1616 'PullRequest',
1616 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1617 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1617 cascade="all, delete, delete-orphan")
1618 cascade="all, delete, delete-orphan")
1618 pull_requests_target = relationship(
1619 pull_requests_target = relationship(
1619 'PullRequest',
1620 'PullRequest',
1620 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1621 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1621 cascade="all, delete, delete-orphan")
1622 cascade="all, delete, delete-orphan")
1622 ui = relationship('RepoRhodeCodeUi', cascade="all")
1623 ui = relationship('RepoRhodeCodeUi', cascade="all")
1623 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1624 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1624 integrations = relationship('Integration',
1625 integrations = relationship('Integration',
1625 cascade="all, delete, delete-orphan")
1626 cascade="all, delete, delete-orphan")
1626
1627
1627 scoped_tokens = relationship('UserApiKeys', cascade="all")
1628 scoped_tokens = relationship('UserApiKeys', cascade="all")
1628
1629
1629 def __unicode__(self):
1630 def __unicode__(self):
1630 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1631 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1631 safe_unicode(self.repo_name))
1632 safe_unicode(self.repo_name))
1632
1633
1633 @hybrid_property
1634 @hybrid_property
1634 def description_safe(self):
1635 def description_safe(self):
1635 from rhodecode.lib import helpers as h
1636 from rhodecode.lib import helpers as h
1636 return h.escape(self.description)
1637 return h.escape(self.description)
1637
1638
1638 @hybrid_property
1639 @hybrid_property
1639 def landing_rev(self):
1640 def landing_rev(self):
1640 # always should return [rev_type, rev]
1641 # always should return [rev_type, rev]
1641 if self._landing_revision:
1642 if self._landing_revision:
1642 _rev_info = self._landing_revision.split(':')
1643 _rev_info = self._landing_revision.split(':')
1643 if len(_rev_info) < 2:
1644 if len(_rev_info) < 2:
1644 _rev_info.insert(0, 'rev')
1645 _rev_info.insert(0, 'rev')
1645 return [_rev_info[0], _rev_info[1]]
1646 return [_rev_info[0], _rev_info[1]]
1646 return [None, None]
1647 return [None, None]
1647
1648
1648 @landing_rev.setter
1649 @landing_rev.setter
1649 def landing_rev(self, val):
1650 def landing_rev(self, val):
1650 if ':' not in val:
1651 if ':' not in val:
1651 raise ValueError('value must be delimited with `:` and consist '
1652 raise ValueError('value must be delimited with `:` and consist '
1652 'of <rev_type>:<rev>, got %s instead' % val)
1653 'of <rev_type>:<rev>, got %s instead' % val)
1653 self._landing_revision = val
1654 self._landing_revision = val
1654
1655
1655 @hybrid_property
1656 @hybrid_property
1656 def locked(self):
1657 def locked(self):
1657 if self._locked:
1658 if self._locked:
1658 user_id, timelocked, reason = self._locked.split(':')
1659 user_id, timelocked, reason = self._locked.split(':')
1659 lock_values = int(user_id), timelocked, reason
1660 lock_values = int(user_id), timelocked, reason
1660 else:
1661 else:
1661 lock_values = [None, None, None]
1662 lock_values = [None, None, None]
1662 return lock_values
1663 return lock_values
1663
1664
1664 @locked.setter
1665 @locked.setter
1665 def locked(self, val):
1666 def locked(self, val):
1666 if val and isinstance(val, (list, tuple)):
1667 if val and isinstance(val, (list, tuple)):
1667 self._locked = ':'.join(map(str, val))
1668 self._locked = ':'.join(map(str, val))
1668 else:
1669 else:
1669 self._locked = None
1670 self._locked = None
1670
1671
1671 @hybrid_property
1672 @hybrid_property
1672 def changeset_cache(self):
1673 def changeset_cache(self):
1673 from rhodecode.lib.vcs.backends.base import EmptyCommit
1674 from rhodecode.lib.vcs.backends.base import EmptyCommit
1674 dummy = EmptyCommit().__json__()
1675 dummy = EmptyCommit().__json__()
1675 if not self._changeset_cache:
1676 if not self._changeset_cache:
1676 return dummy
1677 return dummy
1677 try:
1678 try:
1678 return json.loads(self._changeset_cache)
1679 return json.loads(self._changeset_cache)
1679 except TypeError:
1680 except TypeError:
1680 return dummy
1681 return dummy
1681 except Exception:
1682 except Exception:
1682 log.error(traceback.format_exc())
1683 log.error(traceback.format_exc())
1683 return dummy
1684 return dummy
1684
1685
1685 @changeset_cache.setter
1686 @changeset_cache.setter
1686 def changeset_cache(self, val):
1687 def changeset_cache(self, val):
1687 try:
1688 try:
1688 self._changeset_cache = json.dumps(val)
1689 self._changeset_cache = json.dumps(val)
1689 except Exception:
1690 except Exception:
1690 log.error(traceback.format_exc())
1691 log.error(traceback.format_exc())
1691
1692
1692 @hybrid_property
1693 @hybrid_property
1693 def repo_name(self):
1694 def repo_name(self):
1694 return self._repo_name
1695 return self._repo_name
1695
1696
1696 @repo_name.setter
1697 @repo_name.setter
1697 def repo_name(self, value):
1698 def repo_name(self, value):
1698 self._repo_name = value
1699 self._repo_name = value
1699 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1700 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1700
1701
1701 @classmethod
1702 @classmethod
1702 def normalize_repo_name(cls, repo_name):
1703 def normalize_repo_name(cls, repo_name):
1703 """
1704 """
1704 Normalizes os specific repo_name to the format internally stored inside
1705 Normalizes os specific repo_name to the format internally stored inside
1705 database using URL_SEP
1706 database using URL_SEP
1706
1707
1707 :param cls:
1708 :param cls:
1708 :param repo_name:
1709 :param repo_name:
1709 """
1710 """
1710 return cls.NAME_SEP.join(repo_name.split(os.sep))
1711 return cls.NAME_SEP.join(repo_name.split(os.sep))
1711
1712
1712 @classmethod
1713 @classmethod
1713 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1714 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1714 session = Session()
1715 session = Session()
1715 q = session.query(cls).filter(cls.repo_name == repo_name)
1716 q = session.query(cls).filter(cls.repo_name == repo_name)
1716
1717
1717 if cache:
1718 if cache:
1718 if identity_cache:
1719 if identity_cache:
1719 val = cls.identity_cache(session, 'repo_name', repo_name)
1720 val = cls.identity_cache(session, 'repo_name', repo_name)
1720 if val:
1721 if val:
1721 return val
1722 return val
1722 else:
1723 else:
1723 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1724 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1724 q = q.options(
1725 q = q.options(
1725 FromCache("sql_cache_short", cache_key))
1726 FromCache("sql_cache_short", cache_key))
1726
1727
1727 return q.scalar()
1728 return q.scalar()
1728
1729
1729 @classmethod
1730 @classmethod
1730 def get_by_id_or_repo_name(cls, repoid):
1731 def get_by_id_or_repo_name(cls, repoid):
1731 if isinstance(repoid, (int, long)):
1732 if isinstance(repoid, (int, long)):
1732 try:
1733 try:
1733 repo = cls.get(repoid)
1734 repo = cls.get(repoid)
1734 except ValueError:
1735 except ValueError:
1735 repo = None
1736 repo = None
1736 else:
1737 else:
1737 repo = cls.get_by_repo_name(repoid)
1738 repo = cls.get_by_repo_name(repoid)
1738 return repo
1739 return repo
1739
1740
1740 @classmethod
1741 @classmethod
1741 def get_by_full_path(cls, repo_full_path):
1742 def get_by_full_path(cls, repo_full_path):
1742 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1743 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1743 repo_name = cls.normalize_repo_name(repo_name)
1744 repo_name = cls.normalize_repo_name(repo_name)
1744 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1745 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1745
1746
1746 @classmethod
1747 @classmethod
1747 def get_repo_forks(cls, repo_id):
1748 def get_repo_forks(cls, repo_id):
1748 return cls.query().filter(Repository.fork_id == repo_id)
1749 return cls.query().filter(Repository.fork_id == repo_id)
1749
1750
1750 @classmethod
1751 @classmethod
1751 def base_path(cls):
1752 def base_path(cls):
1752 """
1753 """
1753 Returns base path when all repos are stored
1754 Returns base path when all repos are stored
1754
1755
1755 :param cls:
1756 :param cls:
1756 """
1757 """
1757 q = Session().query(RhodeCodeUi)\
1758 q = Session().query(RhodeCodeUi)\
1758 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1759 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1759 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1760 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1760 return q.one().ui_value
1761 return q.one().ui_value
1761
1762
1762 @classmethod
1763 @classmethod
1763 def is_valid(cls, repo_name):
1764 def is_valid(cls, repo_name):
1764 """
1765 """
1765 returns True if given repo name is a valid filesystem repository
1766 returns True if given repo name is a valid filesystem repository
1766
1767
1767 :param cls:
1768 :param cls:
1768 :param repo_name:
1769 :param repo_name:
1769 """
1770 """
1770 from rhodecode.lib.utils import is_valid_repo
1771 from rhodecode.lib.utils import is_valid_repo
1771
1772
1772 return is_valid_repo(repo_name, cls.base_path())
1773 return is_valid_repo(repo_name, cls.base_path())
1773
1774
1774 @classmethod
1775 @classmethod
1775 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1776 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1776 case_insensitive=True):
1777 case_insensitive=True):
1777 q = Repository.query()
1778 q = Repository.query()
1778
1779
1779 if not isinstance(user_id, Optional):
1780 if not isinstance(user_id, Optional):
1780 q = q.filter(Repository.user_id == user_id)
1781 q = q.filter(Repository.user_id == user_id)
1781
1782
1782 if not isinstance(group_id, Optional):
1783 if not isinstance(group_id, Optional):
1783 q = q.filter(Repository.group_id == group_id)
1784 q = q.filter(Repository.group_id == group_id)
1784
1785
1785 if case_insensitive:
1786 if case_insensitive:
1786 q = q.order_by(func.lower(Repository.repo_name))
1787 q = q.order_by(func.lower(Repository.repo_name))
1787 else:
1788 else:
1788 q = q.order_by(Repository.repo_name)
1789 q = q.order_by(Repository.repo_name)
1789 return q.all()
1790 return q.all()
1790
1791
1791 @property
1792 @property
1792 def forks(self):
1793 def forks(self):
1793 """
1794 """
1794 Return forks of this repo
1795 Return forks of this repo
1795 """
1796 """
1796 return Repository.get_repo_forks(self.repo_id)
1797 return Repository.get_repo_forks(self.repo_id)
1797
1798
1798 @property
1799 @property
1799 def parent(self):
1800 def parent(self):
1800 """
1801 """
1801 Returns fork parent
1802 Returns fork parent
1802 """
1803 """
1803 return self.fork
1804 return self.fork
1804
1805
1805 @property
1806 @property
1806 def just_name(self):
1807 def just_name(self):
1807 return self.repo_name.split(self.NAME_SEP)[-1]
1808 return self.repo_name.split(self.NAME_SEP)[-1]
1808
1809
1809 @property
1810 @property
1810 def groups_with_parents(self):
1811 def groups_with_parents(self):
1811 groups = []
1812 groups = []
1812 if self.group is None:
1813 if self.group is None:
1813 return groups
1814 return groups
1814
1815
1815 cur_gr = self.group
1816 cur_gr = self.group
1816 groups.insert(0, cur_gr)
1817 groups.insert(0, cur_gr)
1817 while 1:
1818 while 1:
1818 gr = getattr(cur_gr, 'parent_group', None)
1819 gr = getattr(cur_gr, 'parent_group', None)
1819 cur_gr = cur_gr.parent_group
1820 cur_gr = cur_gr.parent_group
1820 if gr is None:
1821 if gr is None:
1821 break
1822 break
1822 groups.insert(0, gr)
1823 groups.insert(0, gr)
1823
1824
1824 return groups
1825 return groups
1825
1826
1826 @property
1827 @property
1827 def groups_and_repo(self):
1828 def groups_and_repo(self):
1828 return self.groups_with_parents, self
1829 return self.groups_with_parents, self
1829
1830
1830 @LazyProperty
1831 @LazyProperty
1831 def repo_path(self):
1832 def repo_path(self):
1832 """
1833 """
1833 Returns base full path for that repository means where it actually
1834 Returns base full path for that repository means where it actually
1834 exists on a filesystem
1835 exists on a filesystem
1835 """
1836 """
1836 q = Session().query(RhodeCodeUi).filter(
1837 q = Session().query(RhodeCodeUi).filter(
1837 RhodeCodeUi.ui_key == self.NAME_SEP)
1838 RhodeCodeUi.ui_key == self.NAME_SEP)
1838 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1839 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1839 return q.one().ui_value
1840 return q.one().ui_value
1840
1841
1841 @property
1842 @property
1842 def repo_full_path(self):
1843 def repo_full_path(self):
1843 p = [self.repo_path]
1844 p = [self.repo_path]
1844 # we need to split the name by / since this is how we store the
1845 # we need to split the name by / since this is how we store the
1845 # names in the database, but that eventually needs to be converted
1846 # names in the database, but that eventually needs to be converted
1846 # into a valid system path
1847 # into a valid system path
1847 p += self.repo_name.split(self.NAME_SEP)
1848 p += self.repo_name.split(self.NAME_SEP)
1848 return os.path.join(*map(safe_unicode, p))
1849 return os.path.join(*map(safe_unicode, p))
1849
1850
1850 @property
1851 @property
1851 def cache_keys(self):
1852 def cache_keys(self):
1852 """
1853 """
1853 Returns associated cache keys for that repo
1854 Returns associated cache keys for that repo
1854 """
1855 """
1855 return CacheKey.query()\
1856 return CacheKey.query()\
1856 .filter(CacheKey.cache_args == self.repo_name)\
1857 .filter(CacheKey.cache_args == self.repo_name)\
1857 .order_by(CacheKey.cache_key)\
1858 .order_by(CacheKey.cache_key)\
1858 .all()
1859 .all()
1859
1860
1860 def get_new_name(self, repo_name):
1861 def get_new_name(self, repo_name):
1861 """
1862 """
1862 returns new full repository name based on assigned group and new new
1863 returns new full repository name based on assigned group and new new
1863
1864
1864 :param group_name:
1865 :param group_name:
1865 """
1866 """
1866 path_prefix = self.group.full_path_splitted if self.group else []
1867 path_prefix = self.group.full_path_splitted if self.group else []
1867 return self.NAME_SEP.join(path_prefix + [repo_name])
1868 return self.NAME_SEP.join(path_prefix + [repo_name])
1868
1869
1869 @property
1870 @property
1870 def _config(self):
1871 def _config(self):
1871 """
1872 """
1872 Returns db based config object.
1873 Returns db based config object.
1873 """
1874 """
1874 from rhodecode.lib.utils import make_db_config
1875 from rhodecode.lib.utils import make_db_config
1875 return make_db_config(clear_session=False, repo=self)
1876 return make_db_config(clear_session=False, repo=self)
1876
1877
1877 def permissions(self, with_admins=True, with_owner=True):
1878 def permissions(self, with_admins=True, with_owner=True):
1878 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1879 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1879 q = q.options(joinedload(UserRepoToPerm.repository),
1880 q = q.options(joinedload(UserRepoToPerm.repository),
1880 joinedload(UserRepoToPerm.user),
1881 joinedload(UserRepoToPerm.user),
1881 joinedload(UserRepoToPerm.permission),)
1882 joinedload(UserRepoToPerm.permission),)
1882
1883
1883 # get owners and admins and permissions. We do a trick of re-writing
1884 # get owners and admins and permissions. We do a trick of re-writing
1884 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1885 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1885 # has a global reference and changing one object propagates to all
1886 # has a global reference and changing one object propagates to all
1886 # others. This means if admin is also an owner admin_row that change
1887 # others. This means if admin is also an owner admin_row that change
1887 # would propagate to both objects
1888 # would propagate to both objects
1888 perm_rows = []
1889 perm_rows = []
1889 for _usr in q.all():
1890 for _usr in q.all():
1890 usr = AttributeDict(_usr.user.get_dict())
1891 usr = AttributeDict(_usr.user.get_dict())
1891 usr.permission = _usr.permission.permission_name
1892 usr.permission = _usr.permission.permission_name
1892 perm_rows.append(usr)
1893 perm_rows.append(usr)
1893
1894
1894 # filter the perm rows by 'default' first and then sort them by
1895 # filter the perm rows by 'default' first and then sort them by
1895 # admin,write,read,none permissions sorted again alphabetically in
1896 # admin,write,read,none permissions sorted again alphabetically in
1896 # each group
1897 # each group
1897 perm_rows = sorted(perm_rows, key=display_user_sort)
1898 perm_rows = sorted(perm_rows, key=display_user_sort)
1898
1899
1899 _admin_perm = 'repository.admin'
1900 _admin_perm = 'repository.admin'
1900 owner_row = []
1901 owner_row = []
1901 if with_owner:
1902 if with_owner:
1902 usr = AttributeDict(self.user.get_dict())
1903 usr = AttributeDict(self.user.get_dict())
1903 usr.owner_row = True
1904 usr.owner_row = True
1904 usr.permission = _admin_perm
1905 usr.permission = _admin_perm
1905 owner_row.append(usr)
1906 owner_row.append(usr)
1906
1907
1907 super_admin_rows = []
1908 super_admin_rows = []
1908 if with_admins:
1909 if with_admins:
1909 for usr in User.get_all_super_admins():
1910 for usr in User.get_all_super_admins():
1910 # if this admin is also owner, don't double the record
1911 # if this admin is also owner, don't double the record
1911 if usr.user_id == owner_row[0].user_id:
1912 if usr.user_id == owner_row[0].user_id:
1912 owner_row[0].admin_row = True
1913 owner_row[0].admin_row = True
1913 else:
1914 else:
1914 usr = AttributeDict(usr.get_dict())
1915 usr = AttributeDict(usr.get_dict())
1915 usr.admin_row = True
1916 usr.admin_row = True
1916 usr.permission = _admin_perm
1917 usr.permission = _admin_perm
1917 super_admin_rows.append(usr)
1918 super_admin_rows.append(usr)
1918
1919
1919 return super_admin_rows + owner_row + perm_rows
1920 return super_admin_rows + owner_row + perm_rows
1920
1921
1921 def permission_user_groups(self):
1922 def permission_user_groups(self):
1922 q = UserGroupRepoToPerm.query().filter(
1923 q = UserGroupRepoToPerm.query().filter(
1923 UserGroupRepoToPerm.repository == self)
1924 UserGroupRepoToPerm.repository == self)
1924 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1925 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1925 joinedload(UserGroupRepoToPerm.users_group),
1926 joinedload(UserGroupRepoToPerm.users_group),
1926 joinedload(UserGroupRepoToPerm.permission),)
1927 joinedload(UserGroupRepoToPerm.permission),)
1927
1928
1928 perm_rows = []
1929 perm_rows = []
1929 for _user_group in q.all():
1930 for _user_group in q.all():
1930 usr = AttributeDict(_user_group.users_group.get_dict())
1931 usr = AttributeDict(_user_group.users_group.get_dict())
1931 usr.permission = _user_group.permission.permission_name
1932 usr.permission = _user_group.permission.permission_name
1932 perm_rows.append(usr)
1933 perm_rows.append(usr)
1933
1934
1934 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1935 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1935 return perm_rows
1936 return perm_rows
1936
1937
1937 def get_api_data(self, include_secrets=False):
1938 def get_api_data(self, include_secrets=False):
1938 """
1939 """
1939 Common function for generating repo api data
1940 Common function for generating repo api data
1940
1941
1941 :param include_secrets: See :meth:`User.get_api_data`.
1942 :param include_secrets: See :meth:`User.get_api_data`.
1942
1943
1943 """
1944 """
1944 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1945 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1945 # move this methods on models level.
1946 # move this methods on models level.
1946 from rhodecode.model.settings import SettingsModel
1947 from rhodecode.model.settings import SettingsModel
1947 from rhodecode.model.repo import RepoModel
1948 from rhodecode.model.repo import RepoModel
1948
1949
1949 repo = self
1950 repo = self
1950 _user_id, _time, _reason = self.locked
1951 _user_id, _time, _reason = self.locked
1951
1952
1952 data = {
1953 data = {
1953 'repo_id': repo.repo_id,
1954 'repo_id': repo.repo_id,
1954 'repo_name': repo.repo_name,
1955 'repo_name': repo.repo_name,
1955 'repo_type': repo.repo_type,
1956 'repo_type': repo.repo_type,
1956 'clone_uri': repo.clone_uri or '',
1957 'clone_uri': repo.clone_uri or '',
1957 'url': RepoModel().get_url(self),
1958 'url': RepoModel().get_url(self),
1958 'private': repo.private,
1959 'private': repo.private,
1959 'created_on': repo.created_on,
1960 'created_on': repo.created_on,
1960 'description': repo.description_safe,
1961 'description': repo.description_safe,
1961 'landing_rev': repo.landing_rev,
1962 'landing_rev': repo.landing_rev,
1962 'owner': repo.user.username,
1963 'owner': repo.user.username,
1963 'fork_of': repo.fork.repo_name if repo.fork else None,
1964 'fork_of': repo.fork.repo_name if repo.fork else None,
1964 'fork_of_id': repo.fork.repo_id if repo.fork else None,
1965 'fork_of_id': repo.fork.repo_id if repo.fork else None,
1965 'enable_statistics': repo.enable_statistics,
1966 'enable_statistics': repo.enable_statistics,
1966 'enable_locking': repo.enable_locking,
1967 'enable_locking': repo.enable_locking,
1967 'enable_downloads': repo.enable_downloads,
1968 'enable_downloads': repo.enable_downloads,
1968 'last_changeset': repo.changeset_cache,
1969 'last_changeset': repo.changeset_cache,
1969 'locked_by': User.get(_user_id).get_api_data(
1970 'locked_by': User.get(_user_id).get_api_data(
1970 include_secrets=include_secrets) if _user_id else None,
1971 include_secrets=include_secrets) if _user_id else None,
1971 'locked_date': time_to_datetime(_time) if _time else None,
1972 'locked_date': time_to_datetime(_time) if _time else None,
1972 'lock_reason': _reason if _reason else None,
1973 'lock_reason': _reason if _reason else None,
1973 }
1974 }
1974
1975
1975 # TODO: mikhail: should be per-repo settings here
1976 # TODO: mikhail: should be per-repo settings here
1976 rc_config = SettingsModel().get_all_settings()
1977 rc_config = SettingsModel().get_all_settings()
1977 repository_fields = str2bool(
1978 repository_fields = str2bool(
1978 rc_config.get('rhodecode_repository_fields'))
1979 rc_config.get('rhodecode_repository_fields'))
1979 if repository_fields:
1980 if repository_fields:
1980 for f in self.extra_fields:
1981 for f in self.extra_fields:
1981 data[f.field_key_prefixed] = f.field_value
1982 data[f.field_key_prefixed] = f.field_value
1982
1983
1983 return data
1984 return data
1984
1985
1985 @classmethod
1986 @classmethod
1986 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1987 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1987 if not lock_time:
1988 if not lock_time:
1988 lock_time = time.time()
1989 lock_time = time.time()
1989 if not lock_reason:
1990 if not lock_reason:
1990 lock_reason = cls.LOCK_AUTOMATIC
1991 lock_reason = cls.LOCK_AUTOMATIC
1991 repo.locked = [user_id, lock_time, lock_reason]
1992 repo.locked = [user_id, lock_time, lock_reason]
1992 Session().add(repo)
1993 Session().add(repo)
1993 Session().commit()
1994 Session().commit()
1994
1995
1995 @classmethod
1996 @classmethod
1996 def unlock(cls, repo):
1997 def unlock(cls, repo):
1997 repo.locked = None
1998 repo.locked = None
1998 Session().add(repo)
1999 Session().add(repo)
1999 Session().commit()
2000 Session().commit()
2000
2001
2001 @classmethod
2002 @classmethod
2002 def getlock(cls, repo):
2003 def getlock(cls, repo):
2003 return repo.locked
2004 return repo.locked
2004
2005
2005 def is_user_lock(self, user_id):
2006 def is_user_lock(self, user_id):
2006 if self.lock[0]:
2007 if self.lock[0]:
2007 lock_user_id = safe_int(self.lock[0])
2008 lock_user_id = safe_int(self.lock[0])
2008 user_id = safe_int(user_id)
2009 user_id = safe_int(user_id)
2009 # both are ints, and they are equal
2010 # both are ints, and they are equal
2010 return all([lock_user_id, user_id]) and lock_user_id == user_id
2011 return all([lock_user_id, user_id]) and lock_user_id == user_id
2011
2012
2012 return False
2013 return False
2013
2014
2014 def get_locking_state(self, action, user_id, only_when_enabled=True):
2015 def get_locking_state(self, action, user_id, only_when_enabled=True):
2015 """
2016 """
2016 Checks locking on this repository, if locking is enabled and lock is
2017 Checks locking on this repository, if locking is enabled and lock is
2017 present returns a tuple of make_lock, locked, locked_by.
2018 present returns a tuple of make_lock, locked, locked_by.
2018 make_lock can have 3 states None (do nothing) True, make lock
2019 make_lock can have 3 states None (do nothing) True, make lock
2019 False release lock, This value is later propagated to hooks, which
2020 False release lock, This value is later propagated to hooks, which
2020 do the locking. Think about this as signals passed to hooks what to do.
2021 do the locking. Think about this as signals passed to hooks what to do.
2021
2022
2022 """
2023 """
2023 # TODO: johbo: This is part of the business logic and should be moved
2024 # TODO: johbo: This is part of the business logic and should be moved
2024 # into the RepositoryModel.
2025 # into the RepositoryModel.
2025
2026
2026 if action not in ('push', 'pull'):
2027 if action not in ('push', 'pull'):
2027 raise ValueError("Invalid action value: %s" % repr(action))
2028 raise ValueError("Invalid action value: %s" % repr(action))
2028
2029
2029 # defines if locked error should be thrown to user
2030 # defines if locked error should be thrown to user
2030 currently_locked = False
2031 currently_locked = False
2031 # defines if new lock should be made, tri-state
2032 # defines if new lock should be made, tri-state
2032 make_lock = None
2033 make_lock = None
2033 repo = self
2034 repo = self
2034 user = User.get(user_id)
2035 user = User.get(user_id)
2035
2036
2036 lock_info = repo.locked
2037 lock_info = repo.locked
2037
2038
2038 if repo and (repo.enable_locking or not only_when_enabled):
2039 if repo and (repo.enable_locking or not only_when_enabled):
2039 if action == 'push':
2040 if action == 'push':
2040 # check if it's already locked !, if it is compare users
2041 # check if it's already locked !, if it is compare users
2041 locked_by_user_id = lock_info[0]
2042 locked_by_user_id = lock_info[0]
2042 if user.user_id == locked_by_user_id:
2043 if user.user_id == locked_by_user_id:
2043 log.debug(
2044 log.debug(
2044 'Got `push` action from user %s, now unlocking', user)
2045 'Got `push` action from user %s, now unlocking', user)
2045 # unlock if we have push from user who locked
2046 # unlock if we have push from user who locked
2046 make_lock = False
2047 make_lock = False
2047 else:
2048 else:
2048 # we're not the same user who locked, ban with
2049 # we're not the same user who locked, ban with
2049 # code defined in settings (default is 423 HTTP Locked) !
2050 # code defined in settings (default is 423 HTTP Locked) !
2050 log.debug('Repo %s is currently locked by %s', repo, user)
2051 log.debug('Repo %s is currently locked by %s', repo, user)
2051 currently_locked = True
2052 currently_locked = True
2052 elif action == 'pull':
2053 elif action == 'pull':
2053 # [0] user [1] date
2054 # [0] user [1] date
2054 if lock_info[0] and lock_info[1]:
2055 if lock_info[0] and lock_info[1]:
2055 log.debug('Repo %s is currently locked by %s', repo, user)
2056 log.debug('Repo %s is currently locked by %s', repo, user)
2056 currently_locked = True
2057 currently_locked = True
2057 else:
2058 else:
2058 log.debug('Setting lock on repo %s by %s', repo, user)
2059 log.debug('Setting lock on repo %s by %s', repo, user)
2059 make_lock = True
2060 make_lock = True
2060
2061
2061 else:
2062 else:
2062 log.debug('Repository %s do not have locking enabled', repo)
2063 log.debug('Repository %s do not have locking enabled', repo)
2063
2064
2064 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2065 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2065 make_lock, currently_locked, lock_info)
2066 make_lock, currently_locked, lock_info)
2066
2067
2067 from rhodecode.lib.auth import HasRepoPermissionAny
2068 from rhodecode.lib.auth import HasRepoPermissionAny
2068 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2069 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2069 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2070 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2070 # if we don't have at least write permission we cannot make a lock
2071 # if we don't have at least write permission we cannot make a lock
2071 log.debug('lock state reset back to FALSE due to lack '
2072 log.debug('lock state reset back to FALSE due to lack '
2072 'of at least read permission')
2073 'of at least read permission')
2073 make_lock = False
2074 make_lock = False
2074
2075
2075 return make_lock, currently_locked, lock_info
2076 return make_lock, currently_locked, lock_info
2076
2077
2077 @property
2078 @property
2078 def last_db_change(self):
2079 def last_db_change(self):
2079 return self.updated_on
2080 return self.updated_on
2080
2081
2081 @property
2082 @property
2082 def clone_uri_hidden(self):
2083 def clone_uri_hidden(self):
2083 clone_uri = self.clone_uri
2084 clone_uri = self.clone_uri
2084 if clone_uri:
2085 if clone_uri:
2085 import urlobject
2086 import urlobject
2086 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2087 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2087 if url_obj.password:
2088 if url_obj.password:
2088 clone_uri = url_obj.with_password('*****')
2089 clone_uri = url_obj.with_password('*****')
2089 return clone_uri
2090 return clone_uri
2090
2091
2091 def clone_url(self, **override):
2092 def clone_url(self, **override):
2092 from rhodecode.model.settings import SettingsModel
2093 from rhodecode.model.settings import SettingsModel
2093
2094
2094 uri_tmpl = None
2095 uri_tmpl = None
2095 if 'with_id' in override:
2096 if 'with_id' in override:
2096 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2097 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2097 del override['with_id']
2098 del override['with_id']
2098
2099
2099 if 'uri_tmpl' in override:
2100 if 'uri_tmpl' in override:
2100 uri_tmpl = override['uri_tmpl']
2101 uri_tmpl = override['uri_tmpl']
2101 del override['uri_tmpl']
2102 del override['uri_tmpl']
2102
2103
2104 ssh = False
2105 if 'ssh' in override:
2106 ssh = True
2107 del override['ssh']
2108
2103 # we didn't override our tmpl from **overrides
2109 # we didn't override our tmpl from **overrides
2104 if not uri_tmpl:
2110 if not uri_tmpl:
2105 rc_config = SettingsModel().get_all_settings(cache=True)
2111 rc_config = SettingsModel().get_all_settings(cache=True)
2106 uri_tmpl = rc_config.get(
2112 if ssh:
2107 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2113 uri_tmpl = rc_config.get(
2114 'rhodecode_clone_uri_ssh_tmpl') or self.DEFAULT_CLONE_URI_SSH
2115 else:
2116 uri_tmpl = rc_config.get(
2117 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2108
2118
2109 request = get_current_request()
2119 request = get_current_request()
2110 return get_clone_url(request=request,
2120 return get_clone_url(request=request,
2111 uri_tmpl=uri_tmpl,
2121 uri_tmpl=uri_tmpl,
2112 repo_name=self.repo_name,
2122 repo_name=self.repo_name,
2113 repo_id=self.repo_id, **override)
2123 repo_id=self.repo_id, **override)
2114
2124
2115 def set_state(self, state):
2125 def set_state(self, state):
2116 self.repo_state = state
2126 self.repo_state = state
2117 Session().add(self)
2127 Session().add(self)
2118 #==========================================================================
2128 #==========================================================================
2119 # SCM PROPERTIES
2129 # SCM PROPERTIES
2120 #==========================================================================
2130 #==========================================================================
2121
2131
2122 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2132 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2123 return get_commit_safe(
2133 return get_commit_safe(
2124 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2134 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2125
2135
2126 def get_changeset(self, rev=None, pre_load=None):
2136 def get_changeset(self, rev=None, pre_load=None):
2127 warnings.warn("Use get_commit", DeprecationWarning)
2137 warnings.warn("Use get_commit", DeprecationWarning)
2128 commit_id = None
2138 commit_id = None
2129 commit_idx = None
2139 commit_idx = None
2130 if isinstance(rev, basestring):
2140 if isinstance(rev, basestring):
2131 commit_id = rev
2141 commit_id = rev
2132 else:
2142 else:
2133 commit_idx = rev
2143 commit_idx = rev
2134 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2144 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2135 pre_load=pre_load)
2145 pre_load=pre_load)
2136
2146
2137 def get_landing_commit(self):
2147 def get_landing_commit(self):
2138 """
2148 """
2139 Returns landing commit, or if that doesn't exist returns the tip
2149 Returns landing commit, or if that doesn't exist returns the tip
2140 """
2150 """
2141 _rev_type, _rev = self.landing_rev
2151 _rev_type, _rev = self.landing_rev
2142 commit = self.get_commit(_rev)
2152 commit = self.get_commit(_rev)
2143 if isinstance(commit, EmptyCommit):
2153 if isinstance(commit, EmptyCommit):
2144 return self.get_commit()
2154 return self.get_commit()
2145 return commit
2155 return commit
2146
2156
2147 def update_commit_cache(self, cs_cache=None, config=None):
2157 def update_commit_cache(self, cs_cache=None, config=None):
2148 """
2158 """
2149 Update cache of last changeset for repository, keys should be::
2159 Update cache of last changeset for repository, keys should be::
2150
2160
2151 short_id
2161 short_id
2152 raw_id
2162 raw_id
2153 revision
2163 revision
2154 parents
2164 parents
2155 message
2165 message
2156 date
2166 date
2157 author
2167 author
2158
2168
2159 :param cs_cache:
2169 :param cs_cache:
2160 """
2170 """
2161 from rhodecode.lib.vcs.backends.base import BaseChangeset
2171 from rhodecode.lib.vcs.backends.base import BaseChangeset
2162 if cs_cache is None:
2172 if cs_cache is None:
2163 # use no-cache version here
2173 # use no-cache version here
2164 scm_repo = self.scm_instance(cache=False, config=config)
2174 scm_repo = self.scm_instance(cache=False, config=config)
2165 if scm_repo:
2175 if scm_repo:
2166 cs_cache = scm_repo.get_commit(
2176 cs_cache = scm_repo.get_commit(
2167 pre_load=["author", "date", "message", "parents"])
2177 pre_load=["author", "date", "message", "parents"])
2168 else:
2178 else:
2169 cs_cache = EmptyCommit()
2179 cs_cache = EmptyCommit()
2170
2180
2171 if isinstance(cs_cache, BaseChangeset):
2181 if isinstance(cs_cache, BaseChangeset):
2172 cs_cache = cs_cache.__json__()
2182 cs_cache = cs_cache.__json__()
2173
2183
2174 def is_outdated(new_cs_cache):
2184 def is_outdated(new_cs_cache):
2175 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2185 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2176 new_cs_cache['revision'] != self.changeset_cache['revision']):
2186 new_cs_cache['revision'] != self.changeset_cache['revision']):
2177 return True
2187 return True
2178 return False
2188 return False
2179
2189
2180 # check if we have maybe already latest cached revision
2190 # check if we have maybe already latest cached revision
2181 if is_outdated(cs_cache) or not self.changeset_cache:
2191 if is_outdated(cs_cache) or not self.changeset_cache:
2182 _default = datetime.datetime.fromtimestamp(0)
2192 _default = datetime.datetime.fromtimestamp(0)
2183 last_change = cs_cache.get('date') or _default
2193 last_change = cs_cache.get('date') or _default
2184 log.debug('updated repo %s with new cs cache %s',
2194 log.debug('updated repo %s with new cs cache %s',
2185 self.repo_name, cs_cache)
2195 self.repo_name, cs_cache)
2186 self.updated_on = last_change
2196 self.updated_on = last_change
2187 self.changeset_cache = cs_cache
2197 self.changeset_cache = cs_cache
2188 Session().add(self)
2198 Session().add(self)
2189 Session().commit()
2199 Session().commit()
2190 else:
2200 else:
2191 log.debug('Skipping update_commit_cache for repo:`%s` '
2201 log.debug('Skipping update_commit_cache for repo:`%s` '
2192 'commit already with latest changes', self.repo_name)
2202 'commit already with latest changes', self.repo_name)
2193
2203
2194 @property
2204 @property
2195 def tip(self):
2205 def tip(self):
2196 return self.get_commit('tip')
2206 return self.get_commit('tip')
2197
2207
2198 @property
2208 @property
2199 def author(self):
2209 def author(self):
2200 return self.tip.author
2210 return self.tip.author
2201
2211
2202 @property
2212 @property
2203 def last_change(self):
2213 def last_change(self):
2204 return self.scm_instance().last_change
2214 return self.scm_instance().last_change
2205
2215
2206 def get_comments(self, revisions=None):
2216 def get_comments(self, revisions=None):
2207 """
2217 """
2208 Returns comments for this repository grouped by revisions
2218 Returns comments for this repository grouped by revisions
2209
2219
2210 :param revisions: filter query by revisions only
2220 :param revisions: filter query by revisions only
2211 """
2221 """
2212 cmts = ChangesetComment.query()\
2222 cmts = ChangesetComment.query()\
2213 .filter(ChangesetComment.repo == self)
2223 .filter(ChangesetComment.repo == self)
2214 if revisions:
2224 if revisions:
2215 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2225 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2216 grouped = collections.defaultdict(list)
2226 grouped = collections.defaultdict(list)
2217 for cmt in cmts.all():
2227 for cmt in cmts.all():
2218 grouped[cmt.revision].append(cmt)
2228 grouped[cmt.revision].append(cmt)
2219 return grouped
2229 return grouped
2220
2230
2221 def statuses(self, revisions=None):
2231 def statuses(self, revisions=None):
2222 """
2232 """
2223 Returns statuses for this repository
2233 Returns statuses for this repository
2224
2234
2225 :param revisions: list of revisions to get statuses for
2235 :param revisions: list of revisions to get statuses for
2226 """
2236 """
2227 statuses = ChangesetStatus.query()\
2237 statuses = ChangesetStatus.query()\
2228 .filter(ChangesetStatus.repo == self)\
2238 .filter(ChangesetStatus.repo == self)\
2229 .filter(ChangesetStatus.version == 0)
2239 .filter(ChangesetStatus.version == 0)
2230
2240
2231 if revisions:
2241 if revisions:
2232 # Try doing the filtering in chunks to avoid hitting limits
2242 # Try doing the filtering in chunks to avoid hitting limits
2233 size = 500
2243 size = 500
2234 status_results = []
2244 status_results = []
2235 for chunk in xrange(0, len(revisions), size):
2245 for chunk in xrange(0, len(revisions), size):
2236 status_results += statuses.filter(
2246 status_results += statuses.filter(
2237 ChangesetStatus.revision.in_(
2247 ChangesetStatus.revision.in_(
2238 revisions[chunk: chunk+size])
2248 revisions[chunk: chunk+size])
2239 ).all()
2249 ).all()
2240 else:
2250 else:
2241 status_results = statuses.all()
2251 status_results = statuses.all()
2242
2252
2243 grouped = {}
2253 grouped = {}
2244
2254
2245 # maybe we have open new pullrequest without a status?
2255 # maybe we have open new pullrequest without a status?
2246 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2256 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2247 status_lbl = ChangesetStatus.get_status_lbl(stat)
2257 status_lbl = ChangesetStatus.get_status_lbl(stat)
2248 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2258 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2249 for rev in pr.revisions:
2259 for rev in pr.revisions:
2250 pr_id = pr.pull_request_id
2260 pr_id = pr.pull_request_id
2251 pr_repo = pr.target_repo.repo_name
2261 pr_repo = pr.target_repo.repo_name
2252 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2262 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2253
2263
2254 for stat in status_results:
2264 for stat in status_results:
2255 pr_id = pr_repo = None
2265 pr_id = pr_repo = None
2256 if stat.pull_request:
2266 if stat.pull_request:
2257 pr_id = stat.pull_request.pull_request_id
2267 pr_id = stat.pull_request.pull_request_id
2258 pr_repo = stat.pull_request.target_repo.repo_name
2268 pr_repo = stat.pull_request.target_repo.repo_name
2259 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2269 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2260 pr_id, pr_repo]
2270 pr_id, pr_repo]
2261 return grouped
2271 return grouped
2262
2272
2263 # ==========================================================================
2273 # ==========================================================================
2264 # SCM CACHE INSTANCE
2274 # SCM CACHE INSTANCE
2265 # ==========================================================================
2275 # ==========================================================================
2266
2276
2267 def scm_instance(self, **kwargs):
2277 def scm_instance(self, **kwargs):
2268 import rhodecode
2278 import rhodecode
2269
2279
2270 # Passing a config will not hit the cache currently only used
2280 # Passing a config will not hit the cache currently only used
2271 # for repo2dbmapper
2281 # for repo2dbmapper
2272 config = kwargs.pop('config', None)
2282 config = kwargs.pop('config', None)
2273 cache = kwargs.pop('cache', None)
2283 cache = kwargs.pop('cache', None)
2274 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2284 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2275 # if cache is NOT defined use default global, else we have a full
2285 # if cache is NOT defined use default global, else we have a full
2276 # control over cache behaviour
2286 # control over cache behaviour
2277 if cache is None and full_cache and not config:
2287 if cache is None and full_cache and not config:
2278 return self._get_instance_cached()
2288 return self._get_instance_cached()
2279 return self._get_instance(cache=bool(cache), config=config)
2289 return self._get_instance(cache=bool(cache), config=config)
2280
2290
2281 def _get_instance_cached(self):
2291 def _get_instance_cached(self):
2282 @cache_region('long_term')
2292 @cache_region('long_term')
2283 def _get_repo(cache_key):
2293 def _get_repo(cache_key):
2284 return self._get_instance()
2294 return self._get_instance()
2285
2295
2286 invalidator_context = CacheKey.repo_context_cache(
2296 invalidator_context = CacheKey.repo_context_cache(
2287 _get_repo, self.repo_name, None, thread_scoped=True)
2297 _get_repo, self.repo_name, None, thread_scoped=True)
2288
2298
2289 with invalidator_context as context:
2299 with invalidator_context as context:
2290 context.invalidate()
2300 context.invalidate()
2291 repo = context.compute()
2301 repo = context.compute()
2292
2302
2293 return repo
2303 return repo
2294
2304
2295 def _get_instance(self, cache=True, config=None):
2305 def _get_instance(self, cache=True, config=None):
2296 config = config or self._config
2306 config = config or self._config
2297 custom_wire = {
2307 custom_wire = {
2298 'cache': cache # controls the vcs.remote cache
2308 'cache': cache # controls the vcs.remote cache
2299 }
2309 }
2300 repo = get_vcs_instance(
2310 repo = get_vcs_instance(
2301 repo_path=safe_str(self.repo_full_path),
2311 repo_path=safe_str(self.repo_full_path),
2302 config=config,
2312 config=config,
2303 with_wire=custom_wire,
2313 with_wire=custom_wire,
2304 create=False,
2314 create=False,
2305 _vcs_alias=self.repo_type)
2315 _vcs_alias=self.repo_type)
2306
2316
2307 return repo
2317 return repo
2308
2318
2309 def __json__(self):
2319 def __json__(self):
2310 return {'landing_rev': self.landing_rev}
2320 return {'landing_rev': self.landing_rev}
2311
2321
2312 def get_dict(self):
2322 def get_dict(self):
2313
2323
2314 # Since we transformed `repo_name` to a hybrid property, we need to
2324 # Since we transformed `repo_name` to a hybrid property, we need to
2315 # keep compatibility with the code which uses `repo_name` field.
2325 # keep compatibility with the code which uses `repo_name` field.
2316
2326
2317 result = super(Repository, self).get_dict()
2327 result = super(Repository, self).get_dict()
2318 result['repo_name'] = result.pop('_repo_name', None)
2328 result['repo_name'] = result.pop('_repo_name', None)
2319 return result
2329 return result
2320
2330
2321
2331
2322 class RepoGroup(Base, BaseModel):
2332 class RepoGroup(Base, BaseModel):
2323 __tablename__ = 'groups'
2333 __tablename__ = 'groups'
2324 __table_args__ = (
2334 __table_args__ = (
2325 UniqueConstraint('group_name', 'group_parent_id'),
2335 UniqueConstraint('group_name', 'group_parent_id'),
2326 CheckConstraint('group_id != group_parent_id'),
2336 CheckConstraint('group_id != group_parent_id'),
2327 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2337 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2328 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2338 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2329 )
2339 )
2330 __mapper_args__ = {'order_by': 'group_name'}
2340 __mapper_args__ = {'order_by': 'group_name'}
2331
2341
2332 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2342 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2333
2343
2334 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2344 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2335 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2345 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2336 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2346 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2337 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2347 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2338 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2348 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2339 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2349 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2340 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2350 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2341 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2351 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2342 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2352 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2343
2353
2344 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2354 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2345 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2355 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2346 parent_group = relationship('RepoGroup', remote_side=group_id)
2356 parent_group = relationship('RepoGroup', remote_side=group_id)
2347 user = relationship('User')
2357 user = relationship('User')
2348 integrations = relationship('Integration',
2358 integrations = relationship('Integration',
2349 cascade="all, delete, delete-orphan")
2359 cascade="all, delete, delete-orphan")
2350
2360
2351 def __init__(self, group_name='', parent_group=None):
2361 def __init__(self, group_name='', parent_group=None):
2352 self.group_name = group_name
2362 self.group_name = group_name
2353 self.parent_group = parent_group
2363 self.parent_group = parent_group
2354
2364
2355 def __unicode__(self):
2365 def __unicode__(self):
2356 return u"<%s('id:%s:%s')>" % (
2366 return u"<%s('id:%s:%s')>" % (
2357 self.__class__.__name__, self.group_id, self.group_name)
2367 self.__class__.__name__, self.group_id, self.group_name)
2358
2368
2359 @hybrid_property
2369 @hybrid_property
2360 def description_safe(self):
2370 def description_safe(self):
2361 from rhodecode.lib import helpers as h
2371 from rhodecode.lib import helpers as h
2362 return h.escape(self.group_description)
2372 return h.escape(self.group_description)
2363
2373
2364 @classmethod
2374 @classmethod
2365 def _generate_choice(cls, repo_group):
2375 def _generate_choice(cls, repo_group):
2366 from webhelpers.html import literal as _literal
2376 from webhelpers.html import literal as _literal
2367 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2377 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2368 return repo_group.group_id, _name(repo_group.full_path_splitted)
2378 return repo_group.group_id, _name(repo_group.full_path_splitted)
2369
2379
2370 @classmethod
2380 @classmethod
2371 def groups_choices(cls, groups=None, show_empty_group=True):
2381 def groups_choices(cls, groups=None, show_empty_group=True):
2372 if not groups:
2382 if not groups:
2373 groups = cls.query().all()
2383 groups = cls.query().all()
2374
2384
2375 repo_groups = []
2385 repo_groups = []
2376 if show_empty_group:
2386 if show_empty_group:
2377 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2387 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2378
2388
2379 repo_groups.extend([cls._generate_choice(x) for x in groups])
2389 repo_groups.extend([cls._generate_choice(x) for x in groups])
2380
2390
2381 repo_groups = sorted(
2391 repo_groups = sorted(
2382 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2392 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2383 return repo_groups
2393 return repo_groups
2384
2394
2385 @classmethod
2395 @classmethod
2386 def url_sep(cls):
2396 def url_sep(cls):
2387 return URL_SEP
2397 return URL_SEP
2388
2398
2389 @classmethod
2399 @classmethod
2390 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2400 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2391 if case_insensitive:
2401 if case_insensitive:
2392 gr = cls.query().filter(func.lower(cls.group_name)
2402 gr = cls.query().filter(func.lower(cls.group_name)
2393 == func.lower(group_name))
2403 == func.lower(group_name))
2394 else:
2404 else:
2395 gr = cls.query().filter(cls.group_name == group_name)
2405 gr = cls.query().filter(cls.group_name == group_name)
2396 if cache:
2406 if cache:
2397 name_key = _hash_key(group_name)
2407 name_key = _hash_key(group_name)
2398 gr = gr.options(
2408 gr = gr.options(
2399 FromCache("sql_cache_short", "get_group_%s" % name_key))
2409 FromCache("sql_cache_short", "get_group_%s" % name_key))
2400 return gr.scalar()
2410 return gr.scalar()
2401
2411
2402 @classmethod
2412 @classmethod
2403 def get_user_personal_repo_group(cls, user_id):
2413 def get_user_personal_repo_group(cls, user_id):
2404 user = User.get(user_id)
2414 user = User.get(user_id)
2405 if user.username == User.DEFAULT_USER:
2415 if user.username == User.DEFAULT_USER:
2406 return None
2416 return None
2407
2417
2408 return cls.query()\
2418 return cls.query()\
2409 .filter(cls.personal == true()) \
2419 .filter(cls.personal == true()) \
2410 .filter(cls.user == user).scalar()
2420 .filter(cls.user == user).scalar()
2411
2421
2412 @classmethod
2422 @classmethod
2413 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2423 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2414 case_insensitive=True):
2424 case_insensitive=True):
2415 q = RepoGroup.query()
2425 q = RepoGroup.query()
2416
2426
2417 if not isinstance(user_id, Optional):
2427 if not isinstance(user_id, Optional):
2418 q = q.filter(RepoGroup.user_id == user_id)
2428 q = q.filter(RepoGroup.user_id == user_id)
2419
2429
2420 if not isinstance(group_id, Optional):
2430 if not isinstance(group_id, Optional):
2421 q = q.filter(RepoGroup.group_parent_id == group_id)
2431 q = q.filter(RepoGroup.group_parent_id == group_id)
2422
2432
2423 if case_insensitive:
2433 if case_insensitive:
2424 q = q.order_by(func.lower(RepoGroup.group_name))
2434 q = q.order_by(func.lower(RepoGroup.group_name))
2425 else:
2435 else:
2426 q = q.order_by(RepoGroup.group_name)
2436 q = q.order_by(RepoGroup.group_name)
2427 return q.all()
2437 return q.all()
2428
2438
2429 @property
2439 @property
2430 def parents(self):
2440 def parents(self):
2431 parents_recursion_limit = 10
2441 parents_recursion_limit = 10
2432 groups = []
2442 groups = []
2433 if self.parent_group is None:
2443 if self.parent_group is None:
2434 return groups
2444 return groups
2435 cur_gr = self.parent_group
2445 cur_gr = self.parent_group
2436 groups.insert(0, cur_gr)
2446 groups.insert(0, cur_gr)
2437 cnt = 0
2447 cnt = 0
2438 while 1:
2448 while 1:
2439 cnt += 1
2449 cnt += 1
2440 gr = getattr(cur_gr, 'parent_group', None)
2450 gr = getattr(cur_gr, 'parent_group', None)
2441 cur_gr = cur_gr.parent_group
2451 cur_gr = cur_gr.parent_group
2442 if gr is None:
2452 if gr is None:
2443 break
2453 break
2444 if cnt == parents_recursion_limit:
2454 if cnt == parents_recursion_limit:
2445 # this will prevent accidental infinit loops
2455 # this will prevent accidental infinit loops
2446 log.error(('more than %s parents found for group %s, stopping '
2456 log.error(('more than %s parents found for group %s, stopping '
2447 'recursive parent fetching' % (parents_recursion_limit, self)))
2457 'recursive parent fetching' % (parents_recursion_limit, self)))
2448 break
2458 break
2449
2459
2450 groups.insert(0, gr)
2460 groups.insert(0, gr)
2451 return groups
2461 return groups
2452
2462
2453 @property
2463 @property
2454 def last_db_change(self):
2464 def last_db_change(self):
2455 return self.updated_on
2465 return self.updated_on
2456
2466
2457 @property
2467 @property
2458 def children(self):
2468 def children(self):
2459 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2469 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2460
2470
2461 @property
2471 @property
2462 def name(self):
2472 def name(self):
2463 return self.group_name.split(RepoGroup.url_sep())[-1]
2473 return self.group_name.split(RepoGroup.url_sep())[-1]
2464
2474
2465 @property
2475 @property
2466 def full_path(self):
2476 def full_path(self):
2467 return self.group_name
2477 return self.group_name
2468
2478
2469 @property
2479 @property
2470 def full_path_splitted(self):
2480 def full_path_splitted(self):
2471 return self.group_name.split(RepoGroup.url_sep())
2481 return self.group_name.split(RepoGroup.url_sep())
2472
2482
2473 @property
2483 @property
2474 def repositories(self):
2484 def repositories(self):
2475 return Repository.query()\
2485 return Repository.query()\
2476 .filter(Repository.group == self)\
2486 .filter(Repository.group == self)\
2477 .order_by(Repository.repo_name)
2487 .order_by(Repository.repo_name)
2478
2488
2479 @property
2489 @property
2480 def repositories_recursive_count(self):
2490 def repositories_recursive_count(self):
2481 cnt = self.repositories.count()
2491 cnt = self.repositories.count()
2482
2492
2483 def children_count(group):
2493 def children_count(group):
2484 cnt = 0
2494 cnt = 0
2485 for child in group.children:
2495 for child in group.children:
2486 cnt += child.repositories.count()
2496 cnt += child.repositories.count()
2487 cnt += children_count(child)
2497 cnt += children_count(child)
2488 return cnt
2498 return cnt
2489
2499
2490 return cnt + children_count(self)
2500 return cnt + children_count(self)
2491
2501
2492 def _recursive_objects(self, include_repos=True):
2502 def _recursive_objects(self, include_repos=True):
2493 all_ = []
2503 all_ = []
2494
2504
2495 def _get_members(root_gr):
2505 def _get_members(root_gr):
2496 if include_repos:
2506 if include_repos:
2497 for r in root_gr.repositories:
2507 for r in root_gr.repositories:
2498 all_.append(r)
2508 all_.append(r)
2499 childs = root_gr.children.all()
2509 childs = root_gr.children.all()
2500 if childs:
2510 if childs:
2501 for gr in childs:
2511 for gr in childs:
2502 all_.append(gr)
2512 all_.append(gr)
2503 _get_members(gr)
2513 _get_members(gr)
2504
2514
2505 _get_members(self)
2515 _get_members(self)
2506 return [self] + all_
2516 return [self] + all_
2507
2517
2508 def recursive_groups_and_repos(self):
2518 def recursive_groups_and_repos(self):
2509 """
2519 """
2510 Recursive return all groups, with repositories in those groups
2520 Recursive return all groups, with repositories in those groups
2511 """
2521 """
2512 return self._recursive_objects()
2522 return self._recursive_objects()
2513
2523
2514 def recursive_groups(self):
2524 def recursive_groups(self):
2515 """
2525 """
2516 Returns all children groups for this group including children of children
2526 Returns all children groups for this group including children of children
2517 """
2527 """
2518 return self._recursive_objects(include_repos=False)
2528 return self._recursive_objects(include_repos=False)
2519
2529
2520 def get_new_name(self, group_name):
2530 def get_new_name(self, group_name):
2521 """
2531 """
2522 returns new full group name based on parent and new name
2532 returns new full group name based on parent and new name
2523
2533
2524 :param group_name:
2534 :param group_name:
2525 """
2535 """
2526 path_prefix = (self.parent_group.full_path_splitted if
2536 path_prefix = (self.parent_group.full_path_splitted if
2527 self.parent_group else [])
2537 self.parent_group else [])
2528 return RepoGroup.url_sep().join(path_prefix + [group_name])
2538 return RepoGroup.url_sep().join(path_prefix + [group_name])
2529
2539
2530 def permissions(self, with_admins=True, with_owner=True):
2540 def permissions(self, with_admins=True, with_owner=True):
2531 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2541 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2532 q = q.options(joinedload(UserRepoGroupToPerm.group),
2542 q = q.options(joinedload(UserRepoGroupToPerm.group),
2533 joinedload(UserRepoGroupToPerm.user),
2543 joinedload(UserRepoGroupToPerm.user),
2534 joinedload(UserRepoGroupToPerm.permission),)
2544 joinedload(UserRepoGroupToPerm.permission),)
2535
2545
2536 # get owners and admins and permissions. We do a trick of re-writing
2546 # get owners and admins and permissions. We do a trick of re-writing
2537 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2547 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2538 # has a global reference and changing one object propagates to all
2548 # has a global reference and changing one object propagates to all
2539 # others. This means if admin is also an owner admin_row that change
2549 # others. This means if admin is also an owner admin_row that change
2540 # would propagate to both objects
2550 # would propagate to both objects
2541 perm_rows = []
2551 perm_rows = []
2542 for _usr in q.all():
2552 for _usr in q.all():
2543 usr = AttributeDict(_usr.user.get_dict())
2553 usr = AttributeDict(_usr.user.get_dict())
2544 usr.permission = _usr.permission.permission_name
2554 usr.permission = _usr.permission.permission_name
2545 perm_rows.append(usr)
2555 perm_rows.append(usr)
2546
2556
2547 # filter the perm rows by 'default' first and then sort them by
2557 # filter the perm rows by 'default' first and then sort them by
2548 # admin,write,read,none permissions sorted again alphabetically in
2558 # admin,write,read,none permissions sorted again alphabetically in
2549 # each group
2559 # each group
2550 perm_rows = sorted(perm_rows, key=display_user_sort)
2560 perm_rows = sorted(perm_rows, key=display_user_sort)
2551
2561
2552 _admin_perm = 'group.admin'
2562 _admin_perm = 'group.admin'
2553 owner_row = []
2563 owner_row = []
2554 if with_owner:
2564 if with_owner:
2555 usr = AttributeDict(self.user.get_dict())
2565 usr = AttributeDict(self.user.get_dict())
2556 usr.owner_row = True
2566 usr.owner_row = True
2557 usr.permission = _admin_perm
2567 usr.permission = _admin_perm
2558 owner_row.append(usr)
2568 owner_row.append(usr)
2559
2569
2560 super_admin_rows = []
2570 super_admin_rows = []
2561 if with_admins:
2571 if with_admins:
2562 for usr in User.get_all_super_admins():
2572 for usr in User.get_all_super_admins():
2563 # if this admin is also owner, don't double the record
2573 # if this admin is also owner, don't double the record
2564 if usr.user_id == owner_row[0].user_id:
2574 if usr.user_id == owner_row[0].user_id:
2565 owner_row[0].admin_row = True
2575 owner_row[0].admin_row = True
2566 else:
2576 else:
2567 usr = AttributeDict(usr.get_dict())
2577 usr = AttributeDict(usr.get_dict())
2568 usr.admin_row = True
2578 usr.admin_row = True
2569 usr.permission = _admin_perm
2579 usr.permission = _admin_perm
2570 super_admin_rows.append(usr)
2580 super_admin_rows.append(usr)
2571
2581
2572 return super_admin_rows + owner_row + perm_rows
2582 return super_admin_rows + owner_row + perm_rows
2573
2583
2574 def permission_user_groups(self):
2584 def permission_user_groups(self):
2575 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2585 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2576 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2586 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2577 joinedload(UserGroupRepoGroupToPerm.users_group),
2587 joinedload(UserGroupRepoGroupToPerm.users_group),
2578 joinedload(UserGroupRepoGroupToPerm.permission),)
2588 joinedload(UserGroupRepoGroupToPerm.permission),)
2579
2589
2580 perm_rows = []
2590 perm_rows = []
2581 for _user_group in q.all():
2591 for _user_group in q.all():
2582 usr = AttributeDict(_user_group.users_group.get_dict())
2592 usr = AttributeDict(_user_group.users_group.get_dict())
2583 usr.permission = _user_group.permission.permission_name
2593 usr.permission = _user_group.permission.permission_name
2584 perm_rows.append(usr)
2594 perm_rows.append(usr)
2585
2595
2586 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2596 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2587 return perm_rows
2597 return perm_rows
2588
2598
2589 def get_api_data(self):
2599 def get_api_data(self):
2590 """
2600 """
2591 Common function for generating api data
2601 Common function for generating api data
2592
2602
2593 """
2603 """
2594 group = self
2604 group = self
2595 data = {
2605 data = {
2596 'group_id': group.group_id,
2606 'group_id': group.group_id,
2597 'group_name': group.group_name,
2607 'group_name': group.group_name,
2598 'group_description': group.description_safe,
2608 'group_description': group.description_safe,
2599 'parent_group': group.parent_group.group_name if group.parent_group else None,
2609 'parent_group': group.parent_group.group_name if group.parent_group else None,
2600 'repositories': [x.repo_name for x in group.repositories],
2610 'repositories': [x.repo_name for x in group.repositories],
2601 'owner': group.user.username,
2611 'owner': group.user.username,
2602 }
2612 }
2603 return data
2613 return data
2604
2614
2605
2615
2606 class Permission(Base, BaseModel):
2616 class Permission(Base, BaseModel):
2607 __tablename__ = 'permissions'
2617 __tablename__ = 'permissions'
2608 __table_args__ = (
2618 __table_args__ = (
2609 Index('p_perm_name_idx', 'permission_name'),
2619 Index('p_perm_name_idx', 'permission_name'),
2610 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2620 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2611 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2621 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2612 )
2622 )
2613 PERMS = [
2623 PERMS = [
2614 ('hg.admin', _('RhodeCode Super Administrator')),
2624 ('hg.admin', _('RhodeCode Super Administrator')),
2615
2625
2616 ('repository.none', _('Repository no access')),
2626 ('repository.none', _('Repository no access')),
2617 ('repository.read', _('Repository read access')),
2627 ('repository.read', _('Repository read access')),
2618 ('repository.write', _('Repository write access')),
2628 ('repository.write', _('Repository write access')),
2619 ('repository.admin', _('Repository admin access')),
2629 ('repository.admin', _('Repository admin access')),
2620
2630
2621 ('group.none', _('Repository group no access')),
2631 ('group.none', _('Repository group no access')),
2622 ('group.read', _('Repository group read access')),
2632 ('group.read', _('Repository group read access')),
2623 ('group.write', _('Repository group write access')),
2633 ('group.write', _('Repository group write access')),
2624 ('group.admin', _('Repository group admin access')),
2634 ('group.admin', _('Repository group admin access')),
2625
2635
2626 ('usergroup.none', _('User group no access')),
2636 ('usergroup.none', _('User group no access')),
2627 ('usergroup.read', _('User group read access')),
2637 ('usergroup.read', _('User group read access')),
2628 ('usergroup.write', _('User group write access')),
2638 ('usergroup.write', _('User group write access')),
2629 ('usergroup.admin', _('User group admin access')),
2639 ('usergroup.admin', _('User group admin access')),
2630
2640
2631 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2641 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2632 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2642 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2633
2643
2634 ('hg.usergroup.create.false', _('User Group creation disabled')),
2644 ('hg.usergroup.create.false', _('User Group creation disabled')),
2635 ('hg.usergroup.create.true', _('User Group creation enabled')),
2645 ('hg.usergroup.create.true', _('User Group creation enabled')),
2636
2646
2637 ('hg.create.none', _('Repository creation disabled')),
2647 ('hg.create.none', _('Repository creation disabled')),
2638 ('hg.create.repository', _('Repository creation enabled')),
2648 ('hg.create.repository', _('Repository creation enabled')),
2639 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2649 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2640 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2650 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2641
2651
2642 ('hg.fork.none', _('Repository forking disabled')),
2652 ('hg.fork.none', _('Repository forking disabled')),
2643 ('hg.fork.repository', _('Repository forking enabled')),
2653 ('hg.fork.repository', _('Repository forking enabled')),
2644
2654
2645 ('hg.register.none', _('Registration disabled')),
2655 ('hg.register.none', _('Registration disabled')),
2646 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2656 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2647 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2657 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2648
2658
2649 ('hg.password_reset.enabled', _('Password reset enabled')),
2659 ('hg.password_reset.enabled', _('Password reset enabled')),
2650 ('hg.password_reset.hidden', _('Password reset hidden')),
2660 ('hg.password_reset.hidden', _('Password reset hidden')),
2651 ('hg.password_reset.disabled', _('Password reset disabled')),
2661 ('hg.password_reset.disabled', _('Password reset disabled')),
2652
2662
2653 ('hg.extern_activate.manual', _('Manual activation of external account')),
2663 ('hg.extern_activate.manual', _('Manual activation of external account')),
2654 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2664 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2655
2665
2656 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2666 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2657 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2667 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2658 ]
2668 ]
2659
2669
2660 # definition of system default permissions for DEFAULT user
2670 # definition of system default permissions for DEFAULT user
2661 DEFAULT_USER_PERMISSIONS = [
2671 DEFAULT_USER_PERMISSIONS = [
2662 'repository.read',
2672 'repository.read',
2663 'group.read',
2673 'group.read',
2664 'usergroup.read',
2674 'usergroup.read',
2665 'hg.create.repository',
2675 'hg.create.repository',
2666 'hg.repogroup.create.false',
2676 'hg.repogroup.create.false',
2667 'hg.usergroup.create.false',
2677 'hg.usergroup.create.false',
2668 'hg.create.write_on_repogroup.true',
2678 'hg.create.write_on_repogroup.true',
2669 'hg.fork.repository',
2679 'hg.fork.repository',
2670 'hg.register.manual_activate',
2680 'hg.register.manual_activate',
2671 'hg.password_reset.enabled',
2681 'hg.password_reset.enabled',
2672 'hg.extern_activate.auto',
2682 'hg.extern_activate.auto',
2673 'hg.inherit_default_perms.true',
2683 'hg.inherit_default_perms.true',
2674 ]
2684 ]
2675
2685
2676 # defines which permissions are more important higher the more important
2686 # defines which permissions are more important higher the more important
2677 # Weight defines which permissions are more important.
2687 # Weight defines which permissions are more important.
2678 # The higher number the more important.
2688 # The higher number the more important.
2679 PERM_WEIGHTS = {
2689 PERM_WEIGHTS = {
2680 'repository.none': 0,
2690 'repository.none': 0,
2681 'repository.read': 1,
2691 'repository.read': 1,
2682 'repository.write': 3,
2692 'repository.write': 3,
2683 'repository.admin': 4,
2693 'repository.admin': 4,
2684
2694
2685 'group.none': 0,
2695 'group.none': 0,
2686 'group.read': 1,
2696 'group.read': 1,
2687 'group.write': 3,
2697 'group.write': 3,
2688 'group.admin': 4,
2698 'group.admin': 4,
2689
2699
2690 'usergroup.none': 0,
2700 'usergroup.none': 0,
2691 'usergroup.read': 1,
2701 'usergroup.read': 1,
2692 'usergroup.write': 3,
2702 'usergroup.write': 3,
2693 'usergroup.admin': 4,
2703 'usergroup.admin': 4,
2694
2704
2695 'hg.repogroup.create.false': 0,
2705 'hg.repogroup.create.false': 0,
2696 'hg.repogroup.create.true': 1,
2706 'hg.repogroup.create.true': 1,
2697
2707
2698 'hg.usergroup.create.false': 0,
2708 'hg.usergroup.create.false': 0,
2699 'hg.usergroup.create.true': 1,
2709 'hg.usergroup.create.true': 1,
2700
2710
2701 'hg.fork.none': 0,
2711 'hg.fork.none': 0,
2702 'hg.fork.repository': 1,
2712 'hg.fork.repository': 1,
2703 'hg.create.none': 0,
2713 'hg.create.none': 0,
2704 'hg.create.repository': 1
2714 'hg.create.repository': 1
2705 }
2715 }
2706
2716
2707 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2717 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2708 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2718 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2709 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2719 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2710
2720
2711 def __unicode__(self):
2721 def __unicode__(self):
2712 return u"<%s('%s:%s')>" % (
2722 return u"<%s('%s:%s')>" % (
2713 self.__class__.__name__, self.permission_id, self.permission_name
2723 self.__class__.__name__, self.permission_id, self.permission_name
2714 )
2724 )
2715
2725
2716 @classmethod
2726 @classmethod
2717 def get_by_key(cls, key):
2727 def get_by_key(cls, key):
2718 return cls.query().filter(cls.permission_name == key).scalar()
2728 return cls.query().filter(cls.permission_name == key).scalar()
2719
2729
2720 @classmethod
2730 @classmethod
2721 def get_default_repo_perms(cls, user_id, repo_id=None):
2731 def get_default_repo_perms(cls, user_id, repo_id=None):
2722 q = Session().query(UserRepoToPerm, Repository, Permission)\
2732 q = Session().query(UserRepoToPerm, Repository, Permission)\
2723 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2733 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2724 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2734 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2725 .filter(UserRepoToPerm.user_id == user_id)
2735 .filter(UserRepoToPerm.user_id == user_id)
2726 if repo_id:
2736 if repo_id:
2727 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2737 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2728 return q.all()
2738 return q.all()
2729
2739
2730 @classmethod
2740 @classmethod
2731 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2741 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2732 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2742 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2733 .join(
2743 .join(
2734 Permission,
2744 Permission,
2735 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2745 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2736 .join(
2746 .join(
2737 Repository,
2747 Repository,
2738 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2748 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2739 .join(
2749 .join(
2740 UserGroup,
2750 UserGroup,
2741 UserGroupRepoToPerm.users_group_id ==
2751 UserGroupRepoToPerm.users_group_id ==
2742 UserGroup.users_group_id)\
2752 UserGroup.users_group_id)\
2743 .join(
2753 .join(
2744 UserGroupMember,
2754 UserGroupMember,
2745 UserGroupRepoToPerm.users_group_id ==
2755 UserGroupRepoToPerm.users_group_id ==
2746 UserGroupMember.users_group_id)\
2756 UserGroupMember.users_group_id)\
2747 .filter(
2757 .filter(
2748 UserGroupMember.user_id == user_id,
2758 UserGroupMember.user_id == user_id,
2749 UserGroup.users_group_active == true())
2759 UserGroup.users_group_active == true())
2750 if repo_id:
2760 if repo_id:
2751 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2761 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2752 return q.all()
2762 return q.all()
2753
2763
2754 @classmethod
2764 @classmethod
2755 def get_default_group_perms(cls, user_id, repo_group_id=None):
2765 def get_default_group_perms(cls, user_id, repo_group_id=None):
2756 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2766 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2757 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2767 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2758 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2768 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2759 .filter(UserRepoGroupToPerm.user_id == user_id)
2769 .filter(UserRepoGroupToPerm.user_id == user_id)
2760 if repo_group_id:
2770 if repo_group_id:
2761 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2771 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2762 return q.all()
2772 return q.all()
2763
2773
2764 @classmethod
2774 @classmethod
2765 def get_default_group_perms_from_user_group(
2775 def get_default_group_perms_from_user_group(
2766 cls, user_id, repo_group_id=None):
2776 cls, user_id, repo_group_id=None):
2767 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2777 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2768 .join(
2778 .join(
2769 Permission,
2779 Permission,
2770 UserGroupRepoGroupToPerm.permission_id ==
2780 UserGroupRepoGroupToPerm.permission_id ==
2771 Permission.permission_id)\
2781 Permission.permission_id)\
2772 .join(
2782 .join(
2773 RepoGroup,
2783 RepoGroup,
2774 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2784 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2775 .join(
2785 .join(
2776 UserGroup,
2786 UserGroup,
2777 UserGroupRepoGroupToPerm.users_group_id ==
2787 UserGroupRepoGroupToPerm.users_group_id ==
2778 UserGroup.users_group_id)\
2788 UserGroup.users_group_id)\
2779 .join(
2789 .join(
2780 UserGroupMember,
2790 UserGroupMember,
2781 UserGroupRepoGroupToPerm.users_group_id ==
2791 UserGroupRepoGroupToPerm.users_group_id ==
2782 UserGroupMember.users_group_id)\
2792 UserGroupMember.users_group_id)\
2783 .filter(
2793 .filter(
2784 UserGroupMember.user_id == user_id,
2794 UserGroupMember.user_id == user_id,
2785 UserGroup.users_group_active == true())
2795 UserGroup.users_group_active == true())
2786 if repo_group_id:
2796 if repo_group_id:
2787 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2797 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2788 return q.all()
2798 return q.all()
2789
2799
2790 @classmethod
2800 @classmethod
2791 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2801 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2792 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2802 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2793 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2803 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2794 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2804 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2795 .filter(UserUserGroupToPerm.user_id == user_id)
2805 .filter(UserUserGroupToPerm.user_id == user_id)
2796 if user_group_id:
2806 if user_group_id:
2797 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2807 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2798 return q.all()
2808 return q.all()
2799
2809
2800 @classmethod
2810 @classmethod
2801 def get_default_user_group_perms_from_user_group(
2811 def get_default_user_group_perms_from_user_group(
2802 cls, user_id, user_group_id=None):
2812 cls, user_id, user_group_id=None):
2803 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2813 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2804 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2814 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2805 .join(
2815 .join(
2806 Permission,
2816 Permission,
2807 UserGroupUserGroupToPerm.permission_id ==
2817 UserGroupUserGroupToPerm.permission_id ==
2808 Permission.permission_id)\
2818 Permission.permission_id)\
2809 .join(
2819 .join(
2810 TargetUserGroup,
2820 TargetUserGroup,
2811 UserGroupUserGroupToPerm.target_user_group_id ==
2821 UserGroupUserGroupToPerm.target_user_group_id ==
2812 TargetUserGroup.users_group_id)\
2822 TargetUserGroup.users_group_id)\
2813 .join(
2823 .join(
2814 UserGroup,
2824 UserGroup,
2815 UserGroupUserGroupToPerm.user_group_id ==
2825 UserGroupUserGroupToPerm.user_group_id ==
2816 UserGroup.users_group_id)\
2826 UserGroup.users_group_id)\
2817 .join(
2827 .join(
2818 UserGroupMember,
2828 UserGroupMember,
2819 UserGroupUserGroupToPerm.user_group_id ==
2829 UserGroupUserGroupToPerm.user_group_id ==
2820 UserGroupMember.users_group_id)\
2830 UserGroupMember.users_group_id)\
2821 .filter(
2831 .filter(
2822 UserGroupMember.user_id == user_id,
2832 UserGroupMember.user_id == user_id,
2823 UserGroup.users_group_active == true())
2833 UserGroup.users_group_active == true())
2824 if user_group_id:
2834 if user_group_id:
2825 q = q.filter(
2835 q = q.filter(
2826 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2836 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2827
2837
2828 return q.all()
2838 return q.all()
2829
2839
2830
2840
2831 class UserRepoToPerm(Base, BaseModel):
2841 class UserRepoToPerm(Base, BaseModel):
2832 __tablename__ = 'repo_to_perm'
2842 __tablename__ = 'repo_to_perm'
2833 __table_args__ = (
2843 __table_args__ = (
2834 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2844 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2835 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2845 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2836 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2846 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2837 )
2847 )
2838 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2848 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2839 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2849 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2840 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2850 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2841 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2851 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2842
2852
2843 user = relationship('User')
2853 user = relationship('User')
2844 repository = relationship('Repository')
2854 repository = relationship('Repository')
2845 permission = relationship('Permission')
2855 permission = relationship('Permission')
2846
2856
2847 @classmethod
2857 @classmethod
2848 def create(cls, user, repository, permission):
2858 def create(cls, user, repository, permission):
2849 n = cls()
2859 n = cls()
2850 n.user = user
2860 n.user = user
2851 n.repository = repository
2861 n.repository = repository
2852 n.permission = permission
2862 n.permission = permission
2853 Session().add(n)
2863 Session().add(n)
2854 return n
2864 return n
2855
2865
2856 def __unicode__(self):
2866 def __unicode__(self):
2857 return u'<%s => %s >' % (self.user, self.repository)
2867 return u'<%s => %s >' % (self.user, self.repository)
2858
2868
2859
2869
2860 class UserUserGroupToPerm(Base, BaseModel):
2870 class UserUserGroupToPerm(Base, BaseModel):
2861 __tablename__ = 'user_user_group_to_perm'
2871 __tablename__ = 'user_user_group_to_perm'
2862 __table_args__ = (
2872 __table_args__ = (
2863 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2873 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2864 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2874 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2865 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2875 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2866 )
2876 )
2867 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2877 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2868 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2878 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2869 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2879 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2870 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2880 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2871
2881
2872 user = relationship('User')
2882 user = relationship('User')
2873 user_group = relationship('UserGroup')
2883 user_group = relationship('UserGroup')
2874 permission = relationship('Permission')
2884 permission = relationship('Permission')
2875
2885
2876 @classmethod
2886 @classmethod
2877 def create(cls, user, user_group, permission):
2887 def create(cls, user, user_group, permission):
2878 n = cls()
2888 n = cls()
2879 n.user = user
2889 n.user = user
2880 n.user_group = user_group
2890 n.user_group = user_group
2881 n.permission = permission
2891 n.permission = permission
2882 Session().add(n)
2892 Session().add(n)
2883 return n
2893 return n
2884
2894
2885 def __unicode__(self):
2895 def __unicode__(self):
2886 return u'<%s => %s >' % (self.user, self.user_group)
2896 return u'<%s => %s >' % (self.user, self.user_group)
2887
2897
2888
2898
2889 class UserToPerm(Base, BaseModel):
2899 class UserToPerm(Base, BaseModel):
2890 __tablename__ = 'user_to_perm'
2900 __tablename__ = 'user_to_perm'
2891 __table_args__ = (
2901 __table_args__ = (
2892 UniqueConstraint('user_id', 'permission_id'),
2902 UniqueConstraint('user_id', 'permission_id'),
2893 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2903 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2894 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2904 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2895 )
2905 )
2896 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2906 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2897 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2907 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2898 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2908 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2899
2909
2900 user = relationship('User')
2910 user = relationship('User')
2901 permission = relationship('Permission', lazy='joined')
2911 permission = relationship('Permission', lazy='joined')
2902
2912
2903 def __unicode__(self):
2913 def __unicode__(self):
2904 return u'<%s => %s >' % (self.user, self.permission)
2914 return u'<%s => %s >' % (self.user, self.permission)
2905
2915
2906
2916
2907 class UserGroupRepoToPerm(Base, BaseModel):
2917 class UserGroupRepoToPerm(Base, BaseModel):
2908 __tablename__ = 'users_group_repo_to_perm'
2918 __tablename__ = 'users_group_repo_to_perm'
2909 __table_args__ = (
2919 __table_args__ = (
2910 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2920 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2911 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2921 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2912 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2922 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2913 )
2923 )
2914 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2924 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2915 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2925 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2916 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2926 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2917 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2927 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2918
2928
2919 users_group = relationship('UserGroup')
2929 users_group = relationship('UserGroup')
2920 permission = relationship('Permission')
2930 permission = relationship('Permission')
2921 repository = relationship('Repository')
2931 repository = relationship('Repository')
2922
2932
2923 @classmethod
2933 @classmethod
2924 def create(cls, users_group, repository, permission):
2934 def create(cls, users_group, repository, permission):
2925 n = cls()
2935 n = cls()
2926 n.users_group = users_group
2936 n.users_group = users_group
2927 n.repository = repository
2937 n.repository = repository
2928 n.permission = permission
2938 n.permission = permission
2929 Session().add(n)
2939 Session().add(n)
2930 return n
2940 return n
2931
2941
2932 def __unicode__(self):
2942 def __unicode__(self):
2933 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2943 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2934
2944
2935
2945
2936 class UserGroupUserGroupToPerm(Base, BaseModel):
2946 class UserGroupUserGroupToPerm(Base, BaseModel):
2937 __tablename__ = 'user_group_user_group_to_perm'
2947 __tablename__ = 'user_group_user_group_to_perm'
2938 __table_args__ = (
2948 __table_args__ = (
2939 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2949 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2940 CheckConstraint('target_user_group_id != user_group_id'),
2950 CheckConstraint('target_user_group_id != user_group_id'),
2941 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2951 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2942 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2952 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2943 )
2953 )
2944 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2954 user_group_user_group_to_perm_id = Column("user_group_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2945 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2955 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2946 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2956 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2947 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2957 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2948
2958
2949 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2959 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2950 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2960 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2951 permission = relationship('Permission')
2961 permission = relationship('Permission')
2952
2962
2953 @classmethod
2963 @classmethod
2954 def create(cls, target_user_group, user_group, permission):
2964 def create(cls, target_user_group, user_group, permission):
2955 n = cls()
2965 n = cls()
2956 n.target_user_group = target_user_group
2966 n.target_user_group = target_user_group
2957 n.user_group = user_group
2967 n.user_group = user_group
2958 n.permission = permission
2968 n.permission = permission
2959 Session().add(n)
2969 Session().add(n)
2960 return n
2970 return n
2961
2971
2962 def __unicode__(self):
2972 def __unicode__(self):
2963 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2973 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2964
2974
2965
2975
2966 class UserGroupToPerm(Base, BaseModel):
2976 class UserGroupToPerm(Base, BaseModel):
2967 __tablename__ = 'users_group_to_perm'
2977 __tablename__ = 'users_group_to_perm'
2968 __table_args__ = (
2978 __table_args__ = (
2969 UniqueConstraint('users_group_id', 'permission_id',),
2979 UniqueConstraint('users_group_id', 'permission_id',),
2970 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2980 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2971 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2981 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2972 )
2982 )
2973 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2983 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2974 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2984 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2975 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2985 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2976
2986
2977 users_group = relationship('UserGroup')
2987 users_group = relationship('UserGroup')
2978 permission = relationship('Permission')
2988 permission = relationship('Permission')
2979
2989
2980
2990
2981 class UserRepoGroupToPerm(Base, BaseModel):
2991 class UserRepoGroupToPerm(Base, BaseModel):
2982 __tablename__ = 'user_repo_group_to_perm'
2992 __tablename__ = 'user_repo_group_to_perm'
2983 __table_args__ = (
2993 __table_args__ = (
2984 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2994 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2985 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2995 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2986 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2996 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2987 )
2997 )
2988
2998
2989 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2999 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2990 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3000 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2991 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3001 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2992 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3002 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2993
3003
2994 user = relationship('User')
3004 user = relationship('User')
2995 group = relationship('RepoGroup')
3005 group = relationship('RepoGroup')
2996 permission = relationship('Permission')
3006 permission = relationship('Permission')
2997
3007
2998 @classmethod
3008 @classmethod
2999 def create(cls, user, repository_group, permission):
3009 def create(cls, user, repository_group, permission):
3000 n = cls()
3010 n = cls()
3001 n.user = user
3011 n.user = user
3002 n.group = repository_group
3012 n.group = repository_group
3003 n.permission = permission
3013 n.permission = permission
3004 Session().add(n)
3014 Session().add(n)
3005 return n
3015 return n
3006
3016
3007
3017
3008 class UserGroupRepoGroupToPerm(Base, BaseModel):
3018 class UserGroupRepoGroupToPerm(Base, BaseModel):
3009 __tablename__ = 'users_group_repo_group_to_perm'
3019 __tablename__ = 'users_group_repo_group_to_perm'
3010 __table_args__ = (
3020 __table_args__ = (
3011 UniqueConstraint('users_group_id', 'group_id'),
3021 UniqueConstraint('users_group_id', 'group_id'),
3012 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3022 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3013 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3023 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3014 )
3024 )
3015
3025
3016 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3026 users_group_repo_group_to_perm_id = Column("users_group_repo_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3017 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3027 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3018 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3028 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3019 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3029 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3020
3030
3021 users_group = relationship('UserGroup')
3031 users_group = relationship('UserGroup')
3022 permission = relationship('Permission')
3032 permission = relationship('Permission')
3023 group = relationship('RepoGroup')
3033 group = relationship('RepoGroup')
3024
3034
3025 @classmethod
3035 @classmethod
3026 def create(cls, user_group, repository_group, permission):
3036 def create(cls, user_group, repository_group, permission):
3027 n = cls()
3037 n = cls()
3028 n.users_group = user_group
3038 n.users_group = user_group
3029 n.group = repository_group
3039 n.group = repository_group
3030 n.permission = permission
3040 n.permission = permission
3031 Session().add(n)
3041 Session().add(n)
3032 return n
3042 return n
3033
3043
3034 def __unicode__(self):
3044 def __unicode__(self):
3035 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3045 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3036
3046
3037
3047
3038 class Statistics(Base, BaseModel):
3048 class Statistics(Base, BaseModel):
3039 __tablename__ = 'statistics'
3049 __tablename__ = 'statistics'
3040 __table_args__ = (
3050 __table_args__ = (
3041 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3051 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3042 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3052 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3043 )
3053 )
3044 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3054 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3045 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3055 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3046 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3056 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3047 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3057 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3048 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3058 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3049 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3059 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3050
3060
3051 repository = relationship('Repository', single_parent=True)
3061 repository = relationship('Repository', single_parent=True)
3052
3062
3053
3063
3054 class UserFollowing(Base, BaseModel):
3064 class UserFollowing(Base, BaseModel):
3055 __tablename__ = 'user_followings'
3065 __tablename__ = 'user_followings'
3056 __table_args__ = (
3066 __table_args__ = (
3057 UniqueConstraint('user_id', 'follows_repository_id'),
3067 UniqueConstraint('user_id', 'follows_repository_id'),
3058 UniqueConstraint('user_id', 'follows_user_id'),
3068 UniqueConstraint('user_id', 'follows_user_id'),
3059 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3069 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3060 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3070 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3061 )
3071 )
3062
3072
3063 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3073 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3064 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3074 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3065 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3075 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3066 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3076 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3067 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3077 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3068
3078
3069 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3079 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3070
3080
3071 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3081 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3072 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3082 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3073
3083
3074 @classmethod
3084 @classmethod
3075 def get_repo_followers(cls, repo_id):
3085 def get_repo_followers(cls, repo_id):
3076 return cls.query().filter(cls.follows_repo_id == repo_id)
3086 return cls.query().filter(cls.follows_repo_id == repo_id)
3077
3087
3078
3088
3079 class CacheKey(Base, BaseModel):
3089 class CacheKey(Base, BaseModel):
3080 __tablename__ = 'cache_invalidation'
3090 __tablename__ = 'cache_invalidation'
3081 __table_args__ = (
3091 __table_args__ = (
3082 UniqueConstraint('cache_key'),
3092 UniqueConstraint('cache_key'),
3083 Index('key_idx', 'cache_key'),
3093 Index('key_idx', 'cache_key'),
3084 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3094 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3085 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3095 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3086 )
3096 )
3087 CACHE_TYPE_ATOM = 'ATOM'
3097 CACHE_TYPE_ATOM = 'ATOM'
3088 CACHE_TYPE_RSS = 'RSS'
3098 CACHE_TYPE_RSS = 'RSS'
3089 CACHE_TYPE_README = 'README'
3099 CACHE_TYPE_README = 'README'
3090
3100
3091 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3101 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3092 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3102 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3093 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3103 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3094 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3104 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3095
3105
3096 def __init__(self, cache_key, cache_args=''):
3106 def __init__(self, cache_key, cache_args=''):
3097 self.cache_key = cache_key
3107 self.cache_key = cache_key
3098 self.cache_args = cache_args
3108 self.cache_args = cache_args
3099 self.cache_active = False
3109 self.cache_active = False
3100
3110
3101 def __unicode__(self):
3111 def __unicode__(self):
3102 return u"<%s('%s:%s[%s]')>" % (
3112 return u"<%s('%s:%s[%s]')>" % (
3103 self.__class__.__name__,
3113 self.__class__.__name__,
3104 self.cache_id, self.cache_key, self.cache_active)
3114 self.cache_id, self.cache_key, self.cache_active)
3105
3115
3106 def _cache_key_partition(self):
3116 def _cache_key_partition(self):
3107 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3117 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3108 return prefix, repo_name, suffix
3118 return prefix, repo_name, suffix
3109
3119
3110 def get_prefix(self):
3120 def get_prefix(self):
3111 """
3121 """
3112 Try to extract prefix from existing cache key. The key could consist
3122 Try to extract prefix from existing cache key. The key could consist
3113 of prefix, repo_name, suffix
3123 of prefix, repo_name, suffix
3114 """
3124 """
3115 # this returns prefix, repo_name, suffix
3125 # this returns prefix, repo_name, suffix
3116 return self._cache_key_partition()[0]
3126 return self._cache_key_partition()[0]
3117
3127
3118 def get_suffix(self):
3128 def get_suffix(self):
3119 """
3129 """
3120 get suffix that might have been used in _get_cache_key to
3130 get suffix that might have been used in _get_cache_key to
3121 generate self.cache_key. Only used for informational purposes
3131 generate self.cache_key. Only used for informational purposes
3122 in repo_edit.mako.
3132 in repo_edit.mako.
3123 """
3133 """
3124 # prefix, repo_name, suffix
3134 # prefix, repo_name, suffix
3125 return self._cache_key_partition()[2]
3135 return self._cache_key_partition()[2]
3126
3136
3127 @classmethod
3137 @classmethod
3128 def delete_all_cache(cls):
3138 def delete_all_cache(cls):
3129 """
3139 """
3130 Delete all cache keys from database.
3140 Delete all cache keys from database.
3131 Should only be run when all instances are down and all entries
3141 Should only be run when all instances are down and all entries
3132 thus stale.
3142 thus stale.
3133 """
3143 """
3134 cls.query().delete()
3144 cls.query().delete()
3135 Session().commit()
3145 Session().commit()
3136
3146
3137 @classmethod
3147 @classmethod
3138 def get_cache_key(cls, repo_name, cache_type):
3148 def get_cache_key(cls, repo_name, cache_type):
3139 """
3149 """
3140
3150
3141 Generate a cache key for this process of RhodeCode instance.
3151 Generate a cache key for this process of RhodeCode instance.
3142 Prefix most likely will be process id or maybe explicitly set
3152 Prefix most likely will be process id or maybe explicitly set
3143 instance_id from .ini file.
3153 instance_id from .ini file.
3144 """
3154 """
3145 import rhodecode
3155 import rhodecode
3146 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
3156 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
3147
3157
3148 repo_as_unicode = safe_unicode(repo_name)
3158 repo_as_unicode = safe_unicode(repo_name)
3149 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
3159 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
3150 if cache_type else repo_as_unicode
3160 if cache_type else repo_as_unicode
3151
3161
3152 return u'{}{}'.format(prefix, key)
3162 return u'{}{}'.format(prefix, key)
3153
3163
3154 @classmethod
3164 @classmethod
3155 def set_invalidate(cls, repo_name, delete=False):
3165 def set_invalidate(cls, repo_name, delete=False):
3156 """
3166 """
3157 Mark all caches of a repo as invalid in the database.
3167 Mark all caches of a repo as invalid in the database.
3158 """
3168 """
3159
3169
3160 try:
3170 try:
3161 qry = Session().query(cls).filter(cls.cache_args == repo_name)
3171 qry = Session().query(cls).filter(cls.cache_args == repo_name)
3162 if delete:
3172 if delete:
3163 log.debug('cache objects deleted for repo %s',
3173 log.debug('cache objects deleted for repo %s',
3164 safe_str(repo_name))
3174 safe_str(repo_name))
3165 qry.delete()
3175 qry.delete()
3166 else:
3176 else:
3167 log.debug('cache objects marked as invalid for repo %s',
3177 log.debug('cache objects marked as invalid for repo %s',
3168 safe_str(repo_name))
3178 safe_str(repo_name))
3169 qry.update({"cache_active": False})
3179 qry.update({"cache_active": False})
3170
3180
3171 Session().commit()
3181 Session().commit()
3172 except Exception:
3182 except Exception:
3173 log.exception(
3183 log.exception(
3174 'Cache key invalidation failed for repository %s',
3184 'Cache key invalidation failed for repository %s',
3175 safe_str(repo_name))
3185 safe_str(repo_name))
3176 Session().rollback()
3186 Session().rollback()
3177
3187
3178 @classmethod
3188 @classmethod
3179 def get_active_cache(cls, cache_key):
3189 def get_active_cache(cls, cache_key):
3180 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3190 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3181 if inv_obj:
3191 if inv_obj:
3182 return inv_obj
3192 return inv_obj
3183 return None
3193 return None
3184
3194
3185 @classmethod
3195 @classmethod
3186 def repo_context_cache(cls, compute_func, repo_name, cache_type,
3196 def repo_context_cache(cls, compute_func, repo_name, cache_type,
3187 thread_scoped=False):
3197 thread_scoped=False):
3188 """
3198 """
3189 @cache_region('long_term')
3199 @cache_region('long_term')
3190 def _heavy_calculation(cache_key):
3200 def _heavy_calculation(cache_key):
3191 return 'result'
3201 return 'result'
3192
3202
3193 cache_context = CacheKey.repo_context_cache(
3203 cache_context = CacheKey.repo_context_cache(
3194 _heavy_calculation, repo_name, cache_type)
3204 _heavy_calculation, repo_name, cache_type)
3195
3205
3196 with cache_context as context:
3206 with cache_context as context:
3197 context.invalidate()
3207 context.invalidate()
3198 computed = context.compute()
3208 computed = context.compute()
3199
3209
3200 assert computed == 'result'
3210 assert computed == 'result'
3201 """
3211 """
3202 from rhodecode.lib import caches
3212 from rhodecode.lib import caches
3203 return caches.InvalidationContext(
3213 return caches.InvalidationContext(
3204 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
3214 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
3205
3215
3206
3216
3207 class ChangesetComment(Base, BaseModel):
3217 class ChangesetComment(Base, BaseModel):
3208 __tablename__ = 'changeset_comments'
3218 __tablename__ = 'changeset_comments'
3209 __table_args__ = (
3219 __table_args__ = (
3210 Index('cc_revision_idx', 'revision'),
3220 Index('cc_revision_idx', 'revision'),
3211 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3221 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3212 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3222 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3213 )
3223 )
3214
3224
3215 COMMENT_OUTDATED = u'comment_outdated'
3225 COMMENT_OUTDATED = u'comment_outdated'
3216 COMMENT_TYPE_NOTE = u'note'
3226 COMMENT_TYPE_NOTE = u'note'
3217 COMMENT_TYPE_TODO = u'todo'
3227 COMMENT_TYPE_TODO = u'todo'
3218 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3228 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3219
3229
3220 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3230 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3221 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3231 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3222 revision = Column('revision', String(40), nullable=True)
3232 revision = Column('revision', String(40), nullable=True)
3223 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3233 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3224 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3234 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3225 line_no = Column('line_no', Unicode(10), nullable=True)
3235 line_no = Column('line_no', Unicode(10), nullable=True)
3226 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3236 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3227 f_path = Column('f_path', Unicode(1000), nullable=True)
3237 f_path = Column('f_path', Unicode(1000), nullable=True)
3228 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3238 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3229 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3239 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3230 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3240 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3231 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3241 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3232 renderer = Column('renderer', Unicode(64), nullable=True)
3242 renderer = Column('renderer', Unicode(64), nullable=True)
3233 display_state = Column('display_state', Unicode(128), nullable=True)
3243 display_state = Column('display_state', Unicode(128), nullable=True)
3234
3244
3235 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3245 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3236 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3246 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3237 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3247 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3238 author = relationship('User', lazy='joined')
3248 author = relationship('User', lazy='joined')
3239 repo = relationship('Repository')
3249 repo = relationship('Repository')
3240 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3250 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3241 pull_request = relationship('PullRequest', lazy='joined')
3251 pull_request = relationship('PullRequest', lazy='joined')
3242 pull_request_version = relationship('PullRequestVersion')
3252 pull_request_version = relationship('PullRequestVersion')
3243
3253
3244 @classmethod
3254 @classmethod
3245 def get_users(cls, revision=None, pull_request_id=None):
3255 def get_users(cls, revision=None, pull_request_id=None):
3246 """
3256 """
3247 Returns user associated with this ChangesetComment. ie those
3257 Returns user associated with this ChangesetComment. ie those
3248 who actually commented
3258 who actually commented
3249
3259
3250 :param cls:
3260 :param cls:
3251 :param revision:
3261 :param revision:
3252 """
3262 """
3253 q = Session().query(User)\
3263 q = Session().query(User)\
3254 .join(ChangesetComment.author)
3264 .join(ChangesetComment.author)
3255 if revision:
3265 if revision:
3256 q = q.filter(cls.revision == revision)
3266 q = q.filter(cls.revision == revision)
3257 elif pull_request_id:
3267 elif pull_request_id:
3258 q = q.filter(cls.pull_request_id == pull_request_id)
3268 q = q.filter(cls.pull_request_id == pull_request_id)
3259 return q.all()
3269 return q.all()
3260
3270
3261 @classmethod
3271 @classmethod
3262 def get_index_from_version(cls, pr_version, versions):
3272 def get_index_from_version(cls, pr_version, versions):
3263 num_versions = [x.pull_request_version_id for x in versions]
3273 num_versions = [x.pull_request_version_id for x in versions]
3264 try:
3274 try:
3265 return num_versions.index(pr_version) +1
3275 return num_versions.index(pr_version) +1
3266 except (IndexError, ValueError):
3276 except (IndexError, ValueError):
3267 return
3277 return
3268
3278
3269 @property
3279 @property
3270 def outdated(self):
3280 def outdated(self):
3271 return self.display_state == self.COMMENT_OUTDATED
3281 return self.display_state == self.COMMENT_OUTDATED
3272
3282
3273 def outdated_at_version(self, version):
3283 def outdated_at_version(self, version):
3274 """
3284 """
3275 Checks if comment is outdated for given pull request version
3285 Checks if comment is outdated for given pull request version
3276 """
3286 """
3277 return self.outdated and self.pull_request_version_id != version
3287 return self.outdated and self.pull_request_version_id != version
3278
3288
3279 def older_than_version(self, version):
3289 def older_than_version(self, version):
3280 """
3290 """
3281 Checks if comment is made from previous version than given
3291 Checks if comment is made from previous version than given
3282 """
3292 """
3283 if version is None:
3293 if version is None:
3284 return self.pull_request_version_id is not None
3294 return self.pull_request_version_id is not None
3285
3295
3286 return self.pull_request_version_id < version
3296 return self.pull_request_version_id < version
3287
3297
3288 @property
3298 @property
3289 def resolved(self):
3299 def resolved(self):
3290 return self.resolved_by[0] if self.resolved_by else None
3300 return self.resolved_by[0] if self.resolved_by else None
3291
3301
3292 @property
3302 @property
3293 def is_todo(self):
3303 def is_todo(self):
3294 return self.comment_type == self.COMMENT_TYPE_TODO
3304 return self.comment_type == self.COMMENT_TYPE_TODO
3295
3305
3296 @property
3306 @property
3297 def is_inline(self):
3307 def is_inline(self):
3298 return self.line_no and self.f_path
3308 return self.line_no and self.f_path
3299
3309
3300 def get_index_version(self, versions):
3310 def get_index_version(self, versions):
3301 return self.get_index_from_version(
3311 return self.get_index_from_version(
3302 self.pull_request_version_id, versions)
3312 self.pull_request_version_id, versions)
3303
3313
3304 def __repr__(self):
3314 def __repr__(self):
3305 if self.comment_id:
3315 if self.comment_id:
3306 return '<DB:Comment #%s>' % self.comment_id
3316 return '<DB:Comment #%s>' % self.comment_id
3307 else:
3317 else:
3308 return '<DB:Comment at %#x>' % id(self)
3318 return '<DB:Comment at %#x>' % id(self)
3309
3319
3310 def get_api_data(self):
3320 def get_api_data(self):
3311 comment = self
3321 comment = self
3312 data = {
3322 data = {
3313 'comment_id': comment.comment_id,
3323 'comment_id': comment.comment_id,
3314 'comment_type': comment.comment_type,
3324 'comment_type': comment.comment_type,
3315 'comment_text': comment.text,
3325 'comment_text': comment.text,
3316 'comment_status': comment.status_change,
3326 'comment_status': comment.status_change,
3317 'comment_f_path': comment.f_path,
3327 'comment_f_path': comment.f_path,
3318 'comment_lineno': comment.line_no,
3328 'comment_lineno': comment.line_no,
3319 'comment_author': comment.author,
3329 'comment_author': comment.author,
3320 'comment_created_on': comment.created_on
3330 'comment_created_on': comment.created_on
3321 }
3331 }
3322 return data
3332 return data
3323
3333
3324 def __json__(self):
3334 def __json__(self):
3325 data = dict()
3335 data = dict()
3326 data.update(self.get_api_data())
3336 data.update(self.get_api_data())
3327 return data
3337 return data
3328
3338
3329
3339
3330 class ChangesetStatus(Base, BaseModel):
3340 class ChangesetStatus(Base, BaseModel):
3331 __tablename__ = 'changeset_statuses'
3341 __tablename__ = 'changeset_statuses'
3332 __table_args__ = (
3342 __table_args__ = (
3333 Index('cs_revision_idx', 'revision'),
3343 Index('cs_revision_idx', 'revision'),
3334 Index('cs_version_idx', 'version'),
3344 Index('cs_version_idx', 'version'),
3335 UniqueConstraint('repo_id', 'revision', 'version'),
3345 UniqueConstraint('repo_id', 'revision', 'version'),
3336 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3346 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3337 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3347 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3338 )
3348 )
3339 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3349 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3340 STATUS_APPROVED = 'approved'
3350 STATUS_APPROVED = 'approved'
3341 STATUS_REJECTED = 'rejected'
3351 STATUS_REJECTED = 'rejected'
3342 STATUS_UNDER_REVIEW = 'under_review'
3352 STATUS_UNDER_REVIEW = 'under_review'
3343
3353
3344 STATUSES = [
3354 STATUSES = [
3345 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3355 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3346 (STATUS_APPROVED, _("Approved")),
3356 (STATUS_APPROVED, _("Approved")),
3347 (STATUS_REJECTED, _("Rejected")),
3357 (STATUS_REJECTED, _("Rejected")),
3348 (STATUS_UNDER_REVIEW, _("Under Review")),
3358 (STATUS_UNDER_REVIEW, _("Under Review")),
3349 ]
3359 ]
3350
3360
3351 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3361 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3352 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3362 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3353 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3363 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3354 revision = Column('revision', String(40), nullable=False)
3364 revision = Column('revision', String(40), nullable=False)
3355 status = Column('status', String(128), nullable=False, default=DEFAULT)
3365 status = Column('status', String(128), nullable=False, default=DEFAULT)
3356 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3366 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3357 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3367 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3358 version = Column('version', Integer(), nullable=False, default=0)
3368 version = Column('version', Integer(), nullable=False, default=0)
3359 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3369 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3360
3370
3361 author = relationship('User', lazy='joined')
3371 author = relationship('User', lazy='joined')
3362 repo = relationship('Repository')
3372 repo = relationship('Repository')
3363 comment = relationship('ChangesetComment', lazy='joined')
3373 comment = relationship('ChangesetComment', lazy='joined')
3364 pull_request = relationship('PullRequest', lazy='joined')
3374 pull_request = relationship('PullRequest', lazy='joined')
3365
3375
3366 def __unicode__(self):
3376 def __unicode__(self):
3367 return u"<%s('%s[v%s]:%s')>" % (
3377 return u"<%s('%s[v%s]:%s')>" % (
3368 self.__class__.__name__,
3378 self.__class__.__name__,
3369 self.status, self.version, self.author
3379 self.status, self.version, self.author
3370 )
3380 )
3371
3381
3372 @classmethod
3382 @classmethod
3373 def get_status_lbl(cls, value):
3383 def get_status_lbl(cls, value):
3374 return dict(cls.STATUSES).get(value)
3384 return dict(cls.STATUSES).get(value)
3375
3385
3376 @property
3386 @property
3377 def status_lbl(self):
3387 def status_lbl(self):
3378 return ChangesetStatus.get_status_lbl(self.status)
3388 return ChangesetStatus.get_status_lbl(self.status)
3379
3389
3380 def get_api_data(self):
3390 def get_api_data(self):
3381 status = self
3391 status = self
3382 data = {
3392 data = {
3383 'status_id': status.changeset_status_id,
3393 'status_id': status.changeset_status_id,
3384 'status': status.status,
3394 'status': status.status,
3385 }
3395 }
3386 return data
3396 return data
3387
3397
3388 def __json__(self):
3398 def __json__(self):
3389 data = dict()
3399 data = dict()
3390 data.update(self.get_api_data())
3400 data.update(self.get_api_data())
3391 return data
3401 return data
3392
3402
3393
3403
3394 class _PullRequestBase(BaseModel):
3404 class _PullRequestBase(BaseModel):
3395 """
3405 """
3396 Common attributes of pull request and version entries.
3406 Common attributes of pull request and version entries.
3397 """
3407 """
3398
3408
3399 # .status values
3409 # .status values
3400 STATUS_NEW = u'new'
3410 STATUS_NEW = u'new'
3401 STATUS_OPEN = u'open'
3411 STATUS_OPEN = u'open'
3402 STATUS_CLOSED = u'closed'
3412 STATUS_CLOSED = u'closed'
3403
3413
3404 title = Column('title', Unicode(255), nullable=True)
3414 title = Column('title', Unicode(255), nullable=True)
3405 description = Column(
3415 description = Column(
3406 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3416 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3407 nullable=True)
3417 nullable=True)
3408 # new/open/closed status of pull request (not approve/reject/etc)
3418 # new/open/closed status of pull request (not approve/reject/etc)
3409 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3419 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3410 created_on = Column(
3420 created_on = Column(
3411 'created_on', DateTime(timezone=False), nullable=False,
3421 'created_on', DateTime(timezone=False), nullable=False,
3412 default=datetime.datetime.now)
3422 default=datetime.datetime.now)
3413 updated_on = Column(
3423 updated_on = Column(
3414 'updated_on', DateTime(timezone=False), nullable=False,
3424 'updated_on', DateTime(timezone=False), nullable=False,
3415 default=datetime.datetime.now)
3425 default=datetime.datetime.now)
3416
3426
3417 @declared_attr
3427 @declared_attr
3418 def user_id(cls):
3428 def user_id(cls):
3419 return Column(
3429 return Column(
3420 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3430 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3421 unique=None)
3431 unique=None)
3422
3432
3423 # 500 revisions max
3433 # 500 revisions max
3424 _revisions = Column(
3434 _revisions = Column(
3425 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3435 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3426
3436
3427 @declared_attr
3437 @declared_attr
3428 def source_repo_id(cls):
3438 def source_repo_id(cls):
3429 # TODO: dan: rename column to source_repo_id
3439 # TODO: dan: rename column to source_repo_id
3430 return Column(
3440 return Column(
3431 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3441 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3432 nullable=False)
3442 nullable=False)
3433
3443
3434 source_ref = Column('org_ref', Unicode(255), nullable=False)
3444 source_ref = Column('org_ref', Unicode(255), nullable=False)
3435
3445
3436 @declared_attr
3446 @declared_attr
3437 def target_repo_id(cls):
3447 def target_repo_id(cls):
3438 # TODO: dan: rename column to target_repo_id
3448 # TODO: dan: rename column to target_repo_id
3439 return Column(
3449 return Column(
3440 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3450 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3441 nullable=False)
3451 nullable=False)
3442
3452
3443 target_ref = Column('other_ref', Unicode(255), nullable=False)
3453 target_ref = Column('other_ref', Unicode(255), nullable=False)
3444 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3454 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3445
3455
3446 # TODO: dan: rename column to last_merge_source_rev
3456 # TODO: dan: rename column to last_merge_source_rev
3447 _last_merge_source_rev = Column(
3457 _last_merge_source_rev = Column(
3448 'last_merge_org_rev', String(40), nullable=True)
3458 'last_merge_org_rev', String(40), nullable=True)
3449 # TODO: dan: rename column to last_merge_target_rev
3459 # TODO: dan: rename column to last_merge_target_rev
3450 _last_merge_target_rev = Column(
3460 _last_merge_target_rev = Column(
3451 'last_merge_other_rev', String(40), nullable=True)
3461 'last_merge_other_rev', String(40), nullable=True)
3452 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3462 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3453 merge_rev = Column('merge_rev', String(40), nullable=True)
3463 merge_rev = Column('merge_rev', String(40), nullable=True)
3454
3464
3455 reviewer_data = Column(
3465 reviewer_data = Column(
3456 'reviewer_data_json', MutationObj.as_mutable(
3466 'reviewer_data_json', MutationObj.as_mutable(
3457 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3467 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3458
3468
3459 @property
3469 @property
3460 def reviewer_data_json(self):
3470 def reviewer_data_json(self):
3461 return json.dumps(self.reviewer_data)
3471 return json.dumps(self.reviewer_data)
3462
3472
3463 @hybrid_property
3473 @hybrid_property
3464 def description_safe(self):
3474 def description_safe(self):
3465 from rhodecode.lib import helpers as h
3475 from rhodecode.lib import helpers as h
3466 return h.escape(self.description)
3476 return h.escape(self.description)
3467
3477
3468 @hybrid_property
3478 @hybrid_property
3469 def revisions(self):
3479 def revisions(self):
3470 return self._revisions.split(':') if self._revisions else []
3480 return self._revisions.split(':') if self._revisions else []
3471
3481
3472 @revisions.setter
3482 @revisions.setter
3473 def revisions(self, val):
3483 def revisions(self, val):
3474 self._revisions = ':'.join(val)
3484 self._revisions = ':'.join(val)
3475
3485
3476 @hybrid_property
3486 @hybrid_property
3477 def last_merge_status(self):
3487 def last_merge_status(self):
3478 return safe_int(self._last_merge_status)
3488 return safe_int(self._last_merge_status)
3479
3489
3480 @last_merge_status.setter
3490 @last_merge_status.setter
3481 def last_merge_status(self, val):
3491 def last_merge_status(self, val):
3482 self._last_merge_status = val
3492 self._last_merge_status = val
3483
3493
3484 @declared_attr
3494 @declared_attr
3485 def author(cls):
3495 def author(cls):
3486 return relationship('User', lazy='joined')
3496 return relationship('User', lazy='joined')
3487
3497
3488 @declared_attr
3498 @declared_attr
3489 def source_repo(cls):
3499 def source_repo(cls):
3490 return relationship(
3500 return relationship(
3491 'Repository',
3501 'Repository',
3492 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3502 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3493
3503
3494 @property
3504 @property
3495 def source_ref_parts(self):
3505 def source_ref_parts(self):
3496 return self.unicode_to_reference(self.source_ref)
3506 return self.unicode_to_reference(self.source_ref)
3497
3507
3498 @declared_attr
3508 @declared_attr
3499 def target_repo(cls):
3509 def target_repo(cls):
3500 return relationship(
3510 return relationship(
3501 'Repository',
3511 'Repository',
3502 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3512 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3503
3513
3504 @property
3514 @property
3505 def target_ref_parts(self):
3515 def target_ref_parts(self):
3506 return self.unicode_to_reference(self.target_ref)
3516 return self.unicode_to_reference(self.target_ref)
3507
3517
3508 @property
3518 @property
3509 def shadow_merge_ref(self):
3519 def shadow_merge_ref(self):
3510 return self.unicode_to_reference(self._shadow_merge_ref)
3520 return self.unicode_to_reference(self._shadow_merge_ref)
3511
3521
3512 @shadow_merge_ref.setter
3522 @shadow_merge_ref.setter
3513 def shadow_merge_ref(self, ref):
3523 def shadow_merge_ref(self, ref):
3514 self._shadow_merge_ref = self.reference_to_unicode(ref)
3524 self._shadow_merge_ref = self.reference_to_unicode(ref)
3515
3525
3516 def unicode_to_reference(self, raw):
3526 def unicode_to_reference(self, raw):
3517 """
3527 """
3518 Convert a unicode (or string) to a reference object.
3528 Convert a unicode (or string) to a reference object.
3519 If unicode evaluates to False it returns None.
3529 If unicode evaluates to False it returns None.
3520 """
3530 """
3521 if raw:
3531 if raw:
3522 refs = raw.split(':')
3532 refs = raw.split(':')
3523 return Reference(*refs)
3533 return Reference(*refs)
3524 else:
3534 else:
3525 return None
3535 return None
3526
3536
3527 def reference_to_unicode(self, ref):
3537 def reference_to_unicode(self, ref):
3528 """
3538 """
3529 Convert a reference object to unicode.
3539 Convert a reference object to unicode.
3530 If reference is None it returns None.
3540 If reference is None it returns None.
3531 """
3541 """
3532 if ref:
3542 if ref:
3533 return u':'.join(ref)
3543 return u':'.join(ref)
3534 else:
3544 else:
3535 return None
3545 return None
3536
3546
3537 def get_api_data(self, with_merge_state=True):
3547 def get_api_data(self, with_merge_state=True):
3538 from rhodecode.model.pull_request import PullRequestModel
3548 from rhodecode.model.pull_request import PullRequestModel
3539
3549
3540 pull_request = self
3550 pull_request = self
3541 if with_merge_state:
3551 if with_merge_state:
3542 merge_status = PullRequestModel().merge_status(pull_request)
3552 merge_status = PullRequestModel().merge_status(pull_request)
3543 merge_state = {
3553 merge_state = {
3544 'status': merge_status[0],
3554 'status': merge_status[0],
3545 'message': safe_unicode(merge_status[1]),
3555 'message': safe_unicode(merge_status[1]),
3546 }
3556 }
3547 else:
3557 else:
3548 merge_state = {'status': 'not_available',
3558 merge_state = {'status': 'not_available',
3549 'message': 'not_available'}
3559 'message': 'not_available'}
3550
3560
3551 merge_data = {
3561 merge_data = {
3552 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3562 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3553 'reference': (
3563 'reference': (
3554 pull_request.shadow_merge_ref._asdict()
3564 pull_request.shadow_merge_ref._asdict()
3555 if pull_request.shadow_merge_ref else None),
3565 if pull_request.shadow_merge_ref else None),
3556 }
3566 }
3557
3567
3558 data = {
3568 data = {
3559 'pull_request_id': pull_request.pull_request_id,
3569 'pull_request_id': pull_request.pull_request_id,
3560 'url': PullRequestModel().get_url(pull_request),
3570 'url': PullRequestModel().get_url(pull_request),
3561 'title': pull_request.title,
3571 'title': pull_request.title,
3562 'description': pull_request.description,
3572 'description': pull_request.description,
3563 'status': pull_request.status,
3573 'status': pull_request.status,
3564 'created_on': pull_request.created_on,
3574 'created_on': pull_request.created_on,
3565 'updated_on': pull_request.updated_on,
3575 'updated_on': pull_request.updated_on,
3566 'commit_ids': pull_request.revisions,
3576 'commit_ids': pull_request.revisions,
3567 'review_status': pull_request.calculated_review_status(),
3577 'review_status': pull_request.calculated_review_status(),
3568 'mergeable': merge_state,
3578 'mergeable': merge_state,
3569 'source': {
3579 'source': {
3570 'clone_url': pull_request.source_repo.clone_url(),
3580 'clone_url': pull_request.source_repo.clone_url(),
3571 'repository': pull_request.source_repo.repo_name,
3581 'repository': pull_request.source_repo.repo_name,
3572 'reference': {
3582 'reference': {
3573 'name': pull_request.source_ref_parts.name,
3583 'name': pull_request.source_ref_parts.name,
3574 'type': pull_request.source_ref_parts.type,
3584 'type': pull_request.source_ref_parts.type,
3575 'commit_id': pull_request.source_ref_parts.commit_id,
3585 'commit_id': pull_request.source_ref_parts.commit_id,
3576 },
3586 },
3577 },
3587 },
3578 'target': {
3588 'target': {
3579 'clone_url': pull_request.target_repo.clone_url(),
3589 'clone_url': pull_request.target_repo.clone_url(),
3580 'repository': pull_request.target_repo.repo_name,
3590 'repository': pull_request.target_repo.repo_name,
3581 'reference': {
3591 'reference': {
3582 'name': pull_request.target_ref_parts.name,
3592 'name': pull_request.target_ref_parts.name,
3583 'type': pull_request.target_ref_parts.type,
3593 'type': pull_request.target_ref_parts.type,
3584 'commit_id': pull_request.target_ref_parts.commit_id,
3594 'commit_id': pull_request.target_ref_parts.commit_id,
3585 },
3595 },
3586 },
3596 },
3587 'merge': merge_data,
3597 'merge': merge_data,
3588 'author': pull_request.author.get_api_data(include_secrets=False,
3598 'author': pull_request.author.get_api_data(include_secrets=False,
3589 details='basic'),
3599 details='basic'),
3590 'reviewers': [
3600 'reviewers': [
3591 {
3601 {
3592 'user': reviewer.get_api_data(include_secrets=False,
3602 'user': reviewer.get_api_data(include_secrets=False,
3593 details='basic'),
3603 details='basic'),
3594 'reasons': reasons,
3604 'reasons': reasons,
3595 'review_status': st[0][1].status if st else 'not_reviewed',
3605 'review_status': st[0][1].status if st else 'not_reviewed',
3596 }
3606 }
3597 for obj, reviewer, reasons, mandatory, st in
3607 for obj, reviewer, reasons, mandatory, st in
3598 pull_request.reviewers_statuses()
3608 pull_request.reviewers_statuses()
3599 ]
3609 ]
3600 }
3610 }
3601
3611
3602 return data
3612 return data
3603
3613
3604
3614
3605 class PullRequest(Base, _PullRequestBase):
3615 class PullRequest(Base, _PullRequestBase):
3606 __tablename__ = 'pull_requests'
3616 __tablename__ = 'pull_requests'
3607 __table_args__ = (
3617 __table_args__ = (
3608 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3618 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3609 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3619 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3610 )
3620 )
3611
3621
3612 pull_request_id = Column(
3622 pull_request_id = Column(
3613 'pull_request_id', Integer(), nullable=False, primary_key=True)
3623 'pull_request_id', Integer(), nullable=False, primary_key=True)
3614
3624
3615 def __repr__(self):
3625 def __repr__(self):
3616 if self.pull_request_id:
3626 if self.pull_request_id:
3617 return '<DB:PullRequest #%s>' % self.pull_request_id
3627 return '<DB:PullRequest #%s>' % self.pull_request_id
3618 else:
3628 else:
3619 return '<DB:PullRequest at %#x>' % id(self)
3629 return '<DB:PullRequest at %#x>' % id(self)
3620
3630
3621 reviewers = relationship('PullRequestReviewers',
3631 reviewers = relationship('PullRequestReviewers',
3622 cascade="all, delete, delete-orphan")
3632 cascade="all, delete, delete-orphan")
3623 statuses = relationship('ChangesetStatus',
3633 statuses = relationship('ChangesetStatus',
3624 cascade="all, delete, delete-orphan")
3634 cascade="all, delete, delete-orphan")
3625 comments = relationship('ChangesetComment',
3635 comments = relationship('ChangesetComment',
3626 cascade="all, delete, delete-orphan")
3636 cascade="all, delete, delete-orphan")
3627 versions = relationship('PullRequestVersion',
3637 versions = relationship('PullRequestVersion',
3628 cascade="all, delete, delete-orphan",
3638 cascade="all, delete, delete-orphan",
3629 lazy='dynamic')
3639 lazy='dynamic')
3630
3640
3631 @classmethod
3641 @classmethod
3632 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3642 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3633 internal_methods=None):
3643 internal_methods=None):
3634
3644
3635 class PullRequestDisplay(object):
3645 class PullRequestDisplay(object):
3636 """
3646 """
3637 Special object wrapper for showing PullRequest data via Versions
3647 Special object wrapper for showing PullRequest data via Versions
3638 It mimics PR object as close as possible. This is read only object
3648 It mimics PR object as close as possible. This is read only object
3639 just for display
3649 just for display
3640 """
3650 """
3641
3651
3642 def __init__(self, attrs, internal=None):
3652 def __init__(self, attrs, internal=None):
3643 self.attrs = attrs
3653 self.attrs = attrs
3644 # internal have priority over the given ones via attrs
3654 # internal have priority over the given ones via attrs
3645 self.internal = internal or ['versions']
3655 self.internal = internal or ['versions']
3646
3656
3647 def __getattr__(self, item):
3657 def __getattr__(self, item):
3648 if item in self.internal:
3658 if item in self.internal:
3649 return getattr(self, item)
3659 return getattr(self, item)
3650 try:
3660 try:
3651 return self.attrs[item]
3661 return self.attrs[item]
3652 except KeyError:
3662 except KeyError:
3653 raise AttributeError(
3663 raise AttributeError(
3654 '%s object has no attribute %s' % (self, item))
3664 '%s object has no attribute %s' % (self, item))
3655
3665
3656 def __repr__(self):
3666 def __repr__(self):
3657 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3667 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3658
3668
3659 def versions(self):
3669 def versions(self):
3660 return pull_request_obj.versions.order_by(
3670 return pull_request_obj.versions.order_by(
3661 PullRequestVersion.pull_request_version_id).all()
3671 PullRequestVersion.pull_request_version_id).all()
3662
3672
3663 def is_closed(self):
3673 def is_closed(self):
3664 return pull_request_obj.is_closed()
3674 return pull_request_obj.is_closed()
3665
3675
3666 @property
3676 @property
3667 def pull_request_version_id(self):
3677 def pull_request_version_id(self):
3668 return getattr(pull_request_obj, 'pull_request_version_id', None)
3678 return getattr(pull_request_obj, 'pull_request_version_id', None)
3669
3679
3670 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3680 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3671
3681
3672 attrs.author = StrictAttributeDict(
3682 attrs.author = StrictAttributeDict(
3673 pull_request_obj.author.get_api_data())
3683 pull_request_obj.author.get_api_data())
3674 if pull_request_obj.target_repo:
3684 if pull_request_obj.target_repo:
3675 attrs.target_repo = StrictAttributeDict(
3685 attrs.target_repo = StrictAttributeDict(
3676 pull_request_obj.target_repo.get_api_data())
3686 pull_request_obj.target_repo.get_api_data())
3677 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3687 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3678
3688
3679 if pull_request_obj.source_repo:
3689 if pull_request_obj.source_repo:
3680 attrs.source_repo = StrictAttributeDict(
3690 attrs.source_repo = StrictAttributeDict(
3681 pull_request_obj.source_repo.get_api_data())
3691 pull_request_obj.source_repo.get_api_data())
3682 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3692 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3683
3693
3684 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3694 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3685 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3695 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3686 attrs.revisions = pull_request_obj.revisions
3696 attrs.revisions = pull_request_obj.revisions
3687
3697
3688 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3698 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3689 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3699 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3690 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3700 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3691
3701
3692 return PullRequestDisplay(attrs, internal=internal_methods)
3702 return PullRequestDisplay(attrs, internal=internal_methods)
3693
3703
3694 def is_closed(self):
3704 def is_closed(self):
3695 return self.status == self.STATUS_CLOSED
3705 return self.status == self.STATUS_CLOSED
3696
3706
3697 def __json__(self):
3707 def __json__(self):
3698 return {
3708 return {
3699 'revisions': self.revisions,
3709 'revisions': self.revisions,
3700 }
3710 }
3701
3711
3702 def calculated_review_status(self):
3712 def calculated_review_status(self):
3703 from rhodecode.model.changeset_status import ChangesetStatusModel
3713 from rhodecode.model.changeset_status import ChangesetStatusModel
3704 return ChangesetStatusModel().calculated_review_status(self)
3714 return ChangesetStatusModel().calculated_review_status(self)
3705
3715
3706 def reviewers_statuses(self):
3716 def reviewers_statuses(self):
3707 from rhodecode.model.changeset_status import ChangesetStatusModel
3717 from rhodecode.model.changeset_status import ChangesetStatusModel
3708 return ChangesetStatusModel().reviewers_statuses(self)
3718 return ChangesetStatusModel().reviewers_statuses(self)
3709
3719
3710 @property
3720 @property
3711 def workspace_id(self):
3721 def workspace_id(self):
3712 from rhodecode.model.pull_request import PullRequestModel
3722 from rhodecode.model.pull_request import PullRequestModel
3713 return PullRequestModel()._workspace_id(self)
3723 return PullRequestModel()._workspace_id(self)
3714
3724
3715 def get_shadow_repo(self):
3725 def get_shadow_repo(self):
3716 workspace_id = self.workspace_id
3726 workspace_id = self.workspace_id
3717 vcs_obj = self.target_repo.scm_instance()
3727 vcs_obj = self.target_repo.scm_instance()
3718 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3728 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3719 workspace_id)
3729 workspace_id)
3720 return vcs_obj._get_shadow_instance(shadow_repository_path)
3730 return vcs_obj._get_shadow_instance(shadow_repository_path)
3721
3731
3722
3732
3723 class PullRequestVersion(Base, _PullRequestBase):
3733 class PullRequestVersion(Base, _PullRequestBase):
3724 __tablename__ = 'pull_request_versions'
3734 __tablename__ = 'pull_request_versions'
3725 __table_args__ = (
3735 __table_args__ = (
3726 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3736 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3727 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3737 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3728 )
3738 )
3729
3739
3730 pull_request_version_id = Column(
3740 pull_request_version_id = Column(
3731 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3741 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3732 pull_request_id = Column(
3742 pull_request_id = Column(
3733 'pull_request_id', Integer(),
3743 'pull_request_id', Integer(),
3734 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3744 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3735 pull_request = relationship('PullRequest')
3745 pull_request = relationship('PullRequest')
3736
3746
3737 def __repr__(self):
3747 def __repr__(self):
3738 if self.pull_request_version_id:
3748 if self.pull_request_version_id:
3739 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3749 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3740 else:
3750 else:
3741 return '<DB:PullRequestVersion at %#x>' % id(self)
3751 return '<DB:PullRequestVersion at %#x>' % id(self)
3742
3752
3743 @property
3753 @property
3744 def reviewers(self):
3754 def reviewers(self):
3745 return self.pull_request.reviewers
3755 return self.pull_request.reviewers
3746
3756
3747 @property
3757 @property
3748 def versions(self):
3758 def versions(self):
3749 return self.pull_request.versions
3759 return self.pull_request.versions
3750
3760
3751 def is_closed(self):
3761 def is_closed(self):
3752 # calculate from original
3762 # calculate from original
3753 return self.pull_request.status == self.STATUS_CLOSED
3763 return self.pull_request.status == self.STATUS_CLOSED
3754
3764
3755 def calculated_review_status(self):
3765 def calculated_review_status(self):
3756 return self.pull_request.calculated_review_status()
3766 return self.pull_request.calculated_review_status()
3757
3767
3758 def reviewers_statuses(self):
3768 def reviewers_statuses(self):
3759 return self.pull_request.reviewers_statuses()
3769 return self.pull_request.reviewers_statuses()
3760
3770
3761
3771
3762 class PullRequestReviewers(Base, BaseModel):
3772 class PullRequestReviewers(Base, BaseModel):
3763 __tablename__ = 'pull_request_reviewers'
3773 __tablename__ = 'pull_request_reviewers'
3764 __table_args__ = (
3774 __table_args__ = (
3765 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3775 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3766 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3776 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3767 )
3777 )
3768
3778
3769 @hybrid_property
3779 @hybrid_property
3770 def reasons(self):
3780 def reasons(self):
3771 if not self._reasons:
3781 if not self._reasons:
3772 return []
3782 return []
3773 return self._reasons
3783 return self._reasons
3774
3784
3775 @reasons.setter
3785 @reasons.setter
3776 def reasons(self, val):
3786 def reasons(self, val):
3777 val = val or []
3787 val = val or []
3778 if any(not isinstance(x, basestring) for x in val):
3788 if any(not isinstance(x, basestring) for x in val):
3779 raise Exception('invalid reasons type, must be list of strings')
3789 raise Exception('invalid reasons type, must be list of strings')
3780 self._reasons = val
3790 self._reasons = val
3781
3791
3782 pull_requests_reviewers_id = Column(
3792 pull_requests_reviewers_id = Column(
3783 'pull_requests_reviewers_id', Integer(), nullable=False,
3793 'pull_requests_reviewers_id', Integer(), nullable=False,
3784 primary_key=True)
3794 primary_key=True)
3785 pull_request_id = Column(
3795 pull_request_id = Column(
3786 "pull_request_id", Integer(),
3796 "pull_request_id", Integer(),
3787 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3797 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3788 user_id = Column(
3798 user_id = Column(
3789 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3799 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3790 _reasons = Column(
3800 _reasons = Column(
3791 'reason', MutationList.as_mutable(
3801 'reason', MutationList.as_mutable(
3792 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3802 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3793
3803
3794 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3804 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3795 user = relationship('User')
3805 user = relationship('User')
3796 pull_request = relationship('PullRequest')
3806 pull_request = relationship('PullRequest')
3797
3807
3798 rule_data = Column(
3808 rule_data = Column(
3799 'rule_data_json',
3809 'rule_data_json',
3800 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
3810 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
3801
3811
3802 def rule_user_group_data(self):
3812 def rule_user_group_data(self):
3803 """
3813 """
3804 Returns the voting user group rule data for this reviewer
3814 Returns the voting user group rule data for this reviewer
3805 """
3815 """
3806
3816
3807 if self.rule_data and 'vote_rule' in self.rule_data:
3817 if self.rule_data and 'vote_rule' in self.rule_data:
3808 user_group_data = {}
3818 user_group_data = {}
3809 if 'rule_user_group_entry_id' in self.rule_data:
3819 if 'rule_user_group_entry_id' in self.rule_data:
3810 # means a group with voting rules !
3820 # means a group with voting rules !
3811 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
3821 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
3812 user_group_data['name'] = self.rule_data['rule_name']
3822 user_group_data['name'] = self.rule_data['rule_name']
3813 user_group_data['vote_rule'] = self.rule_data['vote_rule']
3823 user_group_data['vote_rule'] = self.rule_data['vote_rule']
3814
3824
3815 return user_group_data
3825 return user_group_data
3816
3826
3817 def __unicode__(self):
3827 def __unicode__(self):
3818 return u"<%s('id:%s')>" % (self.__class__.__name__,
3828 return u"<%s('id:%s')>" % (self.__class__.__name__,
3819 self.pull_requests_reviewers_id)
3829 self.pull_requests_reviewers_id)
3820
3830
3821
3831
3822 class Notification(Base, BaseModel):
3832 class Notification(Base, BaseModel):
3823 __tablename__ = 'notifications'
3833 __tablename__ = 'notifications'
3824 __table_args__ = (
3834 __table_args__ = (
3825 Index('notification_type_idx', 'type'),
3835 Index('notification_type_idx', 'type'),
3826 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3836 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3827 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3837 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3828 )
3838 )
3829
3839
3830 TYPE_CHANGESET_COMMENT = u'cs_comment'
3840 TYPE_CHANGESET_COMMENT = u'cs_comment'
3831 TYPE_MESSAGE = u'message'
3841 TYPE_MESSAGE = u'message'
3832 TYPE_MENTION = u'mention'
3842 TYPE_MENTION = u'mention'
3833 TYPE_REGISTRATION = u'registration'
3843 TYPE_REGISTRATION = u'registration'
3834 TYPE_PULL_REQUEST = u'pull_request'
3844 TYPE_PULL_REQUEST = u'pull_request'
3835 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3845 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3836
3846
3837 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3847 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3838 subject = Column('subject', Unicode(512), nullable=True)
3848 subject = Column('subject', Unicode(512), nullable=True)
3839 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3849 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3840 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3850 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3841 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3851 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3842 type_ = Column('type', Unicode(255))
3852 type_ = Column('type', Unicode(255))
3843
3853
3844 created_by_user = relationship('User')
3854 created_by_user = relationship('User')
3845 notifications_to_users = relationship('UserNotification', lazy='joined',
3855 notifications_to_users = relationship('UserNotification', lazy='joined',
3846 cascade="all, delete, delete-orphan")
3856 cascade="all, delete, delete-orphan")
3847
3857
3848 @property
3858 @property
3849 def recipients(self):
3859 def recipients(self):
3850 return [x.user for x in UserNotification.query()\
3860 return [x.user for x in UserNotification.query()\
3851 .filter(UserNotification.notification == self)\
3861 .filter(UserNotification.notification == self)\
3852 .order_by(UserNotification.user_id.asc()).all()]
3862 .order_by(UserNotification.user_id.asc()).all()]
3853
3863
3854 @classmethod
3864 @classmethod
3855 def create(cls, created_by, subject, body, recipients, type_=None):
3865 def create(cls, created_by, subject, body, recipients, type_=None):
3856 if type_ is None:
3866 if type_ is None:
3857 type_ = Notification.TYPE_MESSAGE
3867 type_ = Notification.TYPE_MESSAGE
3858
3868
3859 notification = cls()
3869 notification = cls()
3860 notification.created_by_user = created_by
3870 notification.created_by_user = created_by
3861 notification.subject = subject
3871 notification.subject = subject
3862 notification.body = body
3872 notification.body = body
3863 notification.type_ = type_
3873 notification.type_ = type_
3864 notification.created_on = datetime.datetime.now()
3874 notification.created_on = datetime.datetime.now()
3865
3875
3866 for u in recipients:
3876 for u in recipients:
3867 assoc = UserNotification()
3877 assoc = UserNotification()
3868 assoc.notification = notification
3878 assoc.notification = notification
3869
3879
3870 # if created_by is inside recipients mark his notification
3880 # if created_by is inside recipients mark his notification
3871 # as read
3881 # as read
3872 if u.user_id == created_by.user_id:
3882 if u.user_id == created_by.user_id:
3873 assoc.read = True
3883 assoc.read = True
3874
3884
3875 u.notifications.append(assoc)
3885 u.notifications.append(assoc)
3876 Session().add(notification)
3886 Session().add(notification)
3877
3887
3878 return notification
3888 return notification
3879
3889
3880
3890
3881 class UserNotification(Base, BaseModel):
3891 class UserNotification(Base, BaseModel):
3882 __tablename__ = 'user_to_notification'
3892 __tablename__ = 'user_to_notification'
3883 __table_args__ = (
3893 __table_args__ = (
3884 UniqueConstraint('user_id', 'notification_id'),
3894 UniqueConstraint('user_id', 'notification_id'),
3885 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3895 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3886 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3896 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3887 )
3897 )
3888 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3898 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3889 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3899 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3890 read = Column('read', Boolean, default=False)
3900 read = Column('read', Boolean, default=False)
3891 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3901 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3892
3902
3893 user = relationship('User', lazy="joined")
3903 user = relationship('User', lazy="joined")
3894 notification = relationship('Notification', lazy="joined",
3904 notification = relationship('Notification', lazy="joined",
3895 order_by=lambda: Notification.created_on.desc(),)
3905 order_by=lambda: Notification.created_on.desc(),)
3896
3906
3897 def mark_as_read(self):
3907 def mark_as_read(self):
3898 self.read = True
3908 self.read = True
3899 Session().add(self)
3909 Session().add(self)
3900
3910
3901
3911
3902 class Gist(Base, BaseModel):
3912 class Gist(Base, BaseModel):
3903 __tablename__ = 'gists'
3913 __tablename__ = 'gists'
3904 __table_args__ = (
3914 __table_args__ = (
3905 Index('g_gist_access_id_idx', 'gist_access_id'),
3915 Index('g_gist_access_id_idx', 'gist_access_id'),
3906 Index('g_created_on_idx', 'created_on'),
3916 Index('g_created_on_idx', 'created_on'),
3907 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3917 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3908 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3918 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3909 )
3919 )
3910 GIST_PUBLIC = u'public'
3920 GIST_PUBLIC = u'public'
3911 GIST_PRIVATE = u'private'
3921 GIST_PRIVATE = u'private'
3912 DEFAULT_FILENAME = u'gistfile1.txt'
3922 DEFAULT_FILENAME = u'gistfile1.txt'
3913
3923
3914 ACL_LEVEL_PUBLIC = u'acl_public'
3924 ACL_LEVEL_PUBLIC = u'acl_public'
3915 ACL_LEVEL_PRIVATE = u'acl_private'
3925 ACL_LEVEL_PRIVATE = u'acl_private'
3916
3926
3917 gist_id = Column('gist_id', Integer(), primary_key=True)
3927 gist_id = Column('gist_id', Integer(), primary_key=True)
3918 gist_access_id = Column('gist_access_id', Unicode(250))
3928 gist_access_id = Column('gist_access_id', Unicode(250))
3919 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3929 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3920 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3930 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3921 gist_expires = Column('gist_expires', Float(53), nullable=False)
3931 gist_expires = Column('gist_expires', Float(53), nullable=False)
3922 gist_type = Column('gist_type', Unicode(128), nullable=False)
3932 gist_type = Column('gist_type', Unicode(128), nullable=False)
3923 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3933 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3924 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3934 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3925 acl_level = Column('acl_level', Unicode(128), nullable=True)
3935 acl_level = Column('acl_level', Unicode(128), nullable=True)
3926
3936
3927 owner = relationship('User')
3937 owner = relationship('User')
3928
3938
3929 def __repr__(self):
3939 def __repr__(self):
3930 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3940 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3931
3941
3932 @hybrid_property
3942 @hybrid_property
3933 def description_safe(self):
3943 def description_safe(self):
3934 from rhodecode.lib import helpers as h
3944 from rhodecode.lib import helpers as h
3935 return h.escape(self.gist_description)
3945 return h.escape(self.gist_description)
3936
3946
3937 @classmethod
3947 @classmethod
3938 def get_or_404(cls, id_):
3948 def get_or_404(cls, id_):
3939 from pyramid.httpexceptions import HTTPNotFound
3949 from pyramid.httpexceptions import HTTPNotFound
3940
3950
3941 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3951 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3942 if not res:
3952 if not res:
3943 raise HTTPNotFound()
3953 raise HTTPNotFound()
3944 return res
3954 return res
3945
3955
3946 @classmethod
3956 @classmethod
3947 def get_by_access_id(cls, gist_access_id):
3957 def get_by_access_id(cls, gist_access_id):
3948 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3958 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3949
3959
3950 def gist_url(self):
3960 def gist_url(self):
3951 from rhodecode.model.gist import GistModel
3961 from rhodecode.model.gist import GistModel
3952 return GistModel().get_url(self)
3962 return GistModel().get_url(self)
3953
3963
3954 @classmethod
3964 @classmethod
3955 def base_path(cls):
3965 def base_path(cls):
3956 """
3966 """
3957 Returns base path when all gists are stored
3967 Returns base path when all gists are stored
3958
3968
3959 :param cls:
3969 :param cls:
3960 """
3970 """
3961 from rhodecode.model.gist import GIST_STORE_LOC
3971 from rhodecode.model.gist import GIST_STORE_LOC
3962 q = Session().query(RhodeCodeUi)\
3972 q = Session().query(RhodeCodeUi)\
3963 .filter(RhodeCodeUi.ui_key == URL_SEP)
3973 .filter(RhodeCodeUi.ui_key == URL_SEP)
3964 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3974 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3965 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3975 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3966
3976
3967 def get_api_data(self):
3977 def get_api_data(self):
3968 """
3978 """
3969 Common function for generating gist related data for API
3979 Common function for generating gist related data for API
3970 """
3980 """
3971 gist = self
3981 gist = self
3972 data = {
3982 data = {
3973 'gist_id': gist.gist_id,
3983 'gist_id': gist.gist_id,
3974 'type': gist.gist_type,
3984 'type': gist.gist_type,
3975 'access_id': gist.gist_access_id,
3985 'access_id': gist.gist_access_id,
3976 'description': gist.gist_description,
3986 'description': gist.gist_description,
3977 'url': gist.gist_url(),
3987 'url': gist.gist_url(),
3978 'expires': gist.gist_expires,
3988 'expires': gist.gist_expires,
3979 'created_on': gist.created_on,
3989 'created_on': gist.created_on,
3980 'modified_at': gist.modified_at,
3990 'modified_at': gist.modified_at,
3981 'content': None,
3991 'content': None,
3982 'acl_level': gist.acl_level,
3992 'acl_level': gist.acl_level,
3983 }
3993 }
3984 return data
3994 return data
3985
3995
3986 def __json__(self):
3996 def __json__(self):
3987 data = dict(
3997 data = dict(
3988 )
3998 )
3989 data.update(self.get_api_data())
3999 data.update(self.get_api_data())
3990 return data
4000 return data
3991 # SCM functions
4001 # SCM functions
3992
4002
3993 def scm_instance(self, **kwargs):
4003 def scm_instance(self, **kwargs):
3994 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
4004 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3995 return get_vcs_instance(
4005 return get_vcs_instance(
3996 repo_path=safe_str(full_repo_path), create=False)
4006 repo_path=safe_str(full_repo_path), create=False)
3997
4007
3998
4008
3999 class ExternalIdentity(Base, BaseModel):
4009 class ExternalIdentity(Base, BaseModel):
4000 __tablename__ = 'external_identities'
4010 __tablename__ = 'external_identities'
4001 __table_args__ = (
4011 __table_args__ = (
4002 Index('local_user_id_idx', 'local_user_id'),
4012 Index('local_user_id_idx', 'local_user_id'),
4003 Index('external_id_idx', 'external_id'),
4013 Index('external_id_idx', 'external_id'),
4004 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4014 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4005 'mysql_charset': 'utf8'})
4015 'mysql_charset': 'utf8'})
4006
4016
4007 external_id = Column('external_id', Unicode(255), default=u'',
4017 external_id = Column('external_id', Unicode(255), default=u'',
4008 primary_key=True)
4018 primary_key=True)
4009 external_username = Column('external_username', Unicode(1024), default=u'')
4019 external_username = Column('external_username', Unicode(1024), default=u'')
4010 local_user_id = Column('local_user_id', Integer(),
4020 local_user_id = Column('local_user_id', Integer(),
4011 ForeignKey('users.user_id'), primary_key=True)
4021 ForeignKey('users.user_id'), primary_key=True)
4012 provider_name = Column('provider_name', Unicode(255), default=u'',
4022 provider_name = Column('provider_name', Unicode(255), default=u'',
4013 primary_key=True)
4023 primary_key=True)
4014 access_token = Column('access_token', String(1024), default=u'')
4024 access_token = Column('access_token', String(1024), default=u'')
4015 alt_token = Column('alt_token', String(1024), default=u'')
4025 alt_token = Column('alt_token', String(1024), default=u'')
4016 token_secret = Column('token_secret', String(1024), default=u'')
4026 token_secret = Column('token_secret', String(1024), default=u'')
4017
4027
4018 @classmethod
4028 @classmethod
4019 def by_external_id_and_provider(cls, external_id, provider_name,
4029 def by_external_id_and_provider(cls, external_id, provider_name,
4020 local_user_id=None):
4030 local_user_id=None):
4021 """
4031 """
4022 Returns ExternalIdentity instance based on search params
4032 Returns ExternalIdentity instance based on search params
4023
4033
4024 :param external_id:
4034 :param external_id:
4025 :param provider_name:
4035 :param provider_name:
4026 :return: ExternalIdentity
4036 :return: ExternalIdentity
4027 """
4037 """
4028 query = cls.query()
4038 query = cls.query()
4029 query = query.filter(cls.external_id == external_id)
4039 query = query.filter(cls.external_id == external_id)
4030 query = query.filter(cls.provider_name == provider_name)
4040 query = query.filter(cls.provider_name == provider_name)
4031 if local_user_id:
4041 if local_user_id:
4032 query = query.filter(cls.local_user_id == local_user_id)
4042 query = query.filter(cls.local_user_id == local_user_id)
4033 return query.first()
4043 return query.first()
4034
4044
4035 @classmethod
4045 @classmethod
4036 def user_by_external_id_and_provider(cls, external_id, provider_name):
4046 def user_by_external_id_and_provider(cls, external_id, provider_name):
4037 """
4047 """
4038 Returns User instance based on search params
4048 Returns User instance based on search params
4039
4049
4040 :param external_id:
4050 :param external_id:
4041 :param provider_name:
4051 :param provider_name:
4042 :return: User
4052 :return: User
4043 """
4053 """
4044 query = User.query()
4054 query = User.query()
4045 query = query.filter(cls.external_id == external_id)
4055 query = query.filter(cls.external_id == external_id)
4046 query = query.filter(cls.provider_name == provider_name)
4056 query = query.filter(cls.provider_name == provider_name)
4047 query = query.filter(User.user_id == cls.local_user_id)
4057 query = query.filter(User.user_id == cls.local_user_id)
4048 return query.first()
4058 return query.first()
4049
4059
4050 @classmethod
4060 @classmethod
4051 def by_local_user_id(cls, local_user_id):
4061 def by_local_user_id(cls, local_user_id):
4052 """
4062 """
4053 Returns all tokens for user
4063 Returns all tokens for user
4054
4064
4055 :param local_user_id:
4065 :param local_user_id:
4056 :return: ExternalIdentity
4066 :return: ExternalIdentity
4057 """
4067 """
4058 query = cls.query()
4068 query = cls.query()
4059 query = query.filter(cls.local_user_id == local_user_id)
4069 query = query.filter(cls.local_user_id == local_user_id)
4060 return query
4070 return query
4061
4071
4062
4072
4063 class Integration(Base, BaseModel):
4073 class Integration(Base, BaseModel):
4064 __tablename__ = 'integrations'
4074 __tablename__ = 'integrations'
4065 __table_args__ = (
4075 __table_args__ = (
4066 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4076 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4067 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
4077 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
4068 )
4078 )
4069
4079
4070 integration_id = Column('integration_id', Integer(), primary_key=True)
4080 integration_id = Column('integration_id', Integer(), primary_key=True)
4071 integration_type = Column('integration_type', String(255))
4081 integration_type = Column('integration_type', String(255))
4072 enabled = Column('enabled', Boolean(), nullable=False)
4082 enabled = Column('enabled', Boolean(), nullable=False)
4073 name = Column('name', String(255), nullable=False)
4083 name = Column('name', String(255), nullable=False)
4074 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4084 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4075 default=False)
4085 default=False)
4076
4086
4077 settings = Column(
4087 settings = Column(
4078 'settings_json', MutationObj.as_mutable(
4088 'settings_json', MutationObj.as_mutable(
4079 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4089 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4080 repo_id = Column(
4090 repo_id = Column(
4081 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4091 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4082 nullable=True, unique=None, default=None)
4092 nullable=True, unique=None, default=None)
4083 repo = relationship('Repository', lazy='joined')
4093 repo = relationship('Repository', lazy='joined')
4084
4094
4085 repo_group_id = Column(
4095 repo_group_id = Column(
4086 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4096 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4087 nullable=True, unique=None, default=None)
4097 nullable=True, unique=None, default=None)
4088 repo_group = relationship('RepoGroup', lazy='joined')
4098 repo_group = relationship('RepoGroup', lazy='joined')
4089
4099
4090 @property
4100 @property
4091 def scope(self):
4101 def scope(self):
4092 if self.repo:
4102 if self.repo:
4093 return repr(self.repo)
4103 return repr(self.repo)
4094 if self.repo_group:
4104 if self.repo_group:
4095 if self.child_repos_only:
4105 if self.child_repos_only:
4096 return repr(self.repo_group) + ' (child repos only)'
4106 return repr(self.repo_group) + ' (child repos only)'
4097 else:
4107 else:
4098 return repr(self.repo_group) + ' (recursive)'
4108 return repr(self.repo_group) + ' (recursive)'
4099 if self.child_repos_only:
4109 if self.child_repos_only:
4100 return 'root_repos'
4110 return 'root_repos'
4101 return 'global'
4111 return 'global'
4102
4112
4103 def __repr__(self):
4113 def __repr__(self):
4104 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4114 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4105
4115
4106
4116
4107 class RepoReviewRuleUser(Base, BaseModel):
4117 class RepoReviewRuleUser(Base, BaseModel):
4108 __tablename__ = 'repo_review_rules_users'
4118 __tablename__ = 'repo_review_rules_users'
4109 __table_args__ = (
4119 __table_args__ = (
4110 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4120 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4111 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4121 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4112 )
4122 )
4113
4123
4114 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4124 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4115 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4125 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4116 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4126 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4117 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4127 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4118 user = relationship('User')
4128 user = relationship('User')
4119
4129
4120 def rule_data(self):
4130 def rule_data(self):
4121 return {
4131 return {
4122 'mandatory': self.mandatory
4132 'mandatory': self.mandatory
4123 }
4133 }
4124
4134
4125
4135
4126 class RepoReviewRuleUserGroup(Base, BaseModel):
4136 class RepoReviewRuleUserGroup(Base, BaseModel):
4127 __tablename__ = 'repo_review_rules_users_groups'
4137 __tablename__ = 'repo_review_rules_users_groups'
4128 __table_args__ = (
4138 __table_args__ = (
4129 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4139 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4130 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4140 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4131 )
4141 )
4132 VOTE_RULE_ALL = -1
4142 VOTE_RULE_ALL = -1
4133
4143
4134 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4144 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4135 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4145 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4136 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4146 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4137 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4147 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4138 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4148 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4139 users_group = relationship('UserGroup')
4149 users_group = relationship('UserGroup')
4140
4150
4141 def rule_data(self):
4151 def rule_data(self):
4142 return {
4152 return {
4143 'mandatory': self.mandatory,
4153 'mandatory': self.mandatory,
4144 'vote_rule': self.vote_rule
4154 'vote_rule': self.vote_rule
4145 }
4155 }
4146
4156
4147 @property
4157 @property
4148 def vote_rule_label(self):
4158 def vote_rule_label(self):
4149 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4159 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4150 return 'all must vote'
4160 return 'all must vote'
4151 else:
4161 else:
4152 return 'min. vote {}'.format(self.vote_rule)
4162 return 'min. vote {}'.format(self.vote_rule)
4153
4163
4154
4164
4155 class RepoReviewRule(Base, BaseModel):
4165 class RepoReviewRule(Base, BaseModel):
4156 __tablename__ = 'repo_review_rules'
4166 __tablename__ = 'repo_review_rules'
4157 __table_args__ = (
4167 __table_args__ = (
4158 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4168 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4159 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4169 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4160 )
4170 )
4161
4171
4162 repo_review_rule_id = Column(
4172 repo_review_rule_id = Column(
4163 'repo_review_rule_id', Integer(), primary_key=True)
4173 'repo_review_rule_id', Integer(), primary_key=True)
4164 repo_id = Column(
4174 repo_id = Column(
4165 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4175 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4166 repo = relationship('Repository', backref='review_rules')
4176 repo = relationship('Repository', backref='review_rules')
4167
4177
4168 review_rule_name = Column('review_rule_name', String(255))
4178 review_rule_name = Column('review_rule_name', String(255))
4169 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4179 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4170 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4180 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4171 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4181 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4172
4182
4173 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4183 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4174 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4184 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4175 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4185 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4176 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4186 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4177
4187
4178 rule_users = relationship('RepoReviewRuleUser')
4188 rule_users = relationship('RepoReviewRuleUser')
4179 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4189 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4180
4190
4181 def _validate_glob(self, value):
4191 def _validate_glob(self, value):
4182 re.compile('^' + glob2re(value) + '$')
4192 re.compile('^' + glob2re(value) + '$')
4183
4193
4184 @hybrid_property
4194 @hybrid_property
4185 def source_branch_pattern(self):
4195 def source_branch_pattern(self):
4186 return self._branch_pattern or '*'
4196 return self._branch_pattern or '*'
4187
4197
4188 @source_branch_pattern.setter
4198 @source_branch_pattern.setter
4189 def source_branch_pattern(self, value):
4199 def source_branch_pattern(self, value):
4190 self._validate_glob(value)
4200 self._validate_glob(value)
4191 self._branch_pattern = value or '*'
4201 self._branch_pattern = value or '*'
4192
4202
4193 @hybrid_property
4203 @hybrid_property
4194 def target_branch_pattern(self):
4204 def target_branch_pattern(self):
4195 return self._target_branch_pattern or '*'
4205 return self._target_branch_pattern or '*'
4196
4206
4197 @target_branch_pattern.setter
4207 @target_branch_pattern.setter
4198 def target_branch_pattern(self, value):
4208 def target_branch_pattern(self, value):
4199 self._validate_glob(value)
4209 self._validate_glob(value)
4200 self._target_branch_pattern = value or '*'
4210 self._target_branch_pattern = value or '*'
4201
4211
4202 @hybrid_property
4212 @hybrid_property
4203 def file_pattern(self):
4213 def file_pattern(self):
4204 return self._file_pattern or '*'
4214 return self._file_pattern or '*'
4205
4215
4206 @file_pattern.setter
4216 @file_pattern.setter
4207 def file_pattern(self, value):
4217 def file_pattern(self, value):
4208 self._validate_glob(value)
4218 self._validate_glob(value)
4209 self._file_pattern = value or '*'
4219 self._file_pattern = value or '*'
4210
4220
4211 def matches(self, source_branch, target_branch, files_changed):
4221 def matches(self, source_branch, target_branch, files_changed):
4212 """
4222 """
4213 Check if this review rule matches a branch/files in a pull request
4223 Check if this review rule matches a branch/files in a pull request
4214
4224
4215 :param branch: branch name for the commit
4225 :param branch: branch name for the commit
4216 :param files_changed: list of file paths changed in the pull request
4226 :param files_changed: list of file paths changed in the pull request
4217 """
4227 """
4218
4228
4219 source_branch = source_branch or ''
4229 source_branch = source_branch or ''
4220 target_branch = target_branch or ''
4230 target_branch = target_branch or ''
4221 files_changed = files_changed or []
4231 files_changed = files_changed or []
4222
4232
4223 branch_matches = True
4233 branch_matches = True
4224 if source_branch or target_branch:
4234 if source_branch or target_branch:
4225 source_branch_regex = re.compile(
4235 source_branch_regex = re.compile(
4226 '^' + glob2re(self.source_branch_pattern) + '$')
4236 '^' + glob2re(self.source_branch_pattern) + '$')
4227 target_branch_regex = re.compile(
4237 target_branch_regex = re.compile(
4228 '^' + glob2re(self.target_branch_pattern) + '$')
4238 '^' + glob2re(self.target_branch_pattern) + '$')
4229
4239
4230 branch_matches = (
4240 branch_matches = (
4231 bool(source_branch_regex.search(source_branch)) and
4241 bool(source_branch_regex.search(source_branch)) and
4232 bool(target_branch_regex.search(target_branch))
4242 bool(target_branch_regex.search(target_branch))
4233 )
4243 )
4234
4244
4235 files_matches = True
4245 files_matches = True
4236 if self.file_pattern != '*':
4246 if self.file_pattern != '*':
4237 files_matches = False
4247 files_matches = False
4238 file_regex = re.compile(glob2re(self.file_pattern))
4248 file_regex = re.compile(glob2re(self.file_pattern))
4239 for filename in files_changed:
4249 for filename in files_changed:
4240 if file_regex.search(filename):
4250 if file_regex.search(filename):
4241 files_matches = True
4251 files_matches = True
4242 break
4252 break
4243
4253
4244 return branch_matches and files_matches
4254 return branch_matches and files_matches
4245
4255
4246 @property
4256 @property
4247 def review_users(self):
4257 def review_users(self):
4248 """ Returns the users which this rule applies to """
4258 """ Returns the users which this rule applies to """
4249
4259
4250 users = collections.OrderedDict()
4260 users = collections.OrderedDict()
4251
4261
4252 for rule_user in self.rule_users:
4262 for rule_user in self.rule_users:
4253 if rule_user.user.active:
4263 if rule_user.user.active:
4254 if rule_user.user not in users:
4264 if rule_user.user not in users:
4255 users[rule_user.user.username] = {
4265 users[rule_user.user.username] = {
4256 'user': rule_user.user,
4266 'user': rule_user.user,
4257 'source': 'user',
4267 'source': 'user',
4258 'source_data': {},
4268 'source_data': {},
4259 'data': rule_user.rule_data()
4269 'data': rule_user.rule_data()
4260 }
4270 }
4261
4271
4262 for rule_user_group in self.rule_user_groups:
4272 for rule_user_group in self.rule_user_groups:
4263 source_data = {
4273 source_data = {
4264 'user_group_id': rule_user_group.users_group.users_group_id,
4274 'user_group_id': rule_user_group.users_group.users_group_id,
4265 'name': rule_user_group.users_group.users_group_name,
4275 'name': rule_user_group.users_group.users_group_name,
4266 'members': len(rule_user_group.users_group.members)
4276 'members': len(rule_user_group.users_group.members)
4267 }
4277 }
4268 for member in rule_user_group.users_group.members:
4278 for member in rule_user_group.users_group.members:
4269 if member.user.active:
4279 if member.user.active:
4270 key = member.user.username
4280 key = member.user.username
4271 if key in users:
4281 if key in users:
4272 # skip this member as we have him already
4282 # skip this member as we have him already
4273 # this prevents from override the "first" matched
4283 # this prevents from override the "first" matched
4274 # users with duplicates in multiple groups
4284 # users with duplicates in multiple groups
4275 continue
4285 continue
4276
4286
4277 users[key] = {
4287 users[key] = {
4278 'user': member.user,
4288 'user': member.user,
4279 'source': 'user_group',
4289 'source': 'user_group',
4280 'source_data': source_data,
4290 'source_data': source_data,
4281 'data': rule_user_group.rule_data()
4291 'data': rule_user_group.rule_data()
4282 }
4292 }
4283
4293
4284 return users
4294 return users
4285
4295
4286 def user_group_vote_rule(self):
4296 def user_group_vote_rule(self):
4287 rules = []
4297 rules = []
4288 if self.rule_user_groups:
4298 if self.rule_user_groups:
4289 for user_group in self.rule_user_groups:
4299 for user_group in self.rule_user_groups:
4290 rules.append(user_group)
4300 rules.append(user_group)
4291 return rules
4301 return rules
4292
4302
4293 def __repr__(self):
4303 def __repr__(self):
4294 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4304 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4295 self.repo_review_rule_id, self.repo)
4305 self.repo_review_rule_id, self.repo)
4296
4306
4297
4307
4298 class ScheduleEntry(Base, BaseModel):
4308 class ScheduleEntry(Base, BaseModel):
4299 __tablename__ = 'schedule_entries'
4309 __tablename__ = 'schedule_entries'
4300 __table_args__ = (
4310 __table_args__ = (
4301 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4311 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4302 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4312 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4303 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4313 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4304 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4314 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4305 )
4315 )
4306 schedule_types = ['crontab', 'timedelta', 'integer']
4316 schedule_types = ['crontab', 'timedelta', 'integer']
4307 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4317 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4308
4318
4309 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4319 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4310 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4320 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4311 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4321 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4312
4322
4313 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4323 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4314 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4324 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4315
4325
4316 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4326 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4317 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4327 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4318
4328
4319 # task
4329 # task
4320 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4330 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4321 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4331 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4322 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4332 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4323 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4333 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4324
4334
4325 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4335 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4326 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4336 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4327
4337
4328 @hybrid_property
4338 @hybrid_property
4329 def schedule_type(self):
4339 def schedule_type(self):
4330 return self._schedule_type
4340 return self._schedule_type
4331
4341
4332 @schedule_type.setter
4342 @schedule_type.setter
4333 def schedule_type(self, val):
4343 def schedule_type(self, val):
4334 if val not in self.schedule_types:
4344 if val not in self.schedule_types:
4335 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4345 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4336 val, self.schedule_type))
4346 val, self.schedule_type))
4337
4347
4338 self._schedule_type = val
4348 self._schedule_type = val
4339
4349
4340 @classmethod
4350 @classmethod
4341 def get_uid(cls, obj):
4351 def get_uid(cls, obj):
4342 args = obj.task_args
4352 args = obj.task_args
4343 kwargs = obj.task_kwargs
4353 kwargs = obj.task_kwargs
4344 if isinstance(args, JsonRaw):
4354 if isinstance(args, JsonRaw):
4345 try:
4355 try:
4346 args = json.loads(args)
4356 args = json.loads(args)
4347 except ValueError:
4357 except ValueError:
4348 args = tuple()
4358 args = tuple()
4349
4359
4350 if isinstance(kwargs, JsonRaw):
4360 if isinstance(kwargs, JsonRaw):
4351 try:
4361 try:
4352 kwargs = json.loads(kwargs)
4362 kwargs = json.loads(kwargs)
4353 except ValueError:
4363 except ValueError:
4354 kwargs = dict()
4364 kwargs = dict()
4355
4365
4356 dot_notation = obj.task_dot_notation
4366 dot_notation = obj.task_dot_notation
4357 val = '.'.join(map(safe_str, [
4367 val = '.'.join(map(safe_str, [
4358 sorted(dot_notation), args, sorted(kwargs.items())]))
4368 sorted(dot_notation), args, sorted(kwargs.items())]))
4359 return hashlib.sha1(val).hexdigest()
4369 return hashlib.sha1(val).hexdigest()
4360
4370
4361 @classmethod
4371 @classmethod
4362 def get_by_schedule_name(cls, schedule_name):
4372 def get_by_schedule_name(cls, schedule_name):
4363 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4373 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4364
4374
4365 @classmethod
4375 @classmethod
4366 def get_by_schedule_id(cls, schedule_id):
4376 def get_by_schedule_id(cls, schedule_id):
4367 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4377 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4368
4378
4369 @property
4379 @property
4370 def task(self):
4380 def task(self):
4371 return self.task_dot_notation
4381 return self.task_dot_notation
4372
4382
4373 @property
4383 @property
4374 def schedule(self):
4384 def schedule(self):
4375 from rhodecode.lib.celerylib.utils import raw_2_schedule
4385 from rhodecode.lib.celerylib.utils import raw_2_schedule
4376 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4386 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4377 return schedule
4387 return schedule
4378
4388
4379 @property
4389 @property
4380 def args(self):
4390 def args(self):
4381 try:
4391 try:
4382 return list(self.task_args or [])
4392 return list(self.task_args or [])
4383 except ValueError:
4393 except ValueError:
4384 return list()
4394 return list()
4385
4395
4386 @property
4396 @property
4387 def kwargs(self):
4397 def kwargs(self):
4388 try:
4398 try:
4389 return dict(self.task_kwargs or {})
4399 return dict(self.task_kwargs or {})
4390 except ValueError:
4400 except ValueError:
4391 return dict()
4401 return dict()
4392
4402
4393 def _as_raw(self, val):
4403 def _as_raw(self, val):
4394 if hasattr(val, 'de_coerce'):
4404 if hasattr(val, 'de_coerce'):
4395 val = val.de_coerce()
4405 val = val.de_coerce()
4396 if val:
4406 if val:
4397 val = json.dumps(val)
4407 val = json.dumps(val)
4398
4408
4399 return val
4409 return val
4400
4410
4401 @property
4411 @property
4402 def schedule_definition_raw(self):
4412 def schedule_definition_raw(self):
4403 return self._as_raw(self.schedule_definition)
4413 return self._as_raw(self.schedule_definition)
4404
4414
4405 @property
4415 @property
4406 def args_raw(self):
4416 def args_raw(self):
4407 return self._as_raw(self.task_args)
4417 return self._as_raw(self.task_args)
4408
4418
4409 @property
4419 @property
4410 def kwargs_raw(self):
4420 def kwargs_raw(self):
4411 return self._as_raw(self.task_kwargs)
4421 return self._as_raw(self.task_kwargs)
4412
4422
4413 def __repr__(self):
4423 def __repr__(self):
4414 return '<DB:ScheduleEntry({}:{})>'.format(
4424 return '<DB:ScheduleEntry({}:{})>'.format(
4415 self.schedule_entry_id, self.schedule_name)
4425 self.schedule_entry_id, self.schedule_name)
4416
4426
4417
4427
4418 @event.listens_for(ScheduleEntry, 'before_update')
4428 @event.listens_for(ScheduleEntry, 'before_update')
4419 def update_task_uid(mapper, connection, target):
4429 def update_task_uid(mapper, connection, target):
4420 target.task_uid = ScheduleEntry.get_uid(target)
4430 target.task_uid = ScheduleEntry.get_uid(target)
4421
4431
4422
4432
4423 @event.listens_for(ScheduleEntry, 'before_insert')
4433 @event.listens_for(ScheduleEntry, 'before_insert')
4424 def set_task_uid(mapper, connection, target):
4434 def set_task_uid(mapper, connection, target):
4425 target.task_uid = ScheduleEntry.get_uid(target)
4435 target.task_uid = ScheduleEntry.get_uid(target)
4426
4436
4427
4437
4428 class DbMigrateVersion(Base, BaseModel):
4438 class DbMigrateVersion(Base, BaseModel):
4429 __tablename__ = 'db_migrate_version'
4439 __tablename__ = 'db_migrate_version'
4430 __table_args__ = (
4440 __table_args__ = (
4431 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4441 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4432 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4442 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4433 )
4443 )
4434 repository_id = Column('repository_id', String(250), primary_key=True)
4444 repository_id = Column('repository_id', String(250), primary_key=True)
4435 repository_path = Column('repository_path', Text)
4445 repository_path = Column('repository_path', Text)
4436 version = Column('version', Integer)
4446 version = Column('version', Integer)
4437
4447
4438
4448
4439 class DbSession(Base, BaseModel):
4449 class DbSession(Base, BaseModel):
4440 __tablename__ = 'db_session'
4450 __tablename__ = 'db_session'
4441 __table_args__ = (
4451 __table_args__ = (
4442 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4452 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4443 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4453 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4444 )
4454 )
4445
4455
4446 def __repr__(self):
4456 def __repr__(self):
4447 return '<DB:DbSession({})>'.format(self.id)
4457 return '<DB:DbSession({})>'.format(self.id)
4448
4458
4449 id = Column('id', Integer())
4459 id = Column('id', Integer())
4450 namespace = Column('namespace', String(255), primary_key=True)
4460 namespace = Column('namespace', String(255), primary_key=True)
4451 accessed = Column('accessed', DateTime, nullable=False)
4461 accessed = Column('accessed', DateTime, nullable=False)
4452 created = Column('created', DateTime, nullable=False)
4462 created = Column('created', DateTime, nullable=False)
4453 data = Column('data', PickleType, nullable=False)
4463 data = Column('data', PickleType, nullable=False)
@@ -1,615 +1,616 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2018 RhodeCode GmbH
3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
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/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 """
21 """
22 this is forms validation classes
22 this is forms validation classes
23 http://formencode.org/module-formencode.validators.html
23 http://formencode.org/module-formencode.validators.html
24 for list off all availible validators
24 for list off all availible validators
25
25
26 we can create our own validators
26 we can create our own validators
27
27
28 The table below outlines the options which can be used in a schema in addition to the validators themselves
28 The table below outlines the options which can be used in a schema in addition to the validators themselves
29 pre_validators [] These validators will be applied before the schema
29 pre_validators [] These validators will be applied before the schema
30 chained_validators [] These validators will be applied after the schema
30 chained_validators [] These validators will be applied after the schema
31 allow_extra_fields False If True, then it is not an error when keys that aren't associated with a validator are present
31 allow_extra_fields False If True, then it is not an error when keys that aren't associated with a validator are present
32 filter_extra_fields False If True, then keys that aren't associated with a validator are removed
32 filter_extra_fields False If True, then keys that aren't associated with a validator are removed
33 if_key_missing NoDefault If this is given, then any keys that aren't available but are expected will be replaced with this value (and then validated). This does not override a present .if_missing attribute on validators. NoDefault is a special FormEncode class to mean that no default values has been specified and therefore missing keys shouldn't take a default value.
33 if_key_missing NoDefault If this is given, then any keys that aren't available but are expected will be replaced with this value (and then validated). This does not override a present .if_missing attribute on validators. NoDefault is a special FormEncode class to mean that no default values has been specified and therefore missing keys shouldn't take a default value.
34 ignore_key_missing False If True, then missing keys will be missing in the result, if the validator doesn't have .if_missing on it already
34 ignore_key_missing False If True, then missing keys will be missing in the result, if the validator doesn't have .if_missing on it already
35
35
36
36
37 <name> = formencode.validators.<name of validator>
37 <name> = formencode.validators.<name of validator>
38 <name> must equal form name
38 <name> must equal form name
39 list=[1,2,3,4,5]
39 list=[1,2,3,4,5]
40 for SELECT use formencode.All(OneOf(list), Int())
40 for SELECT use formencode.All(OneOf(list), Int())
41
41
42 """
42 """
43
43
44 import deform
44 import deform
45 import logging
45 import logging
46 import formencode
46 import formencode
47
47
48 from pkg_resources import resource_filename
48 from pkg_resources import resource_filename
49 from formencode import All, Pipe
49 from formencode import All, Pipe
50
50
51 from pyramid.threadlocal import get_current_request
51 from pyramid.threadlocal import get_current_request
52
52
53 from rhodecode import BACKENDS
53 from rhodecode import BACKENDS
54 from rhodecode.lib import helpers
54 from rhodecode.lib import helpers
55 from rhodecode.model import validators as v
55 from rhodecode.model import validators as v
56
56
57 log = logging.getLogger(__name__)
57 log = logging.getLogger(__name__)
58
58
59
59
60 deform_templates = resource_filename('deform', 'templates')
60 deform_templates = resource_filename('deform', 'templates')
61 rhodecode_templates = resource_filename('rhodecode', 'templates/forms')
61 rhodecode_templates = resource_filename('rhodecode', 'templates/forms')
62 search_path = (rhodecode_templates, deform_templates)
62 search_path = (rhodecode_templates, deform_templates)
63
63
64
64
65 class RhodecodeFormZPTRendererFactory(deform.ZPTRendererFactory):
65 class RhodecodeFormZPTRendererFactory(deform.ZPTRendererFactory):
66 """ Subclass of ZPTRendererFactory to add rhodecode context variables """
66 """ Subclass of ZPTRendererFactory to add rhodecode context variables """
67 def __call__(self, template_name, **kw):
67 def __call__(self, template_name, **kw):
68 kw['h'] = helpers
68 kw['h'] = helpers
69 kw['request'] = get_current_request()
69 kw['request'] = get_current_request()
70 return self.load(template_name)(**kw)
70 return self.load(template_name)(**kw)
71
71
72
72
73 form_renderer = RhodecodeFormZPTRendererFactory(search_path)
73 form_renderer = RhodecodeFormZPTRendererFactory(search_path)
74 deform.Form.set_default_renderer(form_renderer)
74 deform.Form.set_default_renderer(form_renderer)
75
75
76
76
77 def LoginForm(localizer):
77 def LoginForm(localizer):
78 _ = localizer
78 _ = localizer
79
79
80 class _LoginForm(formencode.Schema):
80 class _LoginForm(formencode.Schema):
81 allow_extra_fields = True
81 allow_extra_fields = True
82 filter_extra_fields = True
82 filter_extra_fields = True
83 username = v.UnicodeString(
83 username = v.UnicodeString(
84 strip=True,
84 strip=True,
85 min=1,
85 min=1,
86 not_empty=True,
86 not_empty=True,
87 messages={
87 messages={
88 'empty': _(u'Please enter a login'),
88 'empty': _(u'Please enter a login'),
89 'tooShort': _(u'Enter a value %(min)i characters long or more')
89 'tooShort': _(u'Enter a value %(min)i characters long or more')
90 }
90 }
91 )
91 )
92
92
93 password = v.UnicodeString(
93 password = v.UnicodeString(
94 strip=False,
94 strip=False,
95 min=3,
95 min=3,
96 max=72,
96 max=72,
97 not_empty=True,
97 not_empty=True,
98 messages={
98 messages={
99 'empty': _(u'Please enter a password'),
99 'empty': _(u'Please enter a password'),
100 'tooShort': _(u'Enter %(min)i characters or more')}
100 'tooShort': _(u'Enter %(min)i characters or more')}
101 )
101 )
102
102
103 remember = v.StringBoolean(if_missing=False)
103 remember = v.StringBoolean(if_missing=False)
104
104
105 chained_validators = [v.ValidAuth(localizer)]
105 chained_validators = [v.ValidAuth(localizer)]
106 return _LoginForm
106 return _LoginForm
107
107
108
108
109 def UserForm(localizer, edit=False, available_languages=None, old_data=None):
109 def UserForm(localizer, edit=False, available_languages=None, old_data=None):
110 old_data = old_data or {}
110 old_data = old_data or {}
111 available_languages = available_languages or []
111 available_languages = available_languages or []
112 _ = localizer
112 _ = localizer
113
113
114 class _UserForm(formencode.Schema):
114 class _UserForm(formencode.Schema):
115 allow_extra_fields = True
115 allow_extra_fields = True
116 filter_extra_fields = True
116 filter_extra_fields = True
117 username = All(v.UnicodeString(strip=True, min=1, not_empty=True),
117 username = All(v.UnicodeString(strip=True, min=1, not_empty=True),
118 v.ValidUsername(localizer, edit, old_data))
118 v.ValidUsername(localizer, edit, old_data))
119 if edit:
119 if edit:
120 new_password = All(
120 new_password = All(
121 v.ValidPassword(localizer),
121 v.ValidPassword(localizer),
122 v.UnicodeString(strip=False, min=6, max=72, not_empty=False)
122 v.UnicodeString(strip=False, min=6, max=72, not_empty=False)
123 )
123 )
124 password_confirmation = All(
124 password_confirmation = All(
125 v.ValidPassword(localizer),
125 v.ValidPassword(localizer),
126 v.UnicodeString(strip=False, min=6, max=72, not_empty=False),
126 v.UnicodeString(strip=False, min=6, max=72, not_empty=False),
127 )
127 )
128 admin = v.StringBoolean(if_missing=False)
128 admin = v.StringBoolean(if_missing=False)
129 else:
129 else:
130 password = All(
130 password = All(
131 v.ValidPassword(localizer),
131 v.ValidPassword(localizer),
132 v.UnicodeString(strip=False, min=6, max=72, not_empty=True)
132 v.UnicodeString(strip=False, min=6, max=72, not_empty=True)
133 )
133 )
134 password_confirmation = All(
134 password_confirmation = All(
135 v.ValidPassword(localizer),
135 v.ValidPassword(localizer),
136 v.UnicodeString(strip=False, min=6, max=72, not_empty=False)
136 v.UnicodeString(strip=False, min=6, max=72, not_empty=False)
137 )
137 )
138
138
139 password_change = v.StringBoolean(if_missing=False)
139 password_change = v.StringBoolean(if_missing=False)
140 create_repo_group = v.StringBoolean(if_missing=False)
140 create_repo_group = v.StringBoolean(if_missing=False)
141
141
142 active = v.StringBoolean(if_missing=False)
142 active = v.StringBoolean(if_missing=False)
143 firstname = v.UnicodeString(strip=True, min=1, not_empty=False)
143 firstname = v.UnicodeString(strip=True, min=1, not_empty=False)
144 lastname = v.UnicodeString(strip=True, min=1, not_empty=False)
144 lastname = v.UnicodeString(strip=True, min=1, not_empty=False)
145 email = All(v.UniqSystemEmail(localizer, old_data), v.Email(not_empty=True))
145 email = All(v.UniqSystemEmail(localizer, old_data), v.Email(not_empty=True))
146 extern_name = v.UnicodeString(strip=True)
146 extern_name = v.UnicodeString(strip=True)
147 extern_type = v.UnicodeString(strip=True)
147 extern_type = v.UnicodeString(strip=True)
148 language = v.OneOf(available_languages, hideList=False,
148 language = v.OneOf(available_languages, hideList=False,
149 testValueList=True, if_missing=None)
149 testValueList=True, if_missing=None)
150 chained_validators = [v.ValidPasswordsMatch(localizer)]
150 chained_validators = [v.ValidPasswordsMatch(localizer)]
151 return _UserForm
151 return _UserForm
152
152
153
153
154 def UserGroupForm(localizer, edit=False, old_data=None, allow_disabled=False):
154 def UserGroupForm(localizer, edit=False, old_data=None, allow_disabled=False):
155 old_data = old_data or {}
155 old_data = old_data or {}
156 _ = localizer
156 _ = localizer
157
157
158 class _UserGroupForm(formencode.Schema):
158 class _UserGroupForm(formencode.Schema):
159 allow_extra_fields = True
159 allow_extra_fields = True
160 filter_extra_fields = True
160 filter_extra_fields = True
161
161
162 users_group_name = All(
162 users_group_name = All(
163 v.UnicodeString(strip=True, min=1, not_empty=True),
163 v.UnicodeString(strip=True, min=1, not_empty=True),
164 v.ValidUserGroup(localizer, edit, old_data)
164 v.ValidUserGroup(localizer, edit, old_data)
165 )
165 )
166 user_group_description = v.UnicodeString(strip=True, min=1,
166 user_group_description = v.UnicodeString(strip=True, min=1,
167 not_empty=False)
167 not_empty=False)
168
168
169 users_group_active = v.StringBoolean(if_missing=False)
169 users_group_active = v.StringBoolean(if_missing=False)
170
170
171 if edit:
171 if edit:
172 # this is user group owner
172 # this is user group owner
173 user = All(
173 user = All(
174 v.UnicodeString(not_empty=True),
174 v.UnicodeString(not_empty=True),
175 v.ValidRepoUser(localizer, allow_disabled))
175 v.ValidRepoUser(localizer, allow_disabled))
176 return _UserGroupForm
176 return _UserGroupForm
177
177
178
178
179 def RepoGroupForm(localizer, edit=False, old_data=None, available_groups=None,
179 def RepoGroupForm(localizer, edit=False, old_data=None, available_groups=None,
180 can_create_in_root=False, allow_disabled=False):
180 can_create_in_root=False, allow_disabled=False):
181 _ = localizer
181 _ = localizer
182 old_data = old_data or {}
182 old_data = old_data or {}
183 available_groups = available_groups or []
183 available_groups = available_groups or []
184
184
185 class _RepoGroupForm(formencode.Schema):
185 class _RepoGroupForm(formencode.Schema):
186 allow_extra_fields = True
186 allow_extra_fields = True
187 filter_extra_fields = False
187 filter_extra_fields = False
188
188
189 group_name = All(v.UnicodeString(strip=True, min=1, not_empty=True),
189 group_name = All(v.UnicodeString(strip=True, min=1, not_empty=True),
190 v.SlugifyName(localizer),)
190 v.SlugifyName(localizer),)
191 group_description = v.UnicodeString(strip=True, min=1,
191 group_description = v.UnicodeString(strip=True, min=1,
192 not_empty=False)
192 not_empty=False)
193 group_copy_permissions = v.StringBoolean(if_missing=False)
193 group_copy_permissions = v.StringBoolean(if_missing=False)
194
194
195 group_parent_id = v.OneOf(available_groups, hideList=False,
195 group_parent_id = v.OneOf(available_groups, hideList=False,
196 testValueList=True, not_empty=True)
196 testValueList=True, not_empty=True)
197 enable_locking = v.StringBoolean(if_missing=False)
197 enable_locking = v.StringBoolean(if_missing=False)
198 chained_validators = [
198 chained_validators = [
199 v.ValidRepoGroup(localizer, edit, old_data, can_create_in_root)]
199 v.ValidRepoGroup(localizer, edit, old_data, can_create_in_root)]
200
200
201 if edit:
201 if edit:
202 # this is repo group owner
202 # this is repo group owner
203 user = All(
203 user = All(
204 v.UnicodeString(not_empty=True),
204 v.UnicodeString(not_empty=True),
205 v.ValidRepoUser(localizer, allow_disabled))
205 v.ValidRepoUser(localizer, allow_disabled))
206 return _RepoGroupForm
206 return _RepoGroupForm
207
207
208
208
209 def RegisterForm(localizer, edit=False, old_data=None):
209 def RegisterForm(localizer, edit=False, old_data=None):
210 _ = localizer
210 _ = localizer
211 old_data = old_data or {}
211 old_data = old_data or {}
212
212
213 class _RegisterForm(formencode.Schema):
213 class _RegisterForm(formencode.Schema):
214 allow_extra_fields = True
214 allow_extra_fields = True
215 filter_extra_fields = True
215 filter_extra_fields = True
216 username = All(
216 username = All(
217 v.ValidUsername(localizer, edit, old_data),
217 v.ValidUsername(localizer, edit, old_data),
218 v.UnicodeString(strip=True, min=1, not_empty=True)
218 v.UnicodeString(strip=True, min=1, not_empty=True)
219 )
219 )
220 password = All(
220 password = All(
221 v.ValidPassword(localizer),
221 v.ValidPassword(localizer),
222 v.UnicodeString(strip=False, min=6, max=72, not_empty=True)
222 v.UnicodeString(strip=False, min=6, max=72, not_empty=True)
223 )
223 )
224 password_confirmation = All(
224 password_confirmation = All(
225 v.ValidPassword(localizer),
225 v.ValidPassword(localizer),
226 v.UnicodeString(strip=False, min=6, max=72, not_empty=True)
226 v.UnicodeString(strip=False, min=6, max=72, not_empty=True)
227 )
227 )
228 active = v.StringBoolean(if_missing=False)
228 active = v.StringBoolean(if_missing=False)
229 firstname = v.UnicodeString(strip=True, min=1, not_empty=False)
229 firstname = v.UnicodeString(strip=True, min=1, not_empty=False)
230 lastname = v.UnicodeString(strip=True, min=1, not_empty=False)
230 lastname = v.UnicodeString(strip=True, min=1, not_empty=False)
231 email = All(v.UniqSystemEmail(localizer, old_data), v.Email(not_empty=True))
231 email = All(v.UniqSystemEmail(localizer, old_data), v.Email(not_empty=True))
232
232
233 chained_validators = [v.ValidPasswordsMatch(localizer)]
233 chained_validators = [v.ValidPasswordsMatch(localizer)]
234 return _RegisterForm
234 return _RegisterForm
235
235
236
236
237 def PasswordResetForm(localizer):
237 def PasswordResetForm(localizer):
238 _ = localizer
238 _ = localizer
239
239
240 class _PasswordResetForm(formencode.Schema):
240 class _PasswordResetForm(formencode.Schema):
241 allow_extra_fields = True
241 allow_extra_fields = True
242 filter_extra_fields = True
242 filter_extra_fields = True
243 email = All(v.ValidSystemEmail(localizer), v.Email(not_empty=True))
243 email = All(v.ValidSystemEmail(localizer), v.Email(not_empty=True))
244 return _PasswordResetForm
244 return _PasswordResetForm
245
245
246
246
247 def RepoForm(localizer, edit=False, old_data=None, repo_groups=None,
247 def RepoForm(localizer, edit=False, old_data=None, repo_groups=None,
248 landing_revs=None, allow_disabled=False):
248 landing_revs=None, allow_disabled=False):
249 _ = localizer
249 _ = localizer
250 old_data = old_data or {}
250 old_data = old_data or {}
251 repo_groups = repo_groups or []
251 repo_groups = repo_groups or []
252 landing_revs = landing_revs or []
252 landing_revs = landing_revs or []
253 supported_backends = BACKENDS.keys()
253 supported_backends = BACKENDS.keys()
254
254
255 class _RepoForm(formencode.Schema):
255 class _RepoForm(formencode.Schema):
256 allow_extra_fields = True
256 allow_extra_fields = True
257 filter_extra_fields = False
257 filter_extra_fields = False
258 repo_name = All(v.UnicodeString(strip=True, min=1, not_empty=True),
258 repo_name = All(v.UnicodeString(strip=True, min=1, not_empty=True),
259 v.SlugifyName(localizer), v.CannotHaveGitSuffix(localizer))
259 v.SlugifyName(localizer), v.CannotHaveGitSuffix(localizer))
260 repo_group = All(v.CanWriteGroup(localizer, old_data),
260 repo_group = All(v.CanWriteGroup(localizer, old_data),
261 v.OneOf(repo_groups, hideList=True))
261 v.OneOf(repo_groups, hideList=True))
262 repo_type = v.OneOf(supported_backends, required=False,
262 repo_type = v.OneOf(supported_backends, required=False,
263 if_missing=old_data.get('repo_type'))
263 if_missing=old_data.get('repo_type'))
264 repo_description = v.UnicodeString(strip=True, min=1, not_empty=False)
264 repo_description = v.UnicodeString(strip=True, min=1, not_empty=False)
265 repo_private = v.StringBoolean(if_missing=False)
265 repo_private = v.StringBoolean(if_missing=False)
266 repo_landing_rev = v.OneOf(landing_revs, hideList=True)
266 repo_landing_rev = v.OneOf(landing_revs, hideList=True)
267 repo_copy_permissions = v.StringBoolean(if_missing=False)
267 repo_copy_permissions = v.StringBoolean(if_missing=False)
268 clone_uri = All(v.UnicodeString(strip=True, min=1, not_empty=False))
268 clone_uri = All(v.UnicodeString(strip=True, min=1, not_empty=False))
269
269
270 repo_enable_statistics = v.StringBoolean(if_missing=False)
270 repo_enable_statistics = v.StringBoolean(if_missing=False)
271 repo_enable_downloads = v.StringBoolean(if_missing=False)
271 repo_enable_downloads = v.StringBoolean(if_missing=False)
272 repo_enable_locking = v.StringBoolean(if_missing=False)
272 repo_enable_locking = v.StringBoolean(if_missing=False)
273
273
274 if edit:
274 if edit:
275 # this is repo owner
275 # this is repo owner
276 user = All(
276 user = All(
277 v.UnicodeString(not_empty=True),
277 v.UnicodeString(not_empty=True),
278 v.ValidRepoUser(localizer, allow_disabled))
278 v.ValidRepoUser(localizer, allow_disabled))
279 clone_uri_change = v.UnicodeString(
279 clone_uri_change = v.UnicodeString(
280 not_empty=False, if_missing=v.Missing)
280 not_empty=False, if_missing=v.Missing)
281
281
282 chained_validators = [v.ValidCloneUri(localizer),
282 chained_validators = [v.ValidCloneUri(localizer),
283 v.ValidRepoName(localizer, edit, old_data)]
283 v.ValidRepoName(localizer, edit, old_data)]
284 return _RepoForm
284 return _RepoForm
285
285
286
286
287 def RepoPermsForm(localizer):
287 def RepoPermsForm(localizer):
288 _ = localizer
288 _ = localizer
289
289
290 class _RepoPermsForm(formencode.Schema):
290 class _RepoPermsForm(formencode.Schema):
291 allow_extra_fields = True
291 allow_extra_fields = True
292 filter_extra_fields = False
292 filter_extra_fields = False
293 chained_validators = [v.ValidPerms(localizer, type_='repo')]
293 chained_validators = [v.ValidPerms(localizer, type_='repo')]
294 return _RepoPermsForm
294 return _RepoPermsForm
295
295
296
296
297 def RepoGroupPermsForm(localizer, valid_recursive_choices):
297 def RepoGroupPermsForm(localizer, valid_recursive_choices):
298 _ = localizer
298 _ = localizer
299
299
300 class _RepoGroupPermsForm(formencode.Schema):
300 class _RepoGroupPermsForm(formencode.Schema):
301 allow_extra_fields = True
301 allow_extra_fields = True
302 filter_extra_fields = False
302 filter_extra_fields = False
303 recursive = v.OneOf(valid_recursive_choices)
303 recursive = v.OneOf(valid_recursive_choices)
304 chained_validators = [v.ValidPerms(localizer, type_='repo_group')]
304 chained_validators = [v.ValidPerms(localizer, type_='repo_group')]
305 return _RepoGroupPermsForm
305 return _RepoGroupPermsForm
306
306
307
307
308 def UserGroupPermsForm(localizer):
308 def UserGroupPermsForm(localizer):
309 _ = localizer
309 _ = localizer
310
310
311 class _UserPermsForm(formencode.Schema):
311 class _UserPermsForm(formencode.Schema):
312 allow_extra_fields = True
312 allow_extra_fields = True
313 filter_extra_fields = False
313 filter_extra_fields = False
314 chained_validators = [v.ValidPerms(localizer, type_='user_group')]
314 chained_validators = [v.ValidPerms(localizer, type_='user_group')]
315 return _UserPermsForm
315 return _UserPermsForm
316
316
317
317
318 def RepoFieldForm(localizer):
318 def RepoFieldForm(localizer):
319 _ = localizer
319 _ = localizer
320
320
321 class _RepoFieldForm(formencode.Schema):
321 class _RepoFieldForm(formencode.Schema):
322 filter_extra_fields = True
322 filter_extra_fields = True
323 allow_extra_fields = True
323 allow_extra_fields = True
324
324
325 new_field_key = All(v.FieldKey(localizer),
325 new_field_key = All(v.FieldKey(localizer),
326 v.UnicodeString(strip=True, min=3, not_empty=True))
326 v.UnicodeString(strip=True, min=3, not_empty=True))
327 new_field_value = v.UnicodeString(not_empty=False, if_missing=u'')
327 new_field_value = v.UnicodeString(not_empty=False, if_missing=u'')
328 new_field_type = v.OneOf(['str', 'unicode', 'list', 'tuple'],
328 new_field_type = v.OneOf(['str', 'unicode', 'list', 'tuple'],
329 if_missing='str')
329 if_missing='str')
330 new_field_label = v.UnicodeString(not_empty=False)
330 new_field_label = v.UnicodeString(not_empty=False)
331 new_field_desc = v.UnicodeString(not_empty=False)
331 new_field_desc = v.UnicodeString(not_empty=False)
332 return _RepoFieldForm
332 return _RepoFieldForm
333
333
334
334
335 def RepoForkForm(localizer, edit=False, old_data=None,
335 def RepoForkForm(localizer, edit=False, old_data=None,
336 supported_backends=BACKENDS.keys(), repo_groups=None,
336 supported_backends=BACKENDS.keys(), repo_groups=None,
337 landing_revs=None):
337 landing_revs=None):
338 _ = localizer
338 _ = localizer
339 old_data = old_data or {}
339 old_data = old_data or {}
340 repo_groups = repo_groups or []
340 repo_groups = repo_groups or []
341 landing_revs = landing_revs or []
341 landing_revs = landing_revs or []
342
342
343 class _RepoForkForm(formencode.Schema):
343 class _RepoForkForm(formencode.Schema):
344 allow_extra_fields = True
344 allow_extra_fields = True
345 filter_extra_fields = False
345 filter_extra_fields = False
346 repo_name = All(v.UnicodeString(strip=True, min=1, not_empty=True),
346 repo_name = All(v.UnicodeString(strip=True, min=1, not_empty=True),
347 v.SlugifyName(localizer))
347 v.SlugifyName(localizer))
348 repo_group = All(v.CanWriteGroup(localizer, ),
348 repo_group = All(v.CanWriteGroup(localizer, ),
349 v.OneOf(repo_groups, hideList=True))
349 v.OneOf(repo_groups, hideList=True))
350 repo_type = All(v.ValidForkType(localizer, old_data), v.OneOf(supported_backends))
350 repo_type = All(v.ValidForkType(localizer, old_data), v.OneOf(supported_backends))
351 description = v.UnicodeString(strip=True, min=1, not_empty=True)
351 description = v.UnicodeString(strip=True, min=1, not_empty=True)
352 private = v.StringBoolean(if_missing=False)
352 private = v.StringBoolean(if_missing=False)
353 copy_permissions = v.StringBoolean(if_missing=False)
353 copy_permissions = v.StringBoolean(if_missing=False)
354 fork_parent_id = v.UnicodeString()
354 fork_parent_id = v.UnicodeString()
355 chained_validators = [v.ValidForkName(localizer, edit, old_data)]
355 chained_validators = [v.ValidForkName(localizer, edit, old_data)]
356 landing_rev = v.OneOf(landing_revs, hideList=True)
356 landing_rev = v.OneOf(landing_revs, hideList=True)
357 return _RepoForkForm
357 return _RepoForkForm
358
358
359
359
360 def ApplicationSettingsForm(localizer):
360 def ApplicationSettingsForm(localizer):
361 _ = localizer
361 _ = localizer
362
362
363 class _ApplicationSettingsForm(formencode.Schema):
363 class _ApplicationSettingsForm(formencode.Schema):
364 allow_extra_fields = True
364 allow_extra_fields = True
365 filter_extra_fields = False
365 filter_extra_fields = False
366 rhodecode_title = v.UnicodeString(strip=True, max=40, not_empty=False)
366 rhodecode_title = v.UnicodeString(strip=True, max=40, not_empty=False)
367 rhodecode_realm = v.UnicodeString(strip=True, min=1, not_empty=True)
367 rhodecode_realm = v.UnicodeString(strip=True, min=1, not_empty=True)
368 rhodecode_pre_code = v.UnicodeString(strip=True, min=1, not_empty=False)
368 rhodecode_pre_code = v.UnicodeString(strip=True, min=1, not_empty=False)
369 rhodecode_post_code = v.UnicodeString(strip=True, min=1, not_empty=False)
369 rhodecode_post_code = v.UnicodeString(strip=True, min=1, not_empty=False)
370 rhodecode_captcha_public_key = v.UnicodeString(strip=True, min=1, not_empty=False)
370 rhodecode_captcha_public_key = v.UnicodeString(strip=True, min=1, not_empty=False)
371 rhodecode_captcha_private_key = v.UnicodeString(strip=True, min=1, not_empty=False)
371 rhodecode_captcha_private_key = v.UnicodeString(strip=True, min=1, not_empty=False)
372 rhodecode_create_personal_repo_group = v.StringBoolean(if_missing=False)
372 rhodecode_create_personal_repo_group = v.StringBoolean(if_missing=False)
373 rhodecode_personal_repo_group_pattern = v.UnicodeString(strip=True, min=1, not_empty=False)
373 rhodecode_personal_repo_group_pattern = v.UnicodeString(strip=True, min=1, not_empty=False)
374 return _ApplicationSettingsForm
374 return _ApplicationSettingsForm
375
375
376
376
377 def ApplicationVisualisationForm(localizer):
377 def ApplicationVisualisationForm(localizer):
378 _ = localizer
378 _ = localizer
379
379
380 class _ApplicationVisualisationForm(formencode.Schema):
380 class _ApplicationVisualisationForm(formencode.Schema):
381 allow_extra_fields = True
381 allow_extra_fields = True
382 filter_extra_fields = False
382 filter_extra_fields = False
383 rhodecode_show_public_icon = v.StringBoolean(if_missing=False)
383 rhodecode_show_public_icon = v.StringBoolean(if_missing=False)
384 rhodecode_show_private_icon = v.StringBoolean(if_missing=False)
384 rhodecode_show_private_icon = v.StringBoolean(if_missing=False)
385 rhodecode_stylify_metatags = v.StringBoolean(if_missing=False)
385 rhodecode_stylify_metatags = v.StringBoolean(if_missing=False)
386
386
387 rhodecode_repository_fields = v.StringBoolean(if_missing=False)
387 rhodecode_repository_fields = v.StringBoolean(if_missing=False)
388 rhodecode_lightweight_journal = v.StringBoolean(if_missing=False)
388 rhodecode_lightweight_journal = v.StringBoolean(if_missing=False)
389 rhodecode_dashboard_items = v.Int(min=5, not_empty=True)
389 rhodecode_dashboard_items = v.Int(min=5, not_empty=True)
390 rhodecode_admin_grid_items = v.Int(min=5, not_empty=True)
390 rhodecode_admin_grid_items = v.Int(min=5, not_empty=True)
391 rhodecode_show_version = v.StringBoolean(if_missing=False)
391 rhodecode_show_version = v.StringBoolean(if_missing=False)
392 rhodecode_use_gravatar = v.StringBoolean(if_missing=False)
392 rhodecode_use_gravatar = v.StringBoolean(if_missing=False)
393 rhodecode_markup_renderer = v.OneOf(['markdown', 'rst'])
393 rhodecode_markup_renderer = v.OneOf(['markdown', 'rst'])
394 rhodecode_gravatar_url = v.UnicodeString(min=3)
394 rhodecode_gravatar_url = v.UnicodeString(min=3)
395 rhodecode_clone_uri_tmpl = v.UnicodeString(min=3)
395 rhodecode_clone_uri_tmpl = v.UnicodeString(min=3)
396 rhodecode_clone_uri_ssh_tmpl = v.UnicodeString(min=3)
396 rhodecode_support_url = v.UnicodeString()
397 rhodecode_support_url = v.UnicodeString()
397 rhodecode_show_revision_number = v.StringBoolean(if_missing=False)
398 rhodecode_show_revision_number = v.StringBoolean(if_missing=False)
398 rhodecode_show_sha_length = v.Int(min=4, not_empty=True)
399 rhodecode_show_sha_length = v.Int(min=4, not_empty=True)
399 return _ApplicationVisualisationForm
400 return _ApplicationVisualisationForm
400
401
401
402
402 class _BaseVcsSettingsForm(formencode.Schema):
403 class _BaseVcsSettingsForm(formencode.Schema):
403
404
404 allow_extra_fields = True
405 allow_extra_fields = True
405 filter_extra_fields = False
406 filter_extra_fields = False
406 hooks_changegroup_repo_size = v.StringBoolean(if_missing=False)
407 hooks_changegroup_repo_size = v.StringBoolean(if_missing=False)
407 hooks_changegroup_push_logger = v.StringBoolean(if_missing=False)
408 hooks_changegroup_push_logger = v.StringBoolean(if_missing=False)
408 hooks_outgoing_pull_logger = v.StringBoolean(if_missing=False)
409 hooks_outgoing_pull_logger = v.StringBoolean(if_missing=False)
409
410
410 # PR/Code-review
411 # PR/Code-review
411 rhodecode_pr_merge_enabled = v.StringBoolean(if_missing=False)
412 rhodecode_pr_merge_enabled = v.StringBoolean(if_missing=False)
412 rhodecode_use_outdated_comments = v.StringBoolean(if_missing=False)
413 rhodecode_use_outdated_comments = v.StringBoolean(if_missing=False)
413
414
414 # hg
415 # hg
415 extensions_largefiles = v.StringBoolean(if_missing=False)
416 extensions_largefiles = v.StringBoolean(if_missing=False)
416 extensions_evolve = v.StringBoolean(if_missing=False)
417 extensions_evolve = v.StringBoolean(if_missing=False)
417 phases_publish = v.StringBoolean(if_missing=False)
418 phases_publish = v.StringBoolean(if_missing=False)
418
419
419 rhodecode_hg_use_rebase_for_merging = v.StringBoolean(if_missing=False)
420 rhodecode_hg_use_rebase_for_merging = v.StringBoolean(if_missing=False)
420 rhodecode_hg_close_branch_before_merging = v.StringBoolean(if_missing=False)
421 rhodecode_hg_close_branch_before_merging = v.StringBoolean(if_missing=False)
421
422
422 # git
423 # git
423 vcs_git_lfs_enabled = v.StringBoolean(if_missing=False)
424 vcs_git_lfs_enabled = v.StringBoolean(if_missing=False)
424 rhodecode_git_use_rebase_for_merging = v.StringBoolean(if_missing=False)
425 rhodecode_git_use_rebase_for_merging = v.StringBoolean(if_missing=False)
425 rhodecode_git_close_branch_before_merging = v.StringBoolean(if_missing=False)
426 rhodecode_git_close_branch_before_merging = v.StringBoolean(if_missing=False)
426
427
427 # svn
428 # svn
428 vcs_svn_proxy_http_requests_enabled = v.StringBoolean(if_missing=False)
429 vcs_svn_proxy_http_requests_enabled = v.StringBoolean(if_missing=False)
429 vcs_svn_proxy_http_server_url = v.UnicodeString(strip=True, if_missing=None)
430 vcs_svn_proxy_http_server_url = v.UnicodeString(strip=True, if_missing=None)
430
431
431
432
432 def ApplicationUiSettingsForm(localizer):
433 def ApplicationUiSettingsForm(localizer):
433 _ = localizer
434 _ = localizer
434
435
435 class _ApplicationUiSettingsForm(_BaseVcsSettingsForm):
436 class _ApplicationUiSettingsForm(_BaseVcsSettingsForm):
436 web_push_ssl = v.StringBoolean(if_missing=False)
437 web_push_ssl = v.StringBoolean(if_missing=False)
437 paths_root_path = All(
438 paths_root_path = All(
438 v.ValidPath(localizer),
439 v.ValidPath(localizer),
439 v.UnicodeString(strip=True, min=1, not_empty=True)
440 v.UnicodeString(strip=True, min=1, not_empty=True)
440 )
441 )
441 largefiles_usercache = All(
442 largefiles_usercache = All(
442 v.ValidPath(localizer),
443 v.ValidPath(localizer),
443 v.UnicodeString(strip=True, min=2, not_empty=True))
444 v.UnicodeString(strip=True, min=2, not_empty=True))
444 vcs_git_lfs_store_location = All(
445 vcs_git_lfs_store_location = All(
445 v.ValidPath(localizer),
446 v.ValidPath(localizer),
446 v.UnicodeString(strip=True, min=2, not_empty=True))
447 v.UnicodeString(strip=True, min=2, not_empty=True))
447 extensions_hgsubversion = v.StringBoolean(if_missing=False)
448 extensions_hgsubversion = v.StringBoolean(if_missing=False)
448 extensions_hggit = v.StringBoolean(if_missing=False)
449 extensions_hggit = v.StringBoolean(if_missing=False)
449 new_svn_branch = v.ValidSvnPattern(localizer, section='vcs_svn_branch')
450 new_svn_branch = v.ValidSvnPattern(localizer, section='vcs_svn_branch')
450 new_svn_tag = v.ValidSvnPattern(localizer, section='vcs_svn_tag')
451 new_svn_tag = v.ValidSvnPattern(localizer, section='vcs_svn_tag')
451 return _ApplicationUiSettingsForm
452 return _ApplicationUiSettingsForm
452
453
453
454
454 def RepoVcsSettingsForm(localizer, repo_name):
455 def RepoVcsSettingsForm(localizer, repo_name):
455 _ = localizer
456 _ = localizer
456
457
457 class _RepoVcsSettingsForm(_BaseVcsSettingsForm):
458 class _RepoVcsSettingsForm(_BaseVcsSettingsForm):
458 inherit_global_settings = v.StringBoolean(if_missing=False)
459 inherit_global_settings = v.StringBoolean(if_missing=False)
459 new_svn_branch = v.ValidSvnPattern(localizer,
460 new_svn_branch = v.ValidSvnPattern(localizer,
460 section='vcs_svn_branch', repo_name=repo_name)
461 section='vcs_svn_branch', repo_name=repo_name)
461 new_svn_tag = v.ValidSvnPattern(localizer,
462 new_svn_tag = v.ValidSvnPattern(localizer,
462 section='vcs_svn_tag', repo_name=repo_name)
463 section='vcs_svn_tag', repo_name=repo_name)
463 return _RepoVcsSettingsForm
464 return _RepoVcsSettingsForm
464
465
465
466
466 def LabsSettingsForm(localizer):
467 def LabsSettingsForm(localizer):
467 _ = localizer
468 _ = localizer
468
469
469 class _LabSettingsForm(formencode.Schema):
470 class _LabSettingsForm(formencode.Schema):
470 allow_extra_fields = True
471 allow_extra_fields = True
471 filter_extra_fields = False
472 filter_extra_fields = False
472 return _LabSettingsForm
473 return _LabSettingsForm
473
474
474
475
475 def ApplicationPermissionsForm(
476 def ApplicationPermissionsForm(
476 localizer, register_choices, password_reset_choices,
477 localizer, register_choices, password_reset_choices,
477 extern_activate_choices):
478 extern_activate_choices):
478 _ = localizer
479 _ = localizer
479
480
480 class _DefaultPermissionsForm(formencode.Schema):
481 class _DefaultPermissionsForm(formencode.Schema):
481 allow_extra_fields = True
482 allow_extra_fields = True
482 filter_extra_fields = True
483 filter_extra_fields = True
483
484
484 anonymous = v.StringBoolean(if_missing=False)
485 anonymous = v.StringBoolean(if_missing=False)
485 default_register = v.OneOf(register_choices)
486 default_register = v.OneOf(register_choices)
486 default_register_message = v.UnicodeString()
487 default_register_message = v.UnicodeString()
487 default_password_reset = v.OneOf(password_reset_choices)
488 default_password_reset = v.OneOf(password_reset_choices)
488 default_extern_activate = v.OneOf(extern_activate_choices)
489 default_extern_activate = v.OneOf(extern_activate_choices)
489 return _DefaultPermissionsForm
490 return _DefaultPermissionsForm
490
491
491
492
492 def ObjectPermissionsForm(localizer, repo_perms_choices, group_perms_choices,
493 def ObjectPermissionsForm(localizer, repo_perms_choices, group_perms_choices,
493 user_group_perms_choices):
494 user_group_perms_choices):
494 _ = localizer
495 _ = localizer
495
496
496 class _ObjectPermissionsForm(formencode.Schema):
497 class _ObjectPermissionsForm(formencode.Schema):
497 allow_extra_fields = True
498 allow_extra_fields = True
498 filter_extra_fields = True
499 filter_extra_fields = True
499 overwrite_default_repo = v.StringBoolean(if_missing=False)
500 overwrite_default_repo = v.StringBoolean(if_missing=False)
500 overwrite_default_group = v.StringBoolean(if_missing=False)
501 overwrite_default_group = v.StringBoolean(if_missing=False)
501 overwrite_default_user_group = v.StringBoolean(if_missing=False)
502 overwrite_default_user_group = v.StringBoolean(if_missing=False)
502 default_repo_perm = v.OneOf(repo_perms_choices)
503 default_repo_perm = v.OneOf(repo_perms_choices)
503 default_group_perm = v.OneOf(group_perms_choices)
504 default_group_perm = v.OneOf(group_perms_choices)
504 default_user_group_perm = v.OneOf(user_group_perms_choices)
505 default_user_group_perm = v.OneOf(user_group_perms_choices)
505 return _ObjectPermissionsForm
506 return _ObjectPermissionsForm
506
507
507
508
508 def UserPermissionsForm(localizer, create_choices, create_on_write_choices,
509 def UserPermissionsForm(localizer, create_choices, create_on_write_choices,
509 repo_group_create_choices, user_group_create_choices,
510 repo_group_create_choices, user_group_create_choices,
510 fork_choices, inherit_default_permissions_choices):
511 fork_choices, inherit_default_permissions_choices):
511 _ = localizer
512 _ = localizer
512
513
513 class _DefaultPermissionsForm(formencode.Schema):
514 class _DefaultPermissionsForm(formencode.Schema):
514 allow_extra_fields = True
515 allow_extra_fields = True
515 filter_extra_fields = True
516 filter_extra_fields = True
516
517
517 anonymous = v.StringBoolean(if_missing=False)
518 anonymous = v.StringBoolean(if_missing=False)
518
519
519 default_repo_create = v.OneOf(create_choices)
520 default_repo_create = v.OneOf(create_choices)
520 default_repo_create_on_write = v.OneOf(create_on_write_choices)
521 default_repo_create_on_write = v.OneOf(create_on_write_choices)
521 default_user_group_create = v.OneOf(user_group_create_choices)
522 default_user_group_create = v.OneOf(user_group_create_choices)
522 default_repo_group_create = v.OneOf(repo_group_create_choices)
523 default_repo_group_create = v.OneOf(repo_group_create_choices)
523 default_fork_create = v.OneOf(fork_choices)
524 default_fork_create = v.OneOf(fork_choices)
524 default_inherit_default_permissions = v.OneOf(inherit_default_permissions_choices)
525 default_inherit_default_permissions = v.OneOf(inherit_default_permissions_choices)
525 return _DefaultPermissionsForm
526 return _DefaultPermissionsForm
526
527
527
528
528 def UserIndividualPermissionsForm(localizer):
529 def UserIndividualPermissionsForm(localizer):
529 _ = localizer
530 _ = localizer
530
531
531 class _DefaultPermissionsForm(formencode.Schema):
532 class _DefaultPermissionsForm(formencode.Schema):
532 allow_extra_fields = True
533 allow_extra_fields = True
533 filter_extra_fields = True
534 filter_extra_fields = True
534
535
535 inherit_default_permissions = v.StringBoolean(if_missing=False)
536 inherit_default_permissions = v.StringBoolean(if_missing=False)
536 return _DefaultPermissionsForm
537 return _DefaultPermissionsForm
537
538
538
539
539 def DefaultsForm(localizer, edit=False, old_data=None, supported_backends=BACKENDS.keys()):
540 def DefaultsForm(localizer, edit=False, old_data=None, supported_backends=BACKENDS.keys()):
540 _ = localizer
541 _ = localizer
541 old_data = old_data or {}
542 old_data = old_data or {}
542
543
543 class _DefaultsForm(formencode.Schema):
544 class _DefaultsForm(formencode.Schema):
544 allow_extra_fields = True
545 allow_extra_fields = True
545 filter_extra_fields = True
546 filter_extra_fields = True
546 default_repo_type = v.OneOf(supported_backends)
547 default_repo_type = v.OneOf(supported_backends)
547 default_repo_private = v.StringBoolean(if_missing=False)
548 default_repo_private = v.StringBoolean(if_missing=False)
548 default_repo_enable_statistics = v.StringBoolean(if_missing=False)
549 default_repo_enable_statistics = v.StringBoolean(if_missing=False)
549 default_repo_enable_downloads = v.StringBoolean(if_missing=False)
550 default_repo_enable_downloads = v.StringBoolean(if_missing=False)
550 default_repo_enable_locking = v.StringBoolean(if_missing=False)
551 default_repo_enable_locking = v.StringBoolean(if_missing=False)
551 return _DefaultsForm
552 return _DefaultsForm
552
553
553
554
554 def AuthSettingsForm(localizer):
555 def AuthSettingsForm(localizer):
555 _ = localizer
556 _ = localizer
556
557
557 class _AuthSettingsForm(formencode.Schema):
558 class _AuthSettingsForm(formencode.Schema):
558 allow_extra_fields = True
559 allow_extra_fields = True
559 filter_extra_fields = True
560 filter_extra_fields = True
560 auth_plugins = All(v.ValidAuthPlugins(localizer),
561 auth_plugins = All(v.ValidAuthPlugins(localizer),
561 v.UniqueListFromString(localizer)(not_empty=True))
562 v.UniqueListFromString(localizer)(not_empty=True))
562 return _AuthSettingsForm
563 return _AuthSettingsForm
563
564
564
565
565 def UserExtraEmailForm(localizer):
566 def UserExtraEmailForm(localizer):
566 _ = localizer
567 _ = localizer
567
568
568 class _UserExtraEmailForm(formencode.Schema):
569 class _UserExtraEmailForm(formencode.Schema):
569 email = All(v.UniqSystemEmail(localizer), v.Email(not_empty=True))
570 email = All(v.UniqSystemEmail(localizer), v.Email(not_empty=True))
570 return _UserExtraEmailForm
571 return _UserExtraEmailForm
571
572
572
573
573 def UserExtraIpForm(localizer):
574 def UserExtraIpForm(localizer):
574 _ = localizer
575 _ = localizer
575
576
576 class _UserExtraIpForm(formencode.Schema):
577 class _UserExtraIpForm(formencode.Schema):
577 ip = v.ValidIp(localizer)(not_empty=True)
578 ip = v.ValidIp(localizer)(not_empty=True)
578 return _UserExtraIpForm
579 return _UserExtraIpForm
579
580
580
581
581 def PullRequestForm(localizer, repo_id):
582 def PullRequestForm(localizer, repo_id):
582 _ = localizer
583 _ = localizer
583
584
584 class ReviewerForm(formencode.Schema):
585 class ReviewerForm(formencode.Schema):
585 user_id = v.Int(not_empty=True)
586 user_id = v.Int(not_empty=True)
586 reasons = All()
587 reasons = All()
587 rules = All(v.UniqueList(localizer, convert=int)())
588 rules = All(v.UniqueList(localizer, convert=int)())
588 mandatory = v.StringBoolean()
589 mandatory = v.StringBoolean()
589
590
590 class _PullRequestForm(formencode.Schema):
591 class _PullRequestForm(formencode.Schema):
591 allow_extra_fields = True
592 allow_extra_fields = True
592 filter_extra_fields = True
593 filter_extra_fields = True
593
594
594 common_ancestor = v.UnicodeString(strip=True, required=True)
595 common_ancestor = v.UnicodeString(strip=True, required=True)
595 source_repo = v.UnicodeString(strip=True, required=True)
596 source_repo = v.UnicodeString(strip=True, required=True)
596 source_ref = v.UnicodeString(strip=True, required=True)
597 source_ref = v.UnicodeString(strip=True, required=True)
597 target_repo = v.UnicodeString(strip=True, required=True)
598 target_repo = v.UnicodeString(strip=True, required=True)
598 target_ref = v.UnicodeString(strip=True, required=True)
599 target_ref = v.UnicodeString(strip=True, required=True)
599 revisions = All(#v.NotReviewedRevisions(localizer, repo_id)(),
600 revisions = All(#v.NotReviewedRevisions(localizer, repo_id)(),
600 v.UniqueList(localizer)(not_empty=True))
601 v.UniqueList(localizer)(not_empty=True))
601 review_members = formencode.ForEach(ReviewerForm())
602 review_members = formencode.ForEach(ReviewerForm())
602 pullrequest_title = v.UnicodeString(strip=True, required=True, min=3, max=255)
603 pullrequest_title = v.UnicodeString(strip=True, required=True, min=3, max=255)
603 pullrequest_desc = v.UnicodeString(strip=True, required=False)
604 pullrequest_desc = v.UnicodeString(strip=True, required=False)
604
605
605 return _PullRequestForm
606 return _PullRequestForm
606
607
607
608
608 def IssueTrackerPatternsForm(localizer):
609 def IssueTrackerPatternsForm(localizer):
609 _ = localizer
610 _ = localizer
610
611
611 class _IssueTrackerPatternsForm(formencode.Schema):
612 class _IssueTrackerPatternsForm(formencode.Schema):
612 allow_extra_fields = True
613 allow_extra_fields = True
613 filter_extra_fields = False
614 filter_extra_fields = False
614 chained_validators = [v.ValidPattern(localizer)]
615 chained_validators = [v.ValidPattern(localizer)]
615 return _IssueTrackerPatternsForm
616 return _IssueTrackerPatternsForm
@@ -1,270 +1,278 b''
1 // summary.less
1 // summary.less
2 // For use in RhodeCode applications;
2 // For use in RhodeCode applications;
3 // Used for headers and file detail summary screens.
3 // Used for headers and file detail summary screens.
4
4
5 .summary {
5 .summary {
6 float: left;
6 float: left;
7 position: relative;
7 position: relative;
8 width: 100%;
8 width: 100%;
9 margin: 0;
9 margin: 0;
10 padding: 0;
10 padding: 0;
11
11
12 .summary-detail-header {
12 .summary-detail-header {
13 float: left;
13 float: left;
14 display: block;
14 display: block;
15 width: 100%;
15 width: 100%;
16 margin-bottom: @textmargin;
16 margin-bottom: @textmargin;
17 padding: 0 0 .5em 0;
17 padding: 0 0 .5em 0;
18 border-bottom: @border-thickness solid @border-default-color;
18 border-bottom: @border-thickness solid @border-default-color;
19
19
20 .breadcrumbs {
20 .breadcrumbs {
21 float: left;
21 float: left;
22 display: inline;
22 display: inline;
23 margin: 0;
23 margin: 0;
24 padding: 0;
24 padding: 0;
25 }
25 }
26 h4 {
26 h4 {
27 float: left;
27 float: left;
28 margin: 0 1em 0 0;
28 margin: 0 1em 0 0;
29 padding: 0;
29 padding: 0;
30 line-height: 1.2em;
30 line-height: 1.2em;
31 font-size: @basefontsize;
31 font-size: @basefontsize;
32 }
32 }
33
33
34 .action_link {
34 .action_link {
35 float: right;
35 float: right;
36 }
36 }
37
37
38 .new-file {
38 .new-file {
39 float: right;
39 float: right;
40 margin-top: -1.5em;
40 margin-top: -1.5em;
41 }
41 }
42 }
42 }
43
43
44 .summary-detail {
44 .summary-detail {
45 float: left;
45 float: left;
46 position: relative;
46 position: relative;
47 width: 73%;
47 width: 73%;
48 margin: 0 3% @space 0;
48 margin: 0 3% @space 0;
49 padding: 0;
49 padding: 0;
50
50
51 .file_diff_buttons {
51 .file_diff_buttons {
52 margin-top: @space;
52 margin-top: @space;
53 }
53 }
54
54
55 // commit message
55 // commit message
56 .commit {
56 .commit {
57 white-space: pre-wrap;
57 white-space: pre-wrap;
58 }
58 }
59
59
60 #clone_url {
60 .left-clone {
61 width: ~"calc(100% - 103px)";
61 float: left;
62 padding: @padding/4;
62 height: 30px;
63 margin: 0;
64 padding: 0;
65 font-family: @text-semibold;
63 }
66 }
64
67
65 #clone_url_id {
68 .right-clone {
66 width: ~"calc(100% - 125px)";
69 float: right;
67 padding: @padding/4;
70 width: 83%;
71 }
72
73 .clone_url_input {
74 width: ~"calc(100% - 35px)";
75 padding: 5px;
68 }
76 }
69
77
70 &.directory {
78 &.directory {
71 margin-bottom: 0;
79 margin-bottom: 0;
72 }
80 }
73
81
74 .desc {
82 .desc {
75 white-space: pre-wrap;
83 white-space: pre-wrap;
76 }
84 }
77 .disabled {
85 .disabled {
78 opacity: .5;
86 opacity: .5;
79 cursor: inherit;
87 cursor: inherit;
80 }
88 }
81 .help-block {
89 .help-block {
82 color: inherit;
90 color: inherit;
83 margin: 0;
91 margin: 0;
84 }
92 }
85 }
93 }
86
94
87 .sidebar-right {
95 .sidebar-right {
88 float: left;
96 float: left;
89 width: 24%;
97 width: 24%;
90 margin: 0;
98 margin: 0;
91 padding: 0;
99 padding: 0;
92
100
93 ul {
101 ul {
94 margin-left: 0;
102 margin-left: 0;
95 padding-left: 0;
103 padding-left: 0;
96
104
97 li {
105 li {
98
106
99 &:before {
107 &:before {
100 content: none;
108 content: none;
101 width: 0;
109 width: 0;
102 }
110 }
103 }
111 }
104 }
112 }
105 }
113 }
106
114
107 #clone_by_name, #clone_by_id{
115 #clone_by_name, #clone_by_id{
108 display: inline-block;
116 display: inline-block;
109 margin-left: 0px;
117 margin-left: 0px;
110 }
118 }
111
119
112 .codeblock {
120 .codeblock {
113 border: none;
121 border: none;
114 background-color: transparent;
122 background-color: transparent;
115 }
123 }
116
124
117 .code-body {
125 .code-body {
118 border: @border-thickness solid @border-default-color;
126 border: @border-thickness solid @border-default-color;
119 .border-radius(@border-radius);
127 .border-radius(@border-radius);
120 }
128 }
121 }
129 }
122
130
123 // this is used outside of just the summary
131 // this is used outside of just the summary
124 .fieldset, // similar to form fieldset
132 .fieldset, // similar to form fieldset
125 .summary .sidebar-right-content { // these have to match
133 .summary .sidebar-right-content { // these have to match
126 clear: both;
134 clear: both;
127 float: left;
135 float: left;
128 position: relative;
136 position: relative;
129 display:block;
137 display:block;
130 width: 100%;
138 width: 100%;
131 min-height: 1em;
139 min-height: 1em;
132 margin-bottom: @textmargin;
140 margin-bottom: @textmargin;
133 padding: 0;
141 padding: 0;
134 line-height: 1.2em;
142 line-height: 1.2em;
135
143
136 &:after { // clearfix
144 &:after { // clearfix
137 content: "";
145 content: "";
138 clear: both;
146 clear: both;
139 width: 100%;
147 width: 100%;
140 height: 1em;
148 height: 1em;
141 }
149 }
142 }
150 }
143
151
144 .summary .sidebar-right-content {
152 .summary .sidebar-right-content {
145 margin-bottom: @space;
153 margin-bottom: @space;
146
154
147 .rc-user {
155 .rc-user {
148 min-width: 0;
156 min-width: 0;
149 }
157 }
150 }
158 }
151
159
152 .fieldset {
160 .fieldset {
153
161
154 .left-label { // similar to form legend
162 .left-label { // similar to form legend
155 float: left;
163 float: left;
156 display: block;
164 display: block;
157 width: 25%;
165 width: 25%;
158 margin: 0;
166 margin: 0;
159 padding: 0;
167 padding: 0;
160 font-family: @text-semibold;
168 font-family: @text-semibold;
161 }
169 }
162
170
163 .right-content { // similar to form fields
171 .right-content { // similar to form fields
164 float: left;
172 float: left;
165 display: block;
173 display: block;
166 width: 75%;
174 width: 75%;
167 margin: 0 0 0 -15%;
175 margin: 0 0 0 -15%;
168 padding: 0 0 0 15%;
176 padding: 0 0 0 15%;
169
177
170 .truncate-wrap,
178 .truncate-wrap,
171 .truncate {
179 .truncate {
172 max-width: 100%;
180 max-width: 100%;
173 width: 100%;
181 width: 100%;
174 }
182 }
175
183
176 .commit-long {
184 .commit-long {
177 overflow-x: auto;
185 overflow-x: auto;
178 }
186 }
179 }
187 }
180 .commit.truncate-wrap {
188 .commit.truncate-wrap {
181 overflow:hidden;
189 overflow:hidden;
182 text-overflow: ellipsis;
190 text-overflow: ellipsis;
183 }
191 }
184 }
192 }
185
193
186 // expand commit message
194 // expand commit message
187 #message_expand {
195 #message_expand {
188 clear: both;
196 clear: both;
189 display: block;
197 display: block;
190 color: @rcblue;
198 color: @rcblue;
191 cursor: pointer;
199 cursor: pointer;
192 }
200 }
193
201
194 #trimmed_message_box {
202 #trimmed_message_box {
195 max-height: floor(2 * @basefontsize * 1.2); // 2 lines * line-height
203 max-height: floor(2 * @basefontsize * 1.2); // 2 lines * line-height
196 overflow: hidden;
204 overflow: hidden;
197 }
205 }
198
206
199 // show/hide comments button
207 // show/hide comments button
200 .show-inline-comments {
208 .show-inline-comments {
201 display: inline;
209 display: inline;
202 cursor: pointer;
210 cursor: pointer;
203
211
204 .comments-show { display: inline; }
212 .comments-show { display: inline; }
205 .comments-hide { display: none; }
213 .comments-hide { display: none; }
206
214
207 &.comments-visible {
215 &.comments-visible {
208 .comments-show { display: none; }
216 .comments-show { display: none; }
209 .comments-hide { display: inline; }
217 .comments-hide { display: inline; }
210 }
218 }
211 }
219 }
212
220
213 // Quick Start section
221 // Quick Start section
214 .quick_start {
222 .quick_start {
215 float: left;
223 float: left;
216 display: block;
224 display: block;
217 position: relative;
225 position: relative;
218 width: 100%;
226 width: 100%;
219
227
220 // adds some space to make copy and paste easier
228 // adds some space to make copy and paste easier
221 .left-label,
229 .left-label,
222 .right-content {
230 .right-content {
223 line-height: 1.6em;
231 line-height: 1.6em;
224 }
232 }
225 }
233 }
226
234
227 .submodule {
235 .submodule {
228 .summary-detail {
236 .summary-detail {
229 width: 100%;
237 width: 100%;
230
238
231 .btn-collapse {
239 .btn-collapse {
232 display: none;
240 display: none;
233 }
241 }
234 }
242 }
235 }
243 }
236
244
237 .codeblock-header {
245 .codeblock-header {
238 float: left;
246 float: left;
239 display: block;
247 display: block;
240 width: 100%;
248 width: 100%;
241 margin: 0;
249 margin: 0;
242 padding: @space 0 @padding 0;
250 padding: @space 0 @padding 0;
243 border-top: @border-thickness solid @border-default-color;
251 border-top: @border-thickness solid @border-default-color;
244
252
245 .stats {
253 .stats {
246 float: left;
254 float: left;
247 width: 50%;
255 width: 50%;
248 }
256 }
249
257
250 .buttons {
258 .buttons {
251 float: right;
259 float: right;
252 width: 50%;
260 width: 50%;
253 text-align: right;
261 text-align: right;
254 color: @grey4;
262 color: @grey4;
255 }
263 }
256 }
264 }
257
265
258 #summary-menu-stats {
266 #summary-menu-stats {
259
267
260 .stats-bullet {
268 .stats-bullet {
261 color: @grey3;
269 color: @grey3;
262 min-width: 3em;
270 min-width: 3em;
263 }
271 }
264
272
265 .repo-size {
273 .repo-size {
266 margin-bottom: .5em;
274 margin-bottom: .5em;
267 }
275 }
268
276
269 }
277 }
270
278
@@ -1,226 +1,230 b''
1 ${h.secure_form(h.route_path('admin_settings_visual_update'), request=request)}
1 ${h.secure_form(h.route_path('admin_settings_visual_update'), request=request)}
2
2
3 <div class="panel panel-default">
3 <div class="panel panel-default">
4 <div class="panel-heading" id="general">
4 <div class="panel-heading" id="general">
5 <h3 class="panel-title">${_('General')}</h3>
5 <h3 class="panel-title">${_('General')}</h3>
6 </div>
6 </div>
7 <div class="panel-body">
7 <div class="panel-body">
8 <div class="checkbox">
8 <div class="checkbox">
9 ${h.checkbox('rhodecode_repository_fields','True')}
9 ${h.checkbox('rhodecode_repository_fields','True')}
10 <label for="rhodecode_repository_fields">${_('Use repository extra fields')}</label>
10 <label for="rhodecode_repository_fields">${_('Use repository extra fields')}</label>
11 </div>
11 </div>
12 <span class="help-block">${_('Allows storing additional customized fields per repository.')}</span>
12 <span class="help-block">${_('Allows storing additional customized fields per repository.')}</span>
13
13
14 <div></div>
14 <div></div>
15 <div class="checkbox">
15 <div class="checkbox">
16 ${h.checkbox('rhodecode_show_version','True')}
16 ${h.checkbox('rhodecode_show_version','True')}
17 <label for="rhodecode_show_version">${_('Show RhodeCode version')}</label>
17 <label for="rhodecode_show_version">${_('Show RhodeCode version')}</label>
18 </div>
18 </div>
19 <span class="help-block">${_('Shows or hides a version number of RhodeCode displayed in the footer.')}</span>
19 <span class="help-block">${_('Shows or hides a version number of RhodeCode displayed in the footer.')}</span>
20 </div>
20 </div>
21 </div>
21 </div>
22
22
23
23
24 <div class="panel panel-default">
24 <div class="panel panel-default">
25 <div class="panel-heading" id="gravatars">
25 <div class="panel-heading" id="gravatars">
26 <h3 class="panel-title">${_('Gravatars')}</h3>
26 <h3 class="panel-title">${_('Gravatars')}</h3>
27 </div>
27 </div>
28 <div class="panel-body">
28 <div class="panel-body">
29 <div class="checkbox">
29 <div class="checkbox">
30 ${h.checkbox('rhodecode_use_gravatar','True')}
30 ${h.checkbox('rhodecode_use_gravatar','True')}
31 <label for="rhodecode_use_gravatar">${_('Use Gravatars based avatars')}</label>
31 <label for="rhodecode_use_gravatar">${_('Use Gravatars based avatars')}</label>
32 </div>
32 </div>
33 <span class="help-block">${_('Use gravatar.com as avatar system for RhodeCode accounts. If this is disabled avatars are generated based on initials and email.')}</span>
33 <span class="help-block">${_('Use gravatar.com as avatar system for RhodeCode accounts. If this is disabled avatars are generated based on initials and email.')}</span>
34
34
35 <div class="label">
35 <div class="label">
36 <label for="rhodecode_gravatar_url">${_('Gravatar URL')}</label>
36 <label for="rhodecode_gravatar_url">${_('Gravatar URL')}</label>
37 </div>
37 </div>
38 <div class="input">
38 <div class="input">
39 <div class="field">
39 <div class="field">
40 ${h.text('rhodecode_gravatar_url', size='100%')}
40 ${h.text('rhodecode_gravatar_url', size='100%')}
41 </div>
41 </div>
42
42
43 <div class="field">
43 <div class="field">
44 <span class="help-block">${_('''Gravatar url allows you to use other avatar server application.
44 <span class="help-block">${_('''Gravatar url allows you to use other avatar server application.
45 Following variables of the URL will be replaced accordingly.
45 Following variables of the URL will be replaced accordingly.
46 {scheme} 'http' or 'https' sent from running RhodeCode server,
46 {scheme} 'http' or 'https' sent from running RhodeCode server,
47 {email} user email,
47 {email} user email,
48 {md5email} md5 hash of the user email (like at gravatar.com),
48 {md5email} md5 hash of the user email (like at gravatar.com),
49 {size} size of the image that is expected from the server application,
49 {size} size of the image that is expected from the server application,
50 {netloc} network location/server host of running RhodeCode server''')}</span>
50 {netloc} network location/server host of running RhodeCode server''')}</span>
51 </div>
51 </div>
52 </div>
52 </div>
53 </div>
53 </div>
54 </div>
54 </div>
55
55
56
56
57 <div class="panel panel-default">
57 <div class="panel panel-default">
58 <div class="panel-heading" id="meta-tagging">
58 <div class="panel-heading" id="meta-tagging">
59 <h3 class="panel-title">${_('Meta-Tagging')}</h3>
59 <h3 class="panel-title">${_('Meta-Tagging')}</h3>
60 </div>
60 </div>
61 <div class="panel-body">
61 <div class="panel-body">
62 <div class="checkbox">
62 <div class="checkbox">
63 ${h.checkbox('rhodecode_stylify_metatags','True')}
63 ${h.checkbox('rhodecode_stylify_metatags','True')}
64 <label for="rhodecode_stylify_metatags">${_('Stylify recognised meta tags')}</label>
64 <label for="rhodecode_stylify_metatags">${_('Stylify recognised meta tags')}</label>
65 </div>
65 </div>
66 <span class="help-block">${_('Parses meta tags from repository or repository group description fields and turns them into colored tags.')}</span>
66 <span class="help-block">${_('Parses meta tags from repository or repository group description fields and turns them into colored tags.')}</span>
67 <div>
67 <div>
68 <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
68 <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
69 ${dt.metatags_help()}
69 ${dt.metatags_help()}
70 </div>
70 </div>
71 </div>
71 </div>
72 </div>
72 </div>
73
73
74
74
75 <div class="panel panel-default">
75 <div class="panel panel-default">
76 <div class="panel-heading">
76 <div class="panel-heading">
77 <h3 class="panel-title">${_('Dashboard Items')}</h3>
77 <h3 class="panel-title">${_('Dashboard Items')}</h3>
78 </div>
78 </div>
79 <div class="panel-body">
79 <div class="panel-body">
80 <div class="label">
80 <div class="label">
81 <label for="rhodecode_dashboard_items">${_('Main page dashboard items')}</label>
81 <label for="rhodecode_dashboard_items">${_('Main page dashboard items')}</label>
82 </div>
82 </div>
83 <div class="field input">
83 <div class="field input">
84 ${h.text('rhodecode_dashboard_items',size=5)}
84 ${h.text('rhodecode_dashboard_items',size=5)}
85 </div>
85 </div>
86 <div class="field">
86 <div class="field">
87 <span class="help-block">${_('Number of items displayed in the main page dashboard before pagination is shown.')}</span>
87 <span class="help-block">${_('Number of items displayed in the main page dashboard before pagination is shown.')}</span>
88 </div>
88 </div>
89
89
90 <div class="label">
90 <div class="label">
91 <label for="rhodecode_admin_grid_items">${_('Admin pages items')}</label>
91 <label for="rhodecode_admin_grid_items">${_('Admin pages items')}</label>
92 </div>
92 </div>
93 <div class="field input">
93 <div class="field input">
94 ${h.text('rhodecode_admin_grid_items',size=5)}
94 ${h.text('rhodecode_admin_grid_items',size=5)}
95 </div>
95 </div>
96 <div class="field">
96 <div class="field">
97 <span class="help-block">${_('Number of items displayed in the admin pages grids before pagination is shown.')}</span>
97 <span class="help-block">${_('Number of items displayed in the admin pages grids before pagination is shown.')}</span>
98 </div>
98 </div>
99 </div>
99 </div>
100 </div>
100 </div>
101
101
102
102
103
103
104 <div class="panel panel-default">
104 <div class="panel panel-default">
105 <div class="panel-heading" id="commit-id">
105 <div class="panel-heading" id="commit-id">
106 <h3 class="panel-title">${_('Commit ID Style')}</h3>
106 <h3 class="panel-title">${_('Commit ID Style')}</h3>
107 </div>
107 </div>
108 <div class="panel-body">
108 <div class="panel-body">
109 <div class="label">
109 <div class="label">
110 <label for="rhodecode_show_sha_length">${_('Commit sha length')}</label>
110 <label for="rhodecode_show_sha_length">${_('Commit sha length')}</label>
111 </div>
111 </div>
112 <div class="input">
112 <div class="input">
113 <div class="field">
113 <div class="field">
114 ${h.text('rhodecode_show_sha_length',size=5)}
114 ${h.text('rhodecode_show_sha_length',size=5)}
115 </div>
115 </div>
116 <div class="field">
116 <div class="field">
117 <span class="help-block">${_('''Number of chars to show in commit sha displayed in web interface.
117 <span class="help-block">${_('''Number of chars to show in commit sha displayed in web interface.
118 By default it's shown as r123:9043a6a4c226 this value defines the
118 By default it's shown as r123:9043a6a4c226 this value defines the
119 length of the sha after the `r123:` part.''')}</span>
119 length of the sha after the `r123:` part.''')}</span>
120 </div>
120 </div>
121 </div>
121 </div>
122
122
123 <div class="checkbox">
123 <div class="checkbox">
124 ${h.checkbox('rhodecode_show_revision_number','True')}
124 ${h.checkbox('rhodecode_show_revision_number','True')}
125 <label for="rhodecode_show_revision_number">${_('Show commit ID numeric reference')} / ${_('Commit show revision number')}</label>
125 <label for="rhodecode_show_revision_number">${_('Show commit ID numeric reference')} / ${_('Commit show revision number')}</label>
126 </div>
126 </div>
127 <span class="help-block">${_('''Show revision number in commit sha displayed in web interface.
127 <span class="help-block">${_('''Show revision number in commit sha displayed in web interface.
128 By default it's shown as r123:9043a6a4c226 this value defines the
128 By default it's shown as r123:9043a6a4c226 this value defines the
129 if the `r123:` part is shown.''')}</span>
129 if the `r123:` part is shown.''')}</span>
130 </div>
130 </div>
131 </div>
131 </div>
132
132
133
133
134 <div class="panel panel-default">
134 <div class="panel panel-default">
135 <div class="panel-heading" id="icons">
135 <div class="panel-heading" id="icons">
136 <h3 class="panel-title">${_('Icons')}</h3>
136 <h3 class="panel-title">${_('Icons')}</h3>
137 </div>
137 </div>
138 <div class="panel-body">
138 <div class="panel-body">
139 <div class="checkbox">
139 <div class="checkbox">
140 ${h.checkbox('rhodecode_show_public_icon','True')}
140 ${h.checkbox('rhodecode_show_public_icon','True')}
141 <label for="rhodecode_show_public_icon">${_('Show public repo icon on repositories')}</label>
141 <label for="rhodecode_show_public_icon">${_('Show public repo icon on repositories')}</label>
142 </div>
142 </div>
143 <div></div>
143 <div></div>
144
144
145 <div class="checkbox">
145 <div class="checkbox">
146 ${h.checkbox('rhodecode_show_private_icon','True')}
146 ${h.checkbox('rhodecode_show_private_icon','True')}
147 <label for="rhodecode_show_private_icon">${_('Show private repo icon on repositories')}</label>
147 <label for="rhodecode_show_private_icon">${_('Show private repo icon on repositories')}</label>
148 </div>
148 </div>
149 <span class="help-block">${_('Show public/private icons next to repositories names.')}</span>
149 <span class="help-block">${_('Show public/private icons next to repositories names.')}</span>
150 </div>
150 </div>
151 </div>
151 </div>
152
152
153
153
154 <div class="panel panel-default">
154 <div class="panel panel-default">
155 <div class="panel-heading">
155 <div class="panel-heading">
156 <h3 class="panel-title">${_('Markup Renderer')}</h3>
156 <h3 class="panel-title">${_('Markup Renderer')}</h3>
157 </div>
157 </div>
158 <div class="panel-body">
158 <div class="panel-body">
159 <div class="field select">
159 <div class="field select">
160 ${h.select('rhodecode_markup_renderer', '', ['rst', 'markdown'])}
160 ${h.select('rhodecode_markup_renderer', '', ['rst', 'markdown'])}
161 </div>
161 </div>
162 <div class="field">
162 <div class="field">
163 <span class="help-block">${_('Default renderer used to render comments, pull request descriptions and other description elements. After change old entries will still work correctly.')}</span>
163 <span class="help-block">${_('Default renderer used to render comments, pull request descriptions and other description elements. After change old entries will still work correctly.')}</span>
164 </div>
164 </div>
165 </div>
165 </div>
166 </div>
166 </div>
167
167
168 <div class="panel panel-default">
168 <div class="panel panel-default">
169 <div class="panel-heading">
169 <div class="panel-heading">
170 <h3 class="panel-title">${_('Clone URL')}</h3>
170 <h3 class="panel-title">${_('Clone URL templates')}</h3>
171 </div>
171 </div>
172 <div class="panel-body">
172 <div class="panel-body">
173 <div class="field">
173 <div class="field">
174 ${h.text('rhodecode_clone_uri_tmpl', size=60)}
174 ${h.text('rhodecode_clone_uri_tmpl', size=60)} HTTP[S]
175 </div>
175 </div>
176
176 <div class="field">
177 ${h.text('rhodecode_clone_uri_ssh_tmpl', size=60)} SSH
178 </div>
177 <div class="field">
179 <div class="field">
178 <span class="help-block">
180 <span class="help-block">
179 ${_('''Schema of clone url construction eg. '{scheme}://{user}@{netloc}/{repo}', available vars:
181 ${_('''Schema of clone url construction eg. '{scheme}://{user}@{netloc}/{repo}', available vars:
180 {scheme} 'http' or 'https' sent from running RhodeCode server,
182 {scheme} 'http' or 'https' sent from running RhodeCode server,
181 {user} current user username,
183 {user} current user username,
184 {sys_user} current system user running this process, usefull for ssh,
185 {hostname} hostname of this server running RhodeCode,
182 {netloc} network location/server host of running RhodeCode server,
186 {netloc} network location/server host of running RhodeCode server,
183 {repo} full repository name,
187 {repo} full repository name,
184 {repoid} ID of repository, can be used to contruct clone-by-id''')}
188 {repoid} ID of repository, can be used to contruct clone-by-id''')}
185 </span>
189 </span>
186 </div>
190 </div>
187 </div>
191 </div>
188 </div>
192 </div>
189
193
190 <div class="panel panel-default">
194 <div class="panel panel-default">
191 <div class="panel-heading">
195 <div class="panel-heading">
192 <h3 class="panel-title">${_('Custom Support Link')}</h3>
196 <h3 class="panel-title">${_('Custom Support Link')}</h3>
193 </div>
197 </div>
194 <div class="panel-body">
198 <div class="panel-body">
195 <div class="field">
199 <div class="field">
196 ${h.text('rhodecode_support_url', size=60)}
200 ${h.text('rhodecode_support_url', size=60)}
197 </div>
201 </div>
198 <div class="field">
202 <div class="field">
199 <span class="help-block">
203 <span class="help-block">
200 ${_('''Custom url for the support link located at the bottom.
204 ${_('''Custom url for the support link located at the bottom.
201 The default is set to %(default_url)s. In case there's a need
205 The default is set to %(default_url)s. In case there's a need
202 to change the support link to internal issue tracker, it should be done here.
206 to change the support link to internal issue tracker, it should be done here.
203 ''') % {'default_url': h.route_url('rhodecode_support')}}
207 ''') % {'default_url': h.route_url('rhodecode_support')}}
204 </span>
208 </span>
205 </div>
209 </div>
206 </div>
210 </div>
207 </div>
211 </div>
208
212
209 <div class="buttons">
213 <div class="buttons">
210 ${h.submit('save',_('Save settings'),class_="btn")}
214 ${h.submit('save',_('Save settings'),class_="btn")}
211 ${h.reset('reset',_('Reset'),class_="btn")}
215 ${h.reset('reset',_('Reset'),class_="btn")}
212 </div>
216 </div>
213
217
214
218
215 ${h.end_form()}
219 ${h.end_form()}
216
220
217 <script>
221 <script>
218 $(document).ready(function() {
222 $(document).ready(function() {
219 $('#rhodecode_markup_renderer').select2({
223 $('#rhodecode_markup_renderer').select2({
220 containerCssClass: 'drop-menu',
224 containerCssClass: 'drop-menu',
221 dropdownCssClass: 'drop-menu-dropdown',
225 dropdownCssClass: 'drop-menu-dropdown',
222 dropdownAutoWidth: true,
226 dropdownAutoWidth: true,
223 minimumResultsForSearch: -1
227 minimumResultsForSearch: -1
224 });
228 });
225 });
229 });
226 </script>
230 </script>
@@ -1,210 +1,214 b''
1 <%def name="refs_counters(branches, closed_branches, tags, bookmarks)">
1 <%def name="refs_counters(branches, closed_branches, tags, bookmarks)">
2 <span class="branchtag tag">
2 <span class="branchtag tag">
3 <a href="${h.route_path('branches_home',repo_name=c.repo_name)}" class="childs">
3 <a href="${h.route_path('branches_home',repo_name=c.repo_name)}" class="childs">
4 <i class="icon-branch"></i>${_ungettext(
4 <i class="icon-branch"></i>${_ungettext(
5 '%(num)s Branch','%(num)s Branches', len(branches)) % {'num': len(branches)}}</a>
5 '%(num)s Branch','%(num)s Branches', len(branches)) % {'num': len(branches)}}</a>
6 </span>
6 </span>
7
7
8 %if closed_branches:
8 %if closed_branches:
9 <span class="branchtag tag">
9 <span class="branchtag tag">
10 <a href="${h.route_path('branches_home',repo_name=c.repo_name)}" class="childs">
10 <a href="${h.route_path('branches_home',repo_name=c.repo_name)}" class="childs">
11 <i class="icon-branch"></i>${_ungettext(
11 <i class="icon-branch"></i>${_ungettext(
12 '%(num)s Closed Branch', '%(num)s Closed Branches', len(closed_branches)) % {'num': len(closed_branches)}}</a>
12 '%(num)s Closed Branch', '%(num)s Closed Branches', len(closed_branches)) % {'num': len(closed_branches)}}</a>
13 </span>
13 </span>
14 %endif
14 %endif
15
15
16 <span class="tagtag tag">
16 <span class="tagtag tag">
17 <a href="${h.route_path('tags_home',repo_name=c.repo_name)}" class="childs">
17 <a href="${h.route_path('tags_home',repo_name=c.repo_name)}" class="childs">
18 <i class="icon-tag"></i>${_ungettext(
18 <i class="icon-tag"></i>${_ungettext(
19 '%(num)s Tag', '%(num)s Tags', len(tags)) % {'num': len(tags)}}</a>
19 '%(num)s Tag', '%(num)s Tags', len(tags)) % {'num': len(tags)}}</a>
20 </span>
20 </span>
21
21
22 %if bookmarks:
22 %if bookmarks:
23 <span class="booktag tag">
23 <span class="booktag tag">
24 <a href="${h.route_path('bookmarks_home',repo_name=c.repo_name)}" class="childs">
24 <a href="${h.route_path('bookmarks_home',repo_name=c.repo_name)}" class="childs">
25 <i class="icon-bookmark"></i>${_ungettext(
25 <i class="icon-bookmark"></i>${_ungettext(
26 '%(num)s Bookmark', '%(num)s Bookmarks', len(bookmarks)) % {'num': len(bookmarks)}}</a>
26 '%(num)s Bookmark', '%(num)s Bookmarks', len(bookmarks)) % {'num': len(bookmarks)}}</a>
27 </span>
27 </span>
28 %endif
28 %endif
29 </%def>
29 </%def>
30
30
31 <%def name="summary_detail(breadcrumbs_links, show_downloads=True)">
31 <%def name="summary_detail(breadcrumbs_links, show_downloads=True)">
32 <% summary = lambda n:{False:'summary-short'}.get(n) %>
32 <% summary = lambda n:{False:'summary-short'}.get(n) %>
33
33
34 <div id="summary-menu-stats" class="summary-detail">
34 <div id="summary-menu-stats" class="summary-detail">
35 <div class="summary-detail-header">
35 <div class="summary-detail-header">
36 <div class="breadcrumbs files_location">
36 <div class="breadcrumbs files_location">
37 <h4>
37 <h4>
38 ${breadcrumbs_links}
38 ${breadcrumbs_links}
39 </h4>
39 </h4>
40 </div>
40 </div>
41 <div id="summary_details_expand" class="btn-collapse" data-toggle="summary-details">
41 <div id="summary_details_expand" class="btn-collapse" data-toggle="summary-details">
42 ${_('Show More')}
42 ${_('Show More')}
43 </div>
43 </div>
44 </div>
44 </div>
45
45
46 <div class="fieldset">
46 <div class="fieldset">
47 %if h.is_svn_without_proxy(c.rhodecode_db_repo):
48 <div class="left-label disabled">
49 ${_('Read-only url')}:
50 </div>
51 <div class="right-content disabled">
52 <input type="text" class="input-monospace" id="clone_url" disabled value="${c.clone_repo_url}"/>
53 <i id="clone_by_name_copy" class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url}" title="${_('Copy the clone url')}"></i>
54
47
55 <input type="text" class="input-monospace" id="clone_url_id" disabled value="${c.clone_repo_url_id}" style="display: none;"/>
48 <div class="left-clone">
56 <i id="clone_by_id_copy" class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url_id}" title="${_('Copy the clone by id url')}" style="display: none"></i>
49 <select id="clone_option" name="clone_option">
57
50 <option value="http" selected="selected">HTTP</option>
58 <a id="clone_by_name" class="clone" style="display: none;">${_('Show by Name')}</a>
51 <option value="http_id">HTTP UID</option>
59 <a id="clone_by_id" class="clone">${_('Show by ID')}</a>
52 <option value="ssh">SSH</option>
60
53 </select>
61 <p class="help-block">${_('SVN Protocol is disabled. To enable it, see the')} <a href="${h.route_url('enterprise_svn_setup')}" target="_blank">${_('documentation here')}</a>.</p>
62 </div>
54 </div>
63 %else:
55 <div class="right-clone">
64 <div class="left-label">
56 <%
65 ${_('Clone url')}:
57 maybe_disabled = ''
66 </div>
58 if h.is_svn_without_proxy(c.rhodecode_db_repo):
67 <div class="right-content">
59 maybe_disabled = 'disabled'
68 <input type="text" class="input-monospace" id="clone_url" readonly="readonly" value="${c.clone_repo_url}"/>
60 %>
69 <i id="clone_by_name_copy" class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url}" title="${_('Copy the clone url')}"></i>
61
62 <span id="clone_option_http">
63 <input type="text" class="input-monospace clone_url_input" ${maybe_disabled} readonly="readonly" value="${c.clone_repo_url}"/>
64 <i class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url}" title="${_('Copy the clone url')}"></i>
65 </span>
70
66
71 <input type="text" class="input-monospace" id="clone_url_id" readonly="readonly" value="${c.clone_repo_url_id}" style="display: none;"/>
67 <span style="display: none;" id="clone_option_http_id">
72 <i id="clone_by_id_copy" class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url_id}" title="${_('Copy the clone by id url')}" style="display: none"></i>
68 <input type="text" class="input-monospace clone_url_input" ${maybe_disabled} readonly="readonly" value="${c.clone_repo_url_id}"/>
69 <i class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url_id}" title="${_('Copy the clone by id url')}"></i>
70 </span>
73
71
74 <a id="clone_by_name" class="clone" style="display: none;">${_('Show by Name')}</a>
72 <span style="display: none;" id="clone_option_ssh">
75 <a id="clone_by_id" class="clone">${_('Show by ID')}</a>
73 <input type="text" class="input-monospace clone_url_input" ${maybe_disabled} readonly="readonly" value="${c.clone_repo_url_ssh}"/>
74 <i class="tooltip icon-clipboard clipboard-action" data-clipboard-text="${c.clone_repo_url_ssh}" title="${_('Copy the clone by ssh url')}"></i>
75 </span>
76
77 % if maybe_disabled:
78 <p class="help-block">${_('SVN Protocol is disabled. To enable it, see the')} <a href="${h.route_url('enterprise_svn_setup')}" target="_blank">${_('documentation here')}</a>.</p>
79 % endif
80
76 </div>
81 </div>
77 %endif
78 </div>
82 </div>
79
83
80 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
84 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
81 <div class="left-label">
85 <div class="left-label">
82 ${_('Description')}:
86 ${_('Description')}:
83 </div>
87 </div>
84 <div class="right-content">
88 <div class="right-content">
85 <div class="input ${summary(c.show_stats)}">
89 <div class="input ${summary(c.show_stats)}">
86 <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
90 <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
87 ${dt.repo_desc(c.rhodecode_db_repo.description_safe, c.visual.stylify_metatags)}
91 ${dt.repo_desc(c.rhodecode_db_repo.description_safe, c.visual.stylify_metatags)}
88 </div>
92 </div>
89 </div>
93 </div>
90 </div>
94 </div>
91
95
92 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
96 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
93 <div class="left-label">
97 <div class="left-label">
94 ${_('Information')}:
98 ${_('Information')}:
95 </div>
99 </div>
96 <div class="right-content">
100 <div class="right-content">
97
101
98 <div class="repo-size">
102 <div class="repo-size">
99 <% commit_rev = c.rhodecode_db_repo.changeset_cache.get('revision') %>
103 <% commit_rev = c.rhodecode_db_repo.changeset_cache.get('revision') %>
100
104
101 ## commits
105 ## commits
102 % if commit_rev == -1:
106 % if commit_rev == -1:
103 ${_ungettext('%(num)s Commit', '%(num)s Commits', 0) % {'num': 0}},
107 ${_ungettext('%(num)s Commit', '%(num)s Commits', 0) % {'num': 0}},
104 % else:
108 % else:
105 <a href="${h.route_path('repo_changelog', repo_name=c.repo_name)}">
109 <a href="${h.route_path('repo_changelog', repo_name=c.repo_name)}">
106 ${_ungettext('%(num)s Commit', '%(num)s Commits', commit_rev) % {'num': commit_rev}}</a>,
110 ${_ungettext('%(num)s Commit', '%(num)s Commits', commit_rev) % {'num': commit_rev}}</a>,
107 % endif
111 % endif
108
112
109 ## forks
113 ## forks
110 <a title="${_('Number of Repository Forks')}" href="${h.route_path('repo_forks_show_all', repo_name=c.repo_name)}">
114 <a title="${_('Number of Repository Forks')}" href="${h.route_path('repo_forks_show_all', repo_name=c.repo_name)}">
111 ${c.repository_forks} ${_ungettext('Fork', 'Forks', c.repository_forks)}</a>,
115 ${c.repository_forks} ${_ungettext('Fork', 'Forks', c.repository_forks)}</a>,
112
116
113 ## repo size
117 ## repo size
114 % if commit_rev == -1:
118 % if commit_rev == -1:
115 <span class="stats-bullet">0 B</span>
119 <span class="stats-bullet">0 B</span>
116 % else:
120 % else:
117 <span class="stats-bullet" id="repo_size_container">
121 <span class="stats-bullet" id="repo_size_container">
118 ${_('Calculating Repository Size...')}
122 ${_('Calculating Repository Size...')}
119 </span>
123 </span>
120 % endif
124 % endif
121 </div>
125 </div>
122
126
123 <div class="commit-info">
127 <div class="commit-info">
124 <div class="tags">
128 <div class="tags">
125 % if c.rhodecode_repo:
129 % if c.rhodecode_repo:
126 ${refs_counters(
130 ${refs_counters(
127 c.rhodecode_repo.branches,
131 c.rhodecode_repo.branches,
128 c.rhodecode_repo.branches_closed,
132 c.rhodecode_repo.branches_closed,
129 c.rhodecode_repo.tags,
133 c.rhodecode_repo.tags,
130 c.rhodecode_repo.bookmarks)}
134 c.rhodecode_repo.bookmarks)}
131 % else:
135 % else:
132 ## missing requirements can make c.rhodecode_repo None
136 ## missing requirements can make c.rhodecode_repo None
133 ${refs_counters([], [], [], [])}
137 ${refs_counters([], [], [], [])}
134 % endif
138 % endif
135 </div>
139 </div>
136 </div>
140 </div>
137
141
138 </div>
142 </div>
139 </div>
143 </div>
140
144
141 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
145 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
142 <div class="left-label">
146 <div class="left-label">
143 ${_('Statistics')}:
147 ${_('Statistics')}:
144 </div>
148 </div>
145 <div class="right-content">
149 <div class="right-content">
146 <div class="input ${summary(c.show_stats)} statistics">
150 <div class="input ${summary(c.show_stats)} statistics">
147 % if c.show_stats:
151 % if c.show_stats:
148 <div id="lang_stats" class="enabled">
152 <div id="lang_stats" class="enabled">
149 ${_('Calculating Code Statistics...')}
153 ${_('Calculating Code Statistics...')}
150 </div>
154 </div>
151 % else:
155 % else:
152 <span class="disabled">
156 <span class="disabled">
153 ${_('Statistics are disabled for this repository')}
157 ${_('Statistics are disabled for this repository')}
154 </span>
158 </span>
155 % if h.HasPermissionAll('hg.admin')('enable stats on from summary'):
159 % if h.HasPermissionAll('hg.admin')('enable stats on from summary'):
156 , ${h.link_to(_('enable statistics'),h.route_path('edit_repo',repo_name=c.repo_name, _anchor='repo_enable_statistics'))}
160 , ${h.link_to(_('enable statistics'),h.route_path('edit_repo',repo_name=c.repo_name, _anchor='repo_enable_statistics'))}
157 % endif
161 % endif
158 % endif
162 % endif
159 </div>
163 </div>
160
164
161 </div>
165 </div>
162 </div>
166 </div>
163
167
164 % if show_downloads:
168 % if show_downloads:
165 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
169 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
166 <div class="left-label">
170 <div class="left-label">
167 ${_('Downloads')}:
171 ${_('Downloads')}:
168 </div>
172 </div>
169 <div class="right-content">
173 <div class="right-content">
170 <div class="input ${summary(c.show_stats)} downloads">
174 <div class="input ${summary(c.show_stats)} downloads">
171 % if c.rhodecode_repo and len(c.rhodecode_repo.revisions) == 0:
175 % if c.rhodecode_repo and len(c.rhodecode_repo.revisions) == 0:
172 <span class="disabled">
176 <span class="disabled">
173 ${_('There are no downloads yet')}
177 ${_('There are no downloads yet')}
174 </span>
178 </span>
175 % elif not c.enable_downloads:
179 % elif not c.enable_downloads:
176 <span class="disabled">
180 <span class="disabled">
177 ${_('Downloads are disabled for this repository')}
181 ${_('Downloads are disabled for this repository')}
178 </span>
182 </span>
179 % if h.HasPermissionAll('hg.admin')('enable downloads on from summary'):
183 % if h.HasPermissionAll('hg.admin')('enable downloads on from summary'):
180 , ${h.link_to(_('enable downloads'),h.route_path('edit_repo',repo_name=c.repo_name, _anchor='repo_enable_downloads'))}
184 , ${h.link_to(_('enable downloads'),h.route_path('edit_repo',repo_name=c.repo_name, _anchor='repo_enable_downloads'))}
181 % endif
185 % endif
182 % else:
186 % else:
183 <span class="enabled">
187 <span class="enabled">
184 <a id="archive_link" class="btn btn-small" href="${h.route_path('repo_archivefile',repo_name=c.rhodecode_db_repo.repo_name,fname='tip.zip')}">
188 <a id="archive_link" class="btn btn-small" href="${h.route_path('repo_archivefile',repo_name=c.rhodecode_db_repo.repo_name,fname='tip.zip')}">
185 <i class="icon-archive"></i> tip.zip
189 <i class="icon-archive"></i> tip.zip
186 ## replaced by some JS on select
190 ## replaced by some JS on select
187 </a>
191 </a>
188 </span>
192 </span>
189 ${h.hidden('download_options')}
193 ${h.hidden('download_options')}
190 % endif
194 % endif
191 </div>
195 </div>
192 </div>
196 </div>
193 </div>
197 </div>
194 % endif
198 % endif
195
199
196 </div><!--end summary-detail-->
200 </div><!--end summary-detail-->
197 </%def>
201 </%def>
198
202
199 <%def name="summary_stats(gravatar_function)">
203 <%def name="summary_stats(gravatar_function)">
200 <div class="sidebar-right">
204 <div class="sidebar-right">
201 <div class="summary-detail-header">
205 <div class="summary-detail-header">
202 <h4 class="item">
206 <h4 class="item">
203 ${_('Owner')}
207 ${_('Owner')}
204 </h4>
208 </h4>
205 </div>
209 </div>
206 <div class="sidebar-right-content">
210 <div class="sidebar-right-content">
207 ${gravatar_function(c.rhodecode_db_repo.user.email, 16)}
211 ${gravatar_function(c.rhodecode_db_repo.user.email, 16)}
208 </div>
212 </div>
209 </div><!--end sidebar-right-->
213 </div><!--end sidebar-right-->
210 </%def>
214 </%def>
@@ -1,137 +1,119 b''
1 <%inherit file="/summary/summary_base.mako"/>
1 <%inherit file="/summary/summary_base.mako"/>
2
2
3 <%namespace name="components" file="/summary/components.mako"/>
3 <%namespace name="components" file="/summary/components.mako"/>
4
4
5
5
6 <%def name="menu_bar_subnav()">
6 <%def name="menu_bar_subnav()">
7 ${self.repo_menu(active='summary')}
7 ${self.repo_menu(active='summary')}
8 </%def>
8 </%def>
9
9
10 <%def name="main()">
10 <%def name="main()">
11
11
12 <div class="title">
12 <div class="title">
13 ${self.repo_page_title(c.rhodecode_db_repo)}
13 ${self.repo_page_title(c.rhodecode_db_repo)}
14 <ul class="links icon-only-links block-right">
14 <ul class="links icon-only-links block-right">
15 <li>
15 <li>
16 %if c.rhodecode_user.username != h.DEFAULT_USER:
16 %if c.rhodecode_user.username != h.DEFAULT_USER:
17 <a href="${h.route_path('atom_feed_home', repo_name=c.rhodecode_db_repo.repo_name, _query=dict(auth_token=c.rhodecode_user.feed_token))}" title="${_('RSS Feed')}"><i class="icon-rss-sign"></i></a>
17 <a href="${h.route_path('atom_feed_home', repo_name=c.rhodecode_db_repo.repo_name, _query=dict(auth_token=c.rhodecode_user.feed_token))}" title="${_('RSS Feed')}"><i class="icon-rss-sign"></i></a>
18 %else:
18 %else:
19 <a href="${h.route_path('atom_feed_home', repo_name=c.rhodecode_db_repo.repo_name)}" title="${_('RSS Feed')}"><i class="icon-rss-sign"></i></a>
19 <a href="${h.route_path('atom_feed_home', repo_name=c.rhodecode_db_repo.repo_name)}" title="${_('RSS Feed')}"><i class="icon-rss-sign"></i></a>
20 %endif
20 %endif
21 </li>
21 </li>
22 </ul>
22 </ul>
23 </div>
23 </div>
24
24
25 <div id="repo-summary" class="summary">
25 <div id="repo-summary" class="summary">
26 ${components.summary_detail(breadcrumbs_links=self.breadcrumbs_links(), show_downloads=True)}
26 ${components.summary_detail(breadcrumbs_links=self.breadcrumbs_links(), show_downloads=True)}
27 ${components.summary_stats(gravatar_function=self.gravatar_with_user)}
27 ${components.summary_stats(gravatar_function=self.gravatar_with_user)}
28 </div><!--end repo-summary-->
28 </div><!--end repo-summary-->
29
29
30
30
31 <div class="box" >
31 <div class="box" >
32 %if not c.repo_commits:
32 %if not c.repo_commits:
33 <div class="title">
33 <div class="title">
34 <h3>${_('Quick start')}</h3>
34 <h3>${_('Quick start')}</h3>
35 </div>
35 </div>
36 %endif
36 %endif
37 <div class="table">
37 <div class="table">
38 <div id="shortlog_data">
38 <div id="shortlog_data">
39 <%include file='summary_commits.mako'/>
39 <%include file='summary_commits.mako'/>
40 </div>
40 </div>
41 </div>
41 </div>
42 </div>
42 </div>
43
43
44 %if c.readme_data:
44 %if c.readme_data:
45 <div id="readme" class="anchor">
45 <div id="readme" class="anchor">
46 <div class="box" >
46 <div class="box" >
47 <div class="title" title="${h.tooltip(_('Readme file from commit %s:%s') % (c.rhodecode_db_repo.landing_rev[0], c.rhodecode_db_repo.landing_rev[1]))}">
47 <div class="title" title="${h.tooltip(_('Readme file from commit %s:%s') % (c.rhodecode_db_repo.landing_rev[0], c.rhodecode_db_repo.landing_rev[1]))}">
48 <h3 class="breadcrumbs">
48 <h3 class="breadcrumbs">
49 <a href="${h.route_path('repo_files',repo_name=c.repo_name,commit_id=c.rhodecode_db_repo.landing_rev[1],f_path=c.readme_file)}">${c.readme_file}</a>
49 <a href="${h.route_path('repo_files',repo_name=c.repo_name,commit_id=c.rhodecode_db_repo.landing_rev[1],f_path=c.readme_file)}">${c.readme_file}</a>
50 </h3>
50 </h3>
51 </div>
51 </div>
52 <div class="readme codeblock">
52 <div class="readme codeblock">
53 <div class="readme_box">
53 <div class="readme_box">
54 ${c.readme_data|n}
54 ${c.readme_data|n}
55 </div>
55 </div>
56 </div>
56 </div>
57 </div>
57 </div>
58 </div>
58 </div>
59 %endif
59 %endif
60
60
61 <script type="text/javascript">
61 <script type="text/javascript">
62 $(document).ready(function(){
62 $(document).ready(function(){
63 $('#clone_by_name').on('click',function(e){
63 $('#clone_option').on('change', function(e) {
64 // show url by name and hide name button
64 var selected = $(this).val();
65 $('#clone_url').show();
65 $.each(['http', 'http_id', 'ssh'], function (idx, val) {
66 $('#clone_by_name').hide();
66 if(val === selected){
67
67 $('#clone_option_' + val).show();
68 // hide url by id and show name button
68 } else {
69 $('#clone_by_id').show();
69 $('#clone_option_' + val).hide();
70 $('#clone_url_id').hide();
70 }
71
71 });
72 // hide copy by id
73 $('#clone_by_name_copy').show();
74 $('#clone_by_id_copy').hide();
75
76 });
77 $('#clone_by_id').on('click',function(e){
78
79 // show url by id and hide id button
80 $('#clone_by_id').hide();
81 $('#clone_url_id').show();
82
83 // hide url by name and show id button
84 $('#clone_by_name').show();
85 $('#clone_url').hide();
86
87 // hide copy by id
88 $('#clone_by_id_copy').show();
89 $('#clone_by_name_copy').hide();
90 });
72 });
91
73
92 var initialCommitData = {
74 var initialCommitData = {
93 id: null,
75 id: null,
94 text: 'tip',
76 text: 'tip',
95 type: 'tag',
77 type: 'tag',
96 raw_id: null,
78 raw_id: null,
97 files_url: null
79 files_url: null
98 };
80 };
99
81
100 select2RefSwitcher('#download_options', initialCommitData);
82 select2RefSwitcher('#download_options', initialCommitData);
101
83
102 // on change of download options
84 // on change of download options
103 $('#download_options').on('change', function(e) {
85 $('#download_options').on('change', function(e) {
104 // format of Object {text: "v0.0.3", type: "tag", id: "rev"}
86 // format of Object {text: "v0.0.3", type: "tag", id: "rev"}
105 var ext = '.zip';
87 var ext = '.zip';
106 var selected_cs = e.added;
88 var selected_cs = e.added;
107 var fname = e.added.raw_id + ext;
89 var fname = e.added.raw_id + ext;
108 var href = pyroutes.url('repo_archivefile', {'repo_name': templateContext.repo_name, 'fname':fname});
90 var href = pyroutes.url('repo_archivefile', {'repo_name': templateContext.repo_name, 'fname':fname});
109 // set new label
91 // set new label
110 $('#archive_link').html('<i class="icon-archive"></i> {0}{1}'.format(escapeHtml(e.added.text), ext));
92 $('#archive_link').html('<i class="icon-archive"></i> {0}{1}'.format(escapeHtml(e.added.text), ext));
111
93
112 // set new url to button,
94 // set new url to button,
113 $('#archive_link').attr('href', href)
95 $('#archive_link').attr('href', href)
114 });
96 });
115
97
116
98
117 // load details on summary page expand
99 // load details on summary page expand
118 $('#summary_details_expand').on('click', function() {
100 $('#summary_details_expand').on('click', function() {
119
101
120 var callback = function (data) {
102 var callback = function (data) {
121 % if c.show_stats:
103 % if c.show_stats:
122 showRepoStats('lang_stats', data);
104 showRepoStats('lang_stats', data);
123 % endif
105 % endif
124 };
106 };
125
107
126 showRepoSize(
108 showRepoSize(
127 'repo_size_container',
109 'repo_size_container',
128 templateContext.repo_name,
110 templateContext.repo_name,
129 templateContext.repo_landing_commit,
111 templateContext.repo_landing_commit,
130 callback);
112 callback);
131
113
132 })
114 })
133
115
134 })
116 })
135 </script>
117 </script>
136
118
137 </%def>
119 </%def>
General Comments 0
You need to be logged in to leave comments. Login now