##// 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 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21
22 22 import logging
23 23 import collections
24 24
25 25 import datetime
26 26 import formencode
27 27 import formencode.htmlfill
28 28
29 29 import rhodecode
30 30 from pyramid.view import view_config
31 31 from pyramid.httpexceptions import HTTPFound, HTTPNotFound
32 32 from pyramid.renderers import render
33 33 from pyramid.response import Response
34 34
35 35 from rhodecode.apps._base import BaseAppView
36 36 from rhodecode.apps.admin.navigation import navigation_list
37 37 from rhodecode.apps.svn_support.config_keys import generate_config
38 38 from rhodecode.lib import helpers as h
39 39 from rhodecode.lib.auth import (
40 40 LoginRequired, HasPermissionAllDecorator, CSRFRequired)
41 41 from rhodecode.lib.celerylib import tasks, run_task
42 42 from rhodecode.lib.utils import repo2db_mapper
43 43 from rhodecode.lib.utils2 import str2bool, safe_unicode, AttributeDict
44 44 from rhodecode.lib.index import searcher_from_config
45 45
46 46 from rhodecode.model.db import RhodeCodeUi, Repository
47 47 from rhodecode.model.forms import (ApplicationSettingsForm,
48 48 ApplicationUiSettingsForm, ApplicationVisualisationForm,
49 49 LabsSettingsForm, IssueTrackerPatternsForm)
50 50 from rhodecode.model.repo_group import RepoGroupModel
51 51
52 52 from rhodecode.model.scm import ScmModel
53 53 from rhodecode.model.notification import EmailNotificationModel
54 54 from rhodecode.model.meta import Session
55 55 from rhodecode.model.settings import (
56 56 IssueTrackerSettingsModel, VcsSettingsModel, SettingNotFound,
57 57 SettingsModel)
58 58
59 59
60 60 log = logging.getLogger(__name__)
61 61
62 62
63 63 class AdminSettingsView(BaseAppView):
64 64
65 65 def load_default_context(self):
66 66 c = self._get_local_tmpl_context()
67 67 c.labs_active = str2bool(
68 68 rhodecode.CONFIG.get('labs_settings_active', 'true'))
69 69 c.navlist = navigation_list(self.request)
70 70
71 71 return c
72 72
73 73 @classmethod
74 74 def _get_ui_settings(cls):
75 75 ret = RhodeCodeUi.query().all()
76 76
77 77 if not ret:
78 78 raise Exception('Could not get application ui settings !')
79 79 settings = {}
80 80 for each in ret:
81 81 k = each.ui_key
82 82 v = each.ui_value
83 83 if k == '/':
84 84 k = 'root_path'
85 85
86 86 if k in ['push_ssl', 'publish', 'enabled']:
87 87 v = str2bool(v)
88 88
89 89 if k.find('.') != -1:
90 90 k = k.replace('.', '_')
91 91
92 92 if each.ui_section in ['hooks', 'extensions']:
93 93 v = each.ui_active
94 94
95 95 settings[each.ui_section + '_' + k] = v
96 96 return settings
97 97
98 98 @classmethod
99 99 def _form_defaults(cls):
100 100 defaults = SettingsModel().get_all_settings()
101 101 defaults.update(cls._get_ui_settings())
102 102
103 103 defaults.update({
104 104 'new_svn_branch': '',
105 105 'new_svn_tag': '',
106 106 })
107 107 return defaults
108 108
109 109 @LoginRequired()
110 110 @HasPermissionAllDecorator('hg.admin')
111 111 @view_config(
112 112 route_name='admin_settings_vcs', request_method='GET',
113 113 renderer='rhodecode:templates/admin/settings/settings.mako')
114 114 def settings_vcs(self):
115 115 c = self.load_default_context()
116 116 c.active = 'vcs'
117 117 model = VcsSettingsModel()
118 118 c.svn_branch_patterns = model.get_global_svn_branch_patterns()
119 119 c.svn_tag_patterns = model.get_global_svn_tag_patterns()
120 120
121 121 settings = self.request.registry.settings
122 122 c.svn_proxy_generate_config = settings[generate_config]
123 123
124 124 defaults = self._form_defaults()
125 125
126 126 model.create_largeobjects_dirs_if_needed(defaults['paths_root_path'])
127 127
128 128 data = render('rhodecode:templates/admin/settings/settings.mako',
129 129 self._get_template_context(c), self.request)
130 130 html = formencode.htmlfill.render(
131 131 data,
132 132 defaults=defaults,
133 133 encoding="UTF-8",
134 134 force_defaults=False
135 135 )
136 136 return Response(html)
137 137
138 138 @LoginRequired()
139 139 @HasPermissionAllDecorator('hg.admin')
140 140 @CSRFRequired()
141 141 @view_config(
142 142 route_name='admin_settings_vcs_update', request_method='POST',
143 143 renderer='rhodecode:templates/admin/settings/settings.mako')
144 144 def settings_vcs_update(self):
145 145 _ = self.request.translate
146 146 c = self.load_default_context()
147 147 c.active = 'vcs'
148 148
149 149 model = VcsSettingsModel()
150 150 c.svn_branch_patterns = model.get_global_svn_branch_patterns()
151 151 c.svn_tag_patterns = model.get_global_svn_tag_patterns()
152 152
153 153 settings = self.request.registry.settings
154 154 c.svn_proxy_generate_config = settings[generate_config]
155 155
156 156 application_form = ApplicationUiSettingsForm(self.request.translate)()
157 157
158 158 try:
159 159 form_result = application_form.to_python(dict(self.request.POST))
160 160 except formencode.Invalid as errors:
161 161 h.flash(
162 162 _("Some form inputs contain invalid data."),
163 163 category='error')
164 164 data = render('rhodecode:templates/admin/settings/settings.mako',
165 165 self._get_template_context(c), self.request)
166 166 html = formencode.htmlfill.render(
167 167 data,
168 168 defaults=errors.value,
169 169 errors=errors.error_dict or {},
170 170 prefix_error=False,
171 171 encoding="UTF-8",
172 172 force_defaults=False
173 173 )
174 174 return Response(html)
175 175
176 176 try:
177 177 if c.visual.allow_repo_location_change:
178 178 model.update_global_path_setting(
179 179 form_result['paths_root_path'])
180 180
181 181 model.update_global_ssl_setting(form_result['web_push_ssl'])
182 182 model.update_global_hook_settings(form_result)
183 183
184 184 model.create_or_update_global_svn_settings(form_result)
185 185 model.create_or_update_global_hg_settings(form_result)
186 186 model.create_or_update_global_git_settings(form_result)
187 187 model.create_or_update_global_pr_settings(form_result)
188 188 except Exception:
189 189 log.exception("Exception while updating settings")
190 190 h.flash(_('Error occurred during updating '
191 191 'application settings'), category='error')
192 192 else:
193 193 Session().commit()
194 194 h.flash(_('Updated VCS settings'), category='success')
195 195 raise HTTPFound(h.route_path('admin_settings_vcs'))
196 196
197 197 data = render('rhodecode:templates/admin/settings/settings.mako',
198 198 self._get_template_context(c), self.request)
199 199 html = formencode.htmlfill.render(
200 200 data,
201 201 defaults=self._form_defaults(),
202 202 encoding="UTF-8",
203 203 force_defaults=False
204 204 )
205 205 return Response(html)
206 206
207 207 @LoginRequired()
208 208 @HasPermissionAllDecorator('hg.admin')
209 209 @CSRFRequired()
210 210 @view_config(
211 211 route_name='admin_settings_vcs_svn_pattern_delete', request_method='POST',
212 212 renderer='json_ext', xhr=True)
213 213 def settings_vcs_delete_svn_pattern(self):
214 214 delete_pattern_id = self.request.POST.get('delete_svn_pattern')
215 215 model = VcsSettingsModel()
216 216 try:
217 217 model.delete_global_svn_pattern(delete_pattern_id)
218 218 except SettingNotFound:
219 219 log.exception(
220 220 'Failed to delete svn_pattern with id %s', delete_pattern_id)
221 221 raise HTTPNotFound()
222 222
223 223 Session().commit()
224 224 return True
225 225
226 226 @LoginRequired()
227 227 @HasPermissionAllDecorator('hg.admin')
228 228 @view_config(
229 229 route_name='admin_settings_mapping', request_method='GET',
230 230 renderer='rhodecode:templates/admin/settings/settings.mako')
231 231 def settings_mapping(self):
232 232 c = self.load_default_context()
233 233 c.active = 'mapping'
234 234
235 235 data = render('rhodecode:templates/admin/settings/settings.mako',
236 236 self._get_template_context(c), self.request)
237 237 html = formencode.htmlfill.render(
238 238 data,
239 239 defaults=self._form_defaults(),
240 240 encoding="UTF-8",
241 241 force_defaults=False
242 242 )
243 243 return Response(html)
244 244
245 245 @LoginRequired()
246 246 @HasPermissionAllDecorator('hg.admin')
247 247 @CSRFRequired()
248 248 @view_config(
249 249 route_name='admin_settings_mapping_update', request_method='POST',
250 250 renderer='rhodecode:templates/admin/settings/settings.mako')
251 251 def settings_mapping_update(self):
252 252 _ = self.request.translate
253 253 c = self.load_default_context()
254 254 c.active = 'mapping'
255 255 rm_obsolete = self.request.POST.get('destroy', False)
256 256 invalidate_cache = self.request.POST.get('invalidate', False)
257 257 log.debug(
258 258 'rescanning repo location with destroy obsolete=%s', rm_obsolete)
259 259
260 260 if invalidate_cache:
261 261 log.debug('invalidating all repositories cache')
262 262 for repo in Repository.get_all():
263 263 ScmModel().mark_for_invalidation(repo.repo_name, delete=True)
264 264
265 265 filesystem_repos = ScmModel().repo_scan()
266 266 added, removed = repo2db_mapper(filesystem_repos, rm_obsolete)
267 267 _repr = lambda l: ', '.join(map(safe_unicode, l)) or '-'
268 268 h.flash(_('Repositories successfully '
269 269 'rescanned added: %s ; removed: %s') %
270 270 (_repr(added), _repr(removed)),
271 271 category='success')
272 272 raise HTTPFound(h.route_path('admin_settings_mapping'))
273 273
274 274 @LoginRequired()
275 275 @HasPermissionAllDecorator('hg.admin')
276 276 @view_config(
277 277 route_name='admin_settings', request_method='GET',
278 278 renderer='rhodecode:templates/admin/settings/settings.mako')
279 279 @view_config(
280 280 route_name='admin_settings_global', request_method='GET',
281 281 renderer='rhodecode:templates/admin/settings/settings.mako')
282 282 def settings_global(self):
283 283 c = self.load_default_context()
284 284 c.active = 'global'
285 285 c.personal_repo_group_default_pattern = RepoGroupModel()\
286 286 .get_personal_group_name_pattern()
287 287
288 288 data = render('rhodecode:templates/admin/settings/settings.mako',
289 289 self._get_template_context(c), self.request)
290 290 html = formencode.htmlfill.render(
291 291 data,
292 292 defaults=self._form_defaults(),
293 293 encoding="UTF-8",
294 294 force_defaults=False
295 295 )
296 296 return Response(html)
297 297
298 298 @LoginRequired()
299 299 @HasPermissionAllDecorator('hg.admin')
300 300 @CSRFRequired()
301 301 @view_config(
302 302 route_name='admin_settings_update', request_method='POST',
303 303 renderer='rhodecode:templates/admin/settings/settings.mako')
304 304 @view_config(
305 305 route_name='admin_settings_global_update', request_method='POST',
306 306 renderer='rhodecode:templates/admin/settings/settings.mako')
307 307 def settings_global_update(self):
308 308 _ = self.request.translate
309 309 c = self.load_default_context()
310 310 c.active = 'global'
311 311 c.personal_repo_group_default_pattern = RepoGroupModel()\
312 312 .get_personal_group_name_pattern()
313 313 application_form = ApplicationSettingsForm(self.request.translate)()
314 314 try:
315 315 form_result = application_form.to_python(dict(self.request.POST))
316 316 except formencode.Invalid as errors:
317 317 data = render('rhodecode:templates/admin/settings/settings.mako',
318 318 self._get_template_context(c), self.request)
319 319 html = formencode.htmlfill.render(
320 320 data,
321 321 defaults=errors.value,
322 322 errors=errors.error_dict or {},
323 323 prefix_error=False,
324 324 encoding="UTF-8",
325 325 force_defaults=False
326 326 )
327 327 return Response(html)
328 328
329 329 settings = [
330 330 ('title', 'rhodecode_title', 'unicode'),
331 331 ('realm', 'rhodecode_realm', 'unicode'),
332 332 ('pre_code', 'rhodecode_pre_code', 'unicode'),
333 333 ('post_code', 'rhodecode_post_code', 'unicode'),
334 334 ('captcha_public_key', 'rhodecode_captcha_public_key', 'unicode'),
335 335 ('captcha_private_key', 'rhodecode_captcha_private_key', 'unicode'),
336 336 ('create_personal_repo_group', 'rhodecode_create_personal_repo_group', 'bool'),
337 337 ('personal_repo_group_pattern', 'rhodecode_personal_repo_group_pattern', 'unicode'),
338 338 ]
339 339 try:
340 340 for setting, form_key, type_ in settings:
341 341 sett = SettingsModel().create_or_update_setting(
342 342 setting, form_result[form_key], type_)
343 343 Session().add(sett)
344 344
345 345 Session().commit()
346 346 SettingsModel().invalidate_settings_cache()
347 347 h.flash(_('Updated application settings'), category='success')
348 348 except Exception:
349 349 log.exception("Exception while updating application settings")
350 350 h.flash(
351 351 _('Error occurred during updating application settings'),
352 352 category='error')
353 353
354 354 raise HTTPFound(h.route_path('admin_settings_global'))
355 355
356 356 @LoginRequired()
357 357 @HasPermissionAllDecorator('hg.admin')
358 358 @view_config(
359 359 route_name='admin_settings_visual', request_method='GET',
360 360 renderer='rhodecode:templates/admin/settings/settings.mako')
361 361 def settings_visual(self):
362 362 c = self.load_default_context()
363 363 c.active = 'visual'
364 364
365 365 data = render('rhodecode:templates/admin/settings/settings.mako',
366 366 self._get_template_context(c), self.request)
367 367 html = formencode.htmlfill.render(
368 368 data,
369 369 defaults=self._form_defaults(),
370 370 encoding="UTF-8",
371 371 force_defaults=False
372 372 )
373 373 return Response(html)
374 374
375 375 @LoginRequired()
376 376 @HasPermissionAllDecorator('hg.admin')
377 377 @CSRFRequired()
378 378 @view_config(
379 379 route_name='admin_settings_visual_update', request_method='POST',
380 380 renderer='rhodecode:templates/admin/settings/settings.mako')
381 381 def settings_visual_update(self):
382 382 _ = self.request.translate
383 383 c = self.load_default_context()
384 384 c.active = 'visual'
385 385 application_form = ApplicationVisualisationForm(self.request.translate)()
386 386 try:
387 387 form_result = application_form.to_python(dict(self.request.POST))
388 388 except formencode.Invalid as errors:
389 389 data = render('rhodecode:templates/admin/settings/settings.mako',
390 390 self._get_template_context(c), self.request)
391 391 html = formencode.htmlfill.render(
392 392 data,
393 393 defaults=errors.value,
394 394 errors=errors.error_dict or {},
395 395 prefix_error=False,
396 396 encoding="UTF-8",
397 397 force_defaults=False
398 398 )
399 399 return Response(html)
400 400
401 401 try:
402 402 settings = [
403 403 ('show_public_icon', 'rhodecode_show_public_icon', 'bool'),
404 404 ('show_private_icon', 'rhodecode_show_private_icon', 'bool'),
405 405 ('stylify_metatags', 'rhodecode_stylify_metatags', 'bool'),
406 406 ('repository_fields', 'rhodecode_repository_fields', 'bool'),
407 407 ('dashboard_items', 'rhodecode_dashboard_items', 'int'),
408 408 ('admin_grid_items', 'rhodecode_admin_grid_items', 'int'),
409 409 ('show_version', 'rhodecode_show_version', 'bool'),
410 410 ('use_gravatar', 'rhodecode_use_gravatar', 'bool'),
411 411 ('markup_renderer', 'rhodecode_markup_renderer', 'unicode'),
412 412 ('gravatar_url', 'rhodecode_gravatar_url', 'unicode'),
413 413 ('clone_uri_tmpl', 'rhodecode_clone_uri_tmpl', 'unicode'),
414 ('clone_uri_ssh_tmpl', 'rhodecode_clone_uri_ssh_tmpl', 'unicode'),
414 415 ('support_url', 'rhodecode_support_url', 'unicode'),
415 416 ('show_revision_number', 'rhodecode_show_revision_number', 'bool'),
416 417 ('show_sha_length', 'rhodecode_show_sha_length', 'int'),
417 418 ]
418 419 for setting, form_key, type_ in settings:
419 420 sett = SettingsModel().create_or_update_setting(
420 421 setting, form_result[form_key], type_)
421 422 Session().add(sett)
422 423
423 424 Session().commit()
424 425 SettingsModel().invalidate_settings_cache()
425 426 h.flash(_('Updated visualisation settings'), category='success')
426 427 except Exception:
427 428 log.exception("Exception updating visualization settings")
428 429 h.flash(_('Error occurred during updating '
429 430 'visualisation settings'),
430 431 category='error')
431 432
432 433 raise HTTPFound(h.route_path('admin_settings_visual'))
433 434
434 435 @LoginRequired()
435 436 @HasPermissionAllDecorator('hg.admin')
436 437 @view_config(
437 438 route_name='admin_settings_issuetracker', request_method='GET',
438 439 renderer='rhodecode:templates/admin/settings/settings.mako')
439 440 def settings_issuetracker(self):
440 441 c = self.load_default_context()
441 442 c.active = 'issuetracker'
442 443 defaults = SettingsModel().get_all_settings()
443 444
444 445 entry_key = 'rhodecode_issuetracker_pat_'
445 446
446 447 c.issuetracker_entries = {}
447 448 for k, v in defaults.items():
448 449 if k.startswith(entry_key):
449 450 uid = k[len(entry_key):]
450 451 c.issuetracker_entries[uid] = None
451 452
452 453 for uid in c.issuetracker_entries:
453 454 c.issuetracker_entries[uid] = AttributeDict({
454 455 'pat': defaults.get('rhodecode_issuetracker_pat_' + uid),
455 456 'url': defaults.get('rhodecode_issuetracker_url_' + uid),
456 457 'pref': defaults.get('rhodecode_issuetracker_pref_' + uid),
457 458 'desc': defaults.get('rhodecode_issuetracker_desc_' + uid),
458 459 })
459 460
460 461 return self._get_template_context(c)
461 462
462 463 @LoginRequired()
463 464 @HasPermissionAllDecorator('hg.admin')
464 465 @CSRFRequired()
465 466 @view_config(
466 467 route_name='admin_settings_issuetracker_test', request_method='POST',
467 468 renderer='string', xhr=True)
468 469 def settings_issuetracker_test(self):
469 470 return h.urlify_commit_message(
470 471 self.request.POST.get('test_text', ''),
471 472 'repo_group/test_repo1')
472 473
473 474 @LoginRequired()
474 475 @HasPermissionAllDecorator('hg.admin')
475 476 @CSRFRequired()
476 477 @view_config(
477 478 route_name='admin_settings_issuetracker_update', request_method='POST',
478 479 renderer='rhodecode:templates/admin/settings/settings.mako')
479 480 def settings_issuetracker_update(self):
480 481 _ = self.request.translate
481 482 self.load_default_context()
482 483 settings_model = IssueTrackerSettingsModel()
483 484
484 485 try:
485 486 form = IssueTrackerPatternsForm(self.request.translate)()
486 487 data = form.to_python(self.request.POST)
487 488 except formencode.Invalid as errors:
488 489 log.exception('Failed to add new pattern')
489 490 error = errors
490 491 h.flash(_('Invalid issue tracker pattern: {}'.format(error)),
491 492 category='error')
492 493 raise HTTPFound(h.route_path('admin_settings_issuetracker'))
493 494
494 495 if data:
495 496 for uid in data.get('delete_patterns', []):
496 497 settings_model.delete_entries(uid)
497 498
498 499 for pattern in data.get('patterns', []):
499 500 for setting, value, type_ in pattern:
500 501 sett = settings_model.create_or_update_setting(
501 502 setting, value, type_)
502 503 Session().add(sett)
503 504
504 505 Session().commit()
505 506
506 507 SettingsModel().invalidate_settings_cache()
507 508 h.flash(_('Updated issue tracker entries'), category='success')
508 509 raise HTTPFound(h.route_path('admin_settings_issuetracker'))
509 510
510 511 @LoginRequired()
511 512 @HasPermissionAllDecorator('hg.admin')
512 513 @CSRFRequired()
513 514 @view_config(
514 515 route_name='admin_settings_issuetracker_delete', request_method='POST',
515 516 renderer='rhodecode:templates/admin/settings/settings.mako')
516 517 def settings_issuetracker_delete(self):
517 518 _ = self.request.translate
518 519 self.load_default_context()
519 520 uid = self.request.POST.get('uid')
520 521 try:
521 522 IssueTrackerSettingsModel().delete_entries(uid)
522 523 except Exception:
523 524 log.exception('Failed to delete issue tracker setting %s', uid)
524 525 raise HTTPNotFound()
525 526 h.flash(_('Removed issue tracker entry'), category='success')
526 527 raise HTTPFound(h.route_path('admin_settings_issuetracker'))
527 528
528 529 @LoginRequired()
529 530 @HasPermissionAllDecorator('hg.admin')
530 531 @view_config(
531 532 route_name='admin_settings_email', request_method='GET',
532 533 renderer='rhodecode:templates/admin/settings/settings.mako')
533 534 def settings_email(self):
534 535 c = self.load_default_context()
535 536 c.active = 'email'
536 537 c.rhodecode_ini = rhodecode.CONFIG
537 538
538 539 data = render('rhodecode:templates/admin/settings/settings.mako',
539 540 self._get_template_context(c), self.request)
540 541 html = formencode.htmlfill.render(
541 542 data,
542 543 defaults=self._form_defaults(),
543 544 encoding="UTF-8",
544 545 force_defaults=False
545 546 )
546 547 return Response(html)
547 548
548 549 @LoginRequired()
549 550 @HasPermissionAllDecorator('hg.admin')
550 551 @CSRFRequired()
551 552 @view_config(
552 553 route_name='admin_settings_email_update', request_method='POST',
553 554 renderer='rhodecode:templates/admin/settings/settings.mako')
554 555 def settings_email_update(self):
555 556 _ = self.request.translate
556 557 c = self.load_default_context()
557 558 c.active = 'email'
558 559
559 560 test_email = self.request.POST.get('test_email')
560 561
561 562 if not test_email:
562 563 h.flash(_('Please enter email address'), category='error')
563 564 raise HTTPFound(h.route_path('admin_settings_email'))
564 565
565 566 email_kwargs = {
566 567 'date': datetime.datetime.now(),
567 568 'user': c.rhodecode_user,
568 569 'rhodecode_version': c.rhodecode_version
569 570 }
570 571
571 572 (subject, headers, email_body,
572 573 email_body_plaintext) = EmailNotificationModel().render_email(
573 574 EmailNotificationModel.TYPE_EMAIL_TEST, **email_kwargs)
574 575
575 576 recipients = [test_email] if test_email else None
576 577
577 578 run_task(tasks.send_email, recipients, subject,
578 579 email_body_plaintext, email_body)
579 580
580 581 h.flash(_('Send email task created'), category='success')
581 582 raise HTTPFound(h.route_path('admin_settings_email'))
582 583
583 584 @LoginRequired()
584 585 @HasPermissionAllDecorator('hg.admin')
585 586 @view_config(
586 587 route_name='admin_settings_hooks', request_method='GET',
587 588 renderer='rhodecode:templates/admin/settings/settings.mako')
588 589 def settings_hooks(self):
589 590 c = self.load_default_context()
590 591 c.active = 'hooks'
591 592
592 593 model = SettingsModel()
593 594 c.hooks = model.get_builtin_hooks()
594 595 c.custom_hooks = model.get_custom_hooks()
595 596
596 597 data = render('rhodecode:templates/admin/settings/settings.mako',
597 598 self._get_template_context(c), self.request)
598 599 html = formencode.htmlfill.render(
599 600 data,
600 601 defaults=self._form_defaults(),
601 602 encoding="UTF-8",
602 603 force_defaults=False
603 604 )
604 605 return Response(html)
605 606
606 607 @LoginRequired()
607 608 @HasPermissionAllDecorator('hg.admin')
608 609 @CSRFRequired()
609 610 @view_config(
610 611 route_name='admin_settings_hooks_update', request_method='POST',
611 612 renderer='rhodecode:templates/admin/settings/settings.mako')
612 613 @view_config(
613 614 route_name='admin_settings_hooks_delete', request_method='POST',
614 615 renderer='rhodecode:templates/admin/settings/settings.mako')
615 616 def settings_hooks_update(self):
616 617 _ = self.request.translate
617 618 c = self.load_default_context()
618 619 c.active = 'hooks'
619 620 if c.visual.allow_custom_hooks_settings:
620 621 ui_key = self.request.POST.get('new_hook_ui_key')
621 622 ui_value = self.request.POST.get('new_hook_ui_value')
622 623
623 624 hook_id = self.request.POST.get('hook_id')
624 625 new_hook = False
625 626
626 627 model = SettingsModel()
627 628 try:
628 629 if ui_value and ui_key:
629 630 model.create_or_update_hook(ui_key, ui_value)
630 631 h.flash(_('Added new hook'), category='success')
631 632 new_hook = True
632 633 elif hook_id:
633 634 RhodeCodeUi.delete(hook_id)
634 635 Session().commit()
635 636
636 637 # check for edits
637 638 update = False
638 639 _d = self.request.POST.dict_of_lists()
639 640 for k, v in zip(_d.get('hook_ui_key', []),
640 641 _d.get('hook_ui_value_new', [])):
641 642 model.create_or_update_hook(k, v)
642 643 update = True
643 644
644 645 if update and not new_hook:
645 646 h.flash(_('Updated hooks'), category='success')
646 647 Session().commit()
647 648 except Exception:
648 649 log.exception("Exception during hook creation")
649 650 h.flash(_('Error occurred during hook creation'),
650 651 category='error')
651 652
652 653 raise HTTPFound(h.route_path('admin_settings_hooks'))
653 654
654 655 @LoginRequired()
655 656 @HasPermissionAllDecorator('hg.admin')
656 657 @view_config(
657 658 route_name='admin_settings_search', request_method='GET',
658 659 renderer='rhodecode:templates/admin/settings/settings.mako')
659 660 def settings_search(self):
660 661 c = self.load_default_context()
661 662 c.active = 'search'
662 663
663 664 searcher = searcher_from_config(self.request.registry.settings)
664 665 c.statistics = searcher.statistics(self.request.translate)
665 666
666 667 return self._get_template_context(c)
667 668
668 669 @LoginRequired()
669 670 @HasPermissionAllDecorator('hg.admin')
670 671 @view_config(
671 672 route_name='admin_settings_labs', request_method='GET',
672 673 renderer='rhodecode:templates/admin/settings/settings.mako')
673 674 def settings_labs(self):
674 675 c = self.load_default_context()
675 676 if not c.labs_active:
676 677 raise HTTPFound(h.route_path('admin_settings'))
677 678
678 679 c.active = 'labs'
679 680 c.lab_settings = _LAB_SETTINGS
680 681
681 682 data = render('rhodecode:templates/admin/settings/settings.mako',
682 683 self._get_template_context(c), self.request)
683 684 html = formencode.htmlfill.render(
684 685 data,
685 686 defaults=self._form_defaults(),
686 687 encoding="UTF-8",
687 688 force_defaults=False
688 689 )
689 690 return Response(html)
690 691
691 692 @LoginRequired()
692 693 @HasPermissionAllDecorator('hg.admin')
693 694 @CSRFRequired()
694 695 @view_config(
695 696 route_name='admin_settings_labs_update', request_method='POST',
696 697 renderer='rhodecode:templates/admin/settings/settings.mako')
697 698 def settings_labs_update(self):
698 699 _ = self.request.translate
699 700 c = self.load_default_context()
700 701 c.active = 'labs'
701 702
702 703 application_form = LabsSettingsForm(self.request.translate)()
703 704 try:
704 705 form_result = application_form.to_python(dict(self.request.POST))
705 706 except formencode.Invalid as errors:
706 707 h.flash(
707 708 _('Some form inputs contain invalid data.'),
708 709 category='error')
709 710 data = render('rhodecode:templates/admin/settings/settings.mako',
710 711 self._get_template_context(c), self.request)
711 712 html = formencode.htmlfill.render(
712 713 data,
713 714 defaults=errors.value,
714 715 errors=errors.error_dict or {},
715 716 prefix_error=False,
716 717 encoding="UTF-8",
717 718 force_defaults=False
718 719 )
719 720 return Response(html)
720 721
721 722 try:
722 723 session = Session()
723 724 for setting in _LAB_SETTINGS:
724 725 setting_name = setting.key[len('rhodecode_'):]
725 726 sett = SettingsModel().create_or_update_setting(
726 727 setting_name, form_result[setting.key], setting.type)
727 728 session.add(sett)
728 729
729 730 except Exception:
730 731 log.exception('Exception while updating lab settings')
731 732 h.flash(_('Error occurred during updating labs settings'),
732 733 category='error')
733 734 else:
734 735 Session().commit()
735 736 SettingsModel().invalidate_settings_cache()
736 737 h.flash(_('Updated Labs settings'), category='success')
737 738 raise HTTPFound(h.route_path('admin_settings_labs'))
738 739
739 740 data = render('rhodecode:templates/admin/settings/settings.mako',
740 741 self._get_template_context(c), self.request)
741 742 html = formencode.htmlfill.render(
742 743 data,
743 744 defaults=self._form_defaults(),
744 745 encoding="UTF-8",
745 746 force_defaults=False
746 747 )
747 748 return Response(html)
748 749
749 750
750 751 # :param key: name of the setting including the 'rhodecode_' prefix
751 752 # :param type: the RhodeCodeSetting type to use.
752 753 # :param group: the i18ned group in which we should dispaly this setting
753 754 # :param label: the i18ned label we should display for this setting
754 755 # :param help: the i18ned help we should dispaly for this setting
755 756 LabSetting = collections.namedtuple(
756 757 'LabSetting', ('key', 'type', 'group', 'label', 'help'))
757 758
758 759
759 760 # This list has to be kept in sync with the form
760 761 # rhodecode.model.forms.LabsSettingsForm.
761 762 _LAB_SETTINGS = [
762 763
763 764 ]
@@ -1,371 +1,375 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import logging
22 22 import string
23 23
24 24 from pyramid.view import view_config
25 25 from beaker.cache import cache_region
26 26
27 27 from rhodecode.controllers import utils
28 28 from rhodecode.apps._base import RepoAppView
29 29 from rhodecode.config.conf import (LANGUAGES_EXTENSIONS_MAP)
30 30 from rhodecode.lib import caches, helpers as h
31 31 from rhodecode.lib.helpers import RepoPage
32 32 from rhodecode.lib.utils2 import safe_str, safe_int
33 33 from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
34 34 from rhodecode.lib.markup_renderer import MarkupRenderer, relative_links
35 35 from rhodecode.lib.ext_json import json
36 36 from rhodecode.lib.vcs.backends.base import EmptyCommit
37 37 from rhodecode.lib.vcs.exceptions import CommitError, EmptyRepositoryError, \
38 38 CommitDoesNotExistError
39 39 from rhodecode.model.db import Statistics, CacheKey, User
40 40 from rhodecode.model.meta import Session
41 41 from rhodecode.model.repo import ReadmeFinder
42 42 from rhodecode.model.scm import ScmModel
43 43
44 44 log = logging.getLogger(__name__)
45 45
46 46
47 47 class RepoSummaryView(RepoAppView):
48 48
49 49 def load_default_context(self):
50 50 c = self._get_local_tmpl_context(include_app_defaults=True)
51 51
52 52 c.rhodecode_repo = None
53 53 if not c.repository_requirements_missing:
54 54 c.rhodecode_repo = self.rhodecode_vcs_repo
55 55
56 56
57 57 return c
58 58
59 59 def _get_readme_data(self, db_repo, default_renderer):
60 60 repo_name = db_repo.repo_name
61 61 log.debug('Looking for README file')
62 62
63 63 @cache_region('long_term')
64 64 def _generate_readme(cache_key):
65 65 readme_data = None
66 66 readme_node = None
67 67 readme_filename = None
68 68 commit = self._get_landing_commit_or_none(db_repo)
69 69 if commit:
70 70 log.debug("Searching for a README file.")
71 71 readme_node = ReadmeFinder(default_renderer).search(commit)
72 72 if readme_node:
73 73 relative_urls = {
74 74 'raw': h.route_path(
75 75 'repo_file_raw', repo_name=repo_name,
76 76 commit_id=commit.raw_id, f_path=readme_node.path),
77 77 'standard': h.route_path(
78 78 'repo_files', repo_name=repo_name,
79 79 commit_id=commit.raw_id, f_path=readme_node.path),
80 80 }
81 81 readme_data = self._render_readme_or_none(
82 82 commit, readme_node, relative_urls)
83 83 readme_filename = readme_node.path
84 84 return readme_data, readme_filename
85 85
86 86 invalidator_context = CacheKey.repo_context_cache(
87 87 _generate_readme, repo_name, CacheKey.CACHE_TYPE_README)
88 88
89 89 with invalidator_context as context:
90 90 context.invalidate()
91 91 computed = context.compute()
92 92
93 93 return computed
94 94
95 95 def _get_landing_commit_or_none(self, db_repo):
96 96 log.debug("Getting the landing commit.")
97 97 try:
98 98 commit = db_repo.get_landing_commit()
99 99 if not isinstance(commit, EmptyCommit):
100 100 return commit
101 101 else:
102 102 log.debug("Repository is empty, no README to render.")
103 103 except CommitError:
104 104 log.exception(
105 105 "Problem getting commit when trying to render the README.")
106 106
107 107 def _render_readme_or_none(self, commit, readme_node, relative_urls):
108 108 log.debug(
109 109 'Found README file `%s` rendering...', readme_node.path)
110 110 renderer = MarkupRenderer()
111 111 try:
112 112 html_source = renderer.render(
113 113 readme_node.content, filename=readme_node.path)
114 114 if relative_urls:
115 115 return relative_links(html_source, relative_urls)
116 116 return html_source
117 117 except Exception:
118 118 log.exception(
119 119 "Exception while trying to render the README")
120 120
121 121 def _load_commits_context(self, c):
122 122 p = safe_int(self.request.GET.get('page'), 1)
123 123 size = safe_int(self.request.GET.get('size'), 10)
124 124
125 125 def url_generator(**kw):
126 126 query_params = {
127 127 'size': size
128 128 }
129 129 query_params.update(kw)
130 130 return h.route_path(
131 131 'repo_summary_commits',
132 132 repo_name=c.rhodecode_db_repo.repo_name, _query=query_params)
133 133
134 134 pre_load = ['author', 'branch', 'date', 'message']
135 135 try:
136 136 collection = self.rhodecode_vcs_repo.get_commits(pre_load=pre_load)
137 137 except EmptyRepositoryError:
138 138 collection = self.rhodecode_vcs_repo
139 139
140 140 c.repo_commits = RepoPage(
141 141 collection, page=p, items_per_page=size, url=url_generator)
142 142 page_ids = [x.raw_id for x in c.repo_commits]
143 143 c.comments = self.db_repo.get_comments(page_ids)
144 144 c.statuses = self.db_repo.statuses(page_ids)
145 145
146 146 @LoginRequired()
147 147 @HasRepoPermissionAnyDecorator(
148 148 'repository.read', 'repository.write', 'repository.admin')
149 149 @view_config(
150 150 route_name='repo_summary_commits', request_method='GET',
151 151 renderer='rhodecode:templates/summary/summary_commits.mako')
152 152 def summary_commits(self):
153 153 c = self.load_default_context()
154 154 self._load_commits_context(c)
155 155 return self._get_template_context(c)
156 156
157 157 @LoginRequired()
158 158 @HasRepoPermissionAnyDecorator(
159 159 'repository.read', 'repository.write', 'repository.admin')
160 160 @view_config(
161 161 route_name='repo_summary', request_method='GET',
162 162 renderer='rhodecode:templates/summary/summary.mako')
163 163 @view_config(
164 164 route_name='repo_summary_slash', request_method='GET',
165 165 renderer='rhodecode:templates/summary/summary.mako')
166 166 @view_config(
167 167 route_name='repo_summary_explicit', request_method='GET',
168 168 renderer='rhodecode:templates/summary/summary.mako')
169 169 def summary(self):
170 170 c = self.load_default_context()
171 171
172 172 # Prepare the clone URL
173 173 username = ''
174 174 if self._rhodecode_user.username != User.DEFAULT_USER:
175 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 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 182 '{repo}', '_{repoid}')
181 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 185 '_{repoid}', '{repo}')
184 186
185 187 c.clone_repo_url = self.db_repo.clone_url(
186 188 user=username, uri_tmpl=_def_clone_uri)
187 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 194 # If enabled, get statistics data
191 195
192 196 c.show_stats = bool(self.db_repo.enable_statistics)
193 197
194 198 stats = Session().query(Statistics) \
195 199 .filter(Statistics.repository == self.db_repo) \
196 200 .scalar()
197 201
198 202 c.stats_percentage = 0
199 203
200 204 if stats and stats.languages:
201 205 c.no_data = False is self.db_repo.enable_statistics
202 206 lang_stats_d = json.loads(stats.languages)
203 207
204 208 # Sort first by decreasing count and second by the file extension,
205 209 # so we have a consistent output.
206 210 lang_stats_items = sorted(lang_stats_d.iteritems(),
207 211 key=lambda k: (-k[1], k[0]))[:10]
208 212 lang_stats = [(x, {"count": y,
209 213 "desc": LANGUAGES_EXTENSIONS_MAP.get(x)})
210 214 for x, y in lang_stats_items]
211 215
212 216 c.trending_languages = json.dumps(lang_stats)
213 217 else:
214 218 c.no_data = True
215 219 c.trending_languages = json.dumps({})
216 220
217 221 scm_model = ScmModel()
218 222 c.enable_downloads = self.db_repo.enable_downloads
219 223 c.repository_followers = scm_model.get_followers(self.db_repo)
220 224 c.repository_forks = scm_model.get_forks(self.db_repo)
221 225 c.repository_is_user_following = scm_model.is_following_repo(
222 226 self.db_repo_name, self._rhodecode_user.user_id)
223 227
224 228 # first interaction with the VCS instance after here...
225 229 if c.repository_requirements_missing:
226 230 self.request.override_renderer = \
227 231 'rhodecode:templates/summary/missing_requirements.mako'
228 232 return self._get_template_context(c)
229 233
230 234 c.readme_data, c.readme_file = \
231 235 self._get_readme_data(self.db_repo, c.visual.default_renderer)
232 236
233 237 # loads the summary commits template context
234 238 self._load_commits_context(c)
235 239
236 240 return self._get_template_context(c)
237 241
238 242 def get_request_commit_id(self):
239 243 return self.request.matchdict['commit_id']
240 244
241 245 @LoginRequired()
242 246 @HasRepoPermissionAnyDecorator(
243 247 'repository.read', 'repository.write', 'repository.admin')
244 248 @view_config(
245 249 route_name='repo_stats', request_method='GET',
246 250 renderer='json_ext')
247 251 def repo_stats(self):
248 252 commit_id = self.get_request_commit_id()
249 253
250 254 _namespace = caches.get_repo_namespace_key(
251 255 caches.SUMMARY_STATS, self.db_repo_name)
252 256 show_stats = bool(self.db_repo.enable_statistics)
253 257 cache_manager = caches.get_cache_manager(
254 258 'repo_cache_long', _namespace)
255 259 _cache_key = caches.compute_key_from_params(
256 260 self.db_repo_name, commit_id, show_stats)
257 261
258 262 def compute_stats():
259 263 code_stats = {}
260 264 size = 0
261 265 try:
262 266 scm_instance = self.db_repo.scm_instance()
263 267 commit = scm_instance.get_commit(commit_id)
264 268
265 269 for node in commit.get_filenodes_generator():
266 270 size += node.size
267 271 if not show_stats:
268 272 continue
269 273 ext = string.lower(node.extension)
270 274 ext_info = LANGUAGES_EXTENSIONS_MAP.get(ext)
271 275 if ext_info:
272 276 if ext in code_stats:
273 277 code_stats[ext]['count'] += 1
274 278 else:
275 279 code_stats[ext] = {"count": 1, "desc": ext_info}
276 280 except (EmptyRepositoryError, CommitDoesNotExistError):
277 281 pass
278 282 return {'size': h.format_byte_size_binary(size),
279 283 'code_stats': code_stats}
280 284
281 285 stats = cache_manager.get(_cache_key, createfunc=compute_stats)
282 286 return stats
283 287
284 288 @LoginRequired()
285 289 @HasRepoPermissionAnyDecorator(
286 290 'repository.read', 'repository.write', 'repository.admin')
287 291 @view_config(
288 292 route_name='repo_refs_data', request_method='GET',
289 293 renderer='json_ext')
290 294 def repo_refs_data(self):
291 295 _ = self.request.translate
292 296 self.load_default_context()
293 297
294 298 repo = self.rhodecode_vcs_repo
295 299 refs_to_create = [
296 300 (_("Branch"), repo.branches, 'branch'),
297 301 (_("Tag"), repo.tags, 'tag'),
298 302 (_("Bookmark"), repo.bookmarks, 'book'),
299 303 ]
300 304 res = self._create_reference_data(
301 305 repo, self.db_repo_name, refs_to_create)
302 306 data = {
303 307 'more': False,
304 308 'results': res
305 309 }
306 310 return data
307 311
308 312 @LoginRequired()
309 313 @HasRepoPermissionAnyDecorator(
310 314 'repository.read', 'repository.write', 'repository.admin')
311 315 @view_config(
312 316 route_name='repo_refs_changelog_data', request_method='GET',
313 317 renderer='json_ext')
314 318 def repo_refs_changelog_data(self):
315 319 _ = self.request.translate
316 320 self.load_default_context()
317 321
318 322 repo = self.rhodecode_vcs_repo
319 323
320 324 refs_to_create = [
321 325 (_("Branches"), repo.branches, 'branch'),
322 326 (_("Closed branches"), repo.branches_closed, 'branch_closed'),
323 327 # TODO: enable when vcs can handle bookmarks filters
324 328 # (_("Bookmarks"), repo.bookmarks, "book"),
325 329 ]
326 330 res = self._create_reference_data(
327 331 repo, self.db_repo_name, refs_to_create)
328 332 data = {
329 333 'more': False,
330 334 'results': res
331 335 }
332 336 return data
333 337
334 338 def _create_reference_data(self, repo, full_repo_name, refs_to_create):
335 339 format_ref_id = utils.get_format_ref_id(repo)
336 340
337 341 result = []
338 342 for title, refs, ref_type in refs_to_create:
339 343 if refs:
340 344 result.append({
341 345 'text': title,
342 346 'children': self._create_reference_items(
343 347 repo, full_repo_name, refs, ref_type,
344 348 format_ref_id),
345 349 })
346 350 return result
347 351
348 352 def _create_reference_items(self, repo, full_repo_name, refs, ref_type,
349 353 format_ref_id):
350 354 result = []
351 355 is_svn = h.is_svn(repo)
352 356 for ref_name, raw_id in refs.iteritems():
353 357 files_url = self._create_files_url(
354 358 repo, full_repo_name, ref_name, raw_id, is_svn)
355 359 result.append({
356 360 'text': ref_name,
357 361 'id': format_ref_id(ref_name, raw_id),
358 362 'raw_id': raw_id,
359 363 'type': ref_type,
360 364 'files_url': files_url,
361 365 })
362 366 return result
363 367
364 368 def _create_files_url(self, repo, full_repo_name, ref_name, raw_id, is_svn):
365 369 use_commit_id = '/' in ref_name or is_svn
366 370 return h.route_path(
367 371 'repo_files',
368 372 repo_name=full_repo_name,
369 373 f_path=ref_name if is_svn else '',
370 374 commit_id=raw_id if use_commit_id else ref_name,
371 375 _query=dict(at=ref_name))
@@ -1,542 +1,543 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 The base Controller API
23 23 Provides the BaseController class for subclassing. And usage in different
24 24 controllers
25 25 """
26 26
27 27 import logging
28 28 import socket
29 29
30 30 import markupsafe
31 31 import ipaddress
32 32
33 33 from paste.auth.basic import AuthBasicAuthenticator
34 34 from paste.httpexceptions import HTTPUnauthorized, HTTPForbidden, get_exception
35 35 from paste.httpheaders import WWW_AUTHENTICATE, AUTHORIZATION
36 36
37 37 import rhodecode
38 38 from rhodecode.authentication.base import VCS_TYPE
39 39 from rhodecode.lib import auth, utils2
40 40 from rhodecode.lib import helpers as h
41 41 from rhodecode.lib.auth import AuthUser, CookieStoreWrapper
42 42 from rhodecode.lib.exceptions import UserCreationError
43 43 from rhodecode.lib.utils import (password_changed, get_enabled_hook_classes)
44 44 from rhodecode.lib.utils2 import (
45 45 str2bool, safe_unicode, AttributeDict, safe_int, md5, aslist, safe_str)
46 46 from rhodecode.model.db import Repository, User, ChangesetComment
47 47 from rhodecode.model.notification import NotificationModel
48 48 from rhodecode.model.settings import VcsSettingsModel, SettingsModel
49 49
50 50 log = logging.getLogger(__name__)
51 51
52 52
53 53 def _filter_proxy(ip):
54 54 """
55 55 Passed in IP addresses in HEADERS can be in a special format of multiple
56 56 ips. Those comma separated IPs are passed from various proxies in the
57 57 chain of request processing. The left-most being the original client.
58 58 We only care about the first IP which came from the org. client.
59 59
60 60 :param ip: ip string from headers
61 61 """
62 62 if ',' in ip:
63 63 _ips = ip.split(',')
64 64 _first_ip = _ips[0].strip()
65 65 log.debug('Got multiple IPs %s, using %s', ','.join(_ips), _first_ip)
66 66 return _first_ip
67 67 return ip
68 68
69 69
70 70 def _filter_port(ip):
71 71 """
72 72 Removes a port from ip, there are 4 main cases to handle here.
73 73 - ipv4 eg. 127.0.0.1
74 74 - ipv6 eg. ::1
75 75 - ipv4+port eg. 127.0.0.1:8080
76 76 - ipv6+port eg. [::1]:8080
77 77
78 78 :param ip:
79 79 """
80 80 def is_ipv6(ip_addr):
81 81 if hasattr(socket, 'inet_pton'):
82 82 try:
83 83 socket.inet_pton(socket.AF_INET6, ip_addr)
84 84 except socket.error:
85 85 return False
86 86 else:
87 87 # fallback to ipaddress
88 88 try:
89 89 ipaddress.IPv6Address(safe_unicode(ip_addr))
90 90 except Exception:
91 91 return False
92 92 return True
93 93
94 94 if ':' not in ip: # must be ipv4 pure ip
95 95 return ip
96 96
97 97 if '[' in ip and ']' in ip: # ipv6 with port
98 98 return ip.split(']')[0][1:].lower()
99 99
100 100 # must be ipv6 or ipv4 with port
101 101 if is_ipv6(ip):
102 102 return ip
103 103 else:
104 104 ip, _port = ip.split(':')[:2] # means ipv4+port
105 105 return ip
106 106
107 107
108 108 def get_ip_addr(environ):
109 109 proxy_key = 'HTTP_X_REAL_IP'
110 110 proxy_key2 = 'HTTP_X_FORWARDED_FOR'
111 111 def_key = 'REMOTE_ADDR'
112 112 _filters = lambda x: _filter_port(_filter_proxy(x))
113 113
114 114 ip = environ.get(proxy_key)
115 115 if ip:
116 116 return _filters(ip)
117 117
118 118 ip = environ.get(proxy_key2)
119 119 if ip:
120 120 return _filters(ip)
121 121
122 122 ip = environ.get(def_key, '0.0.0.0')
123 123 return _filters(ip)
124 124
125 125
126 126 def get_server_ip_addr(environ, log_errors=True):
127 127 hostname = environ.get('SERVER_NAME')
128 128 try:
129 129 return socket.gethostbyname(hostname)
130 130 except Exception as e:
131 131 if log_errors:
132 132 # in some cases this lookup is not possible, and we don't want to
133 133 # make it an exception in logs
134 134 log.exception('Could not retrieve server ip address: %s', e)
135 135 return hostname
136 136
137 137
138 138 def get_server_port(environ):
139 139 return environ.get('SERVER_PORT')
140 140
141 141
142 142 def get_access_path(environ):
143 143 path = environ.get('PATH_INFO')
144 144 org_req = environ.get('pylons.original_request')
145 145 if org_req:
146 146 path = org_req.environ.get('PATH_INFO')
147 147 return path
148 148
149 149
150 150 def get_user_agent(environ):
151 151 return environ.get('HTTP_USER_AGENT')
152 152
153 153
154 154 def vcs_operation_context(
155 155 environ, repo_name, username, action, scm, check_locking=True,
156 156 is_shadow_repo=False):
157 157 """
158 158 Generate the context for a vcs operation, e.g. push or pull.
159 159
160 160 This context is passed over the layers so that hooks triggered by the
161 161 vcs operation know details like the user, the user's IP address etc.
162 162
163 163 :param check_locking: Allows to switch of the computation of the locking
164 164 data. This serves mainly the need of the simplevcs middleware to be
165 165 able to disable this for certain operations.
166 166
167 167 """
168 168 # Tri-state value: False: unlock, None: nothing, True: lock
169 169 make_lock = None
170 170 locked_by = [None, None, None]
171 171 is_anonymous = username == User.DEFAULT_USER
172 172 user = User.get_by_username(username)
173 173 if not is_anonymous and check_locking:
174 174 log.debug('Checking locking on repository "%s"', repo_name)
175 175 repo = Repository.get_by_repo_name(repo_name)
176 176 make_lock, __, locked_by = repo.get_locking_state(
177 177 action, user.user_id)
178 178 user_id = user.user_id
179 179 settings_model = VcsSettingsModel(repo=repo_name)
180 180 ui_settings = settings_model.get_ui_settings()
181 181
182 182 extras = {
183 183 'ip': get_ip_addr(environ),
184 184 'username': username,
185 185 'user_id': user_id,
186 186 'action': action,
187 187 'repository': repo_name,
188 188 'scm': scm,
189 189 'config': rhodecode.CONFIG['__file__'],
190 190 'make_lock': make_lock,
191 191 'locked_by': locked_by,
192 192 'server_url': utils2.get_server_url(environ),
193 193 'user_agent': get_user_agent(environ),
194 194 'hooks': get_enabled_hook_classes(ui_settings),
195 195 'is_shadow_repo': is_shadow_repo,
196 196 }
197 197 return extras
198 198
199 199
200 200 class BasicAuth(AuthBasicAuthenticator):
201 201
202 202 def __init__(self, realm, authfunc, registry, auth_http_code=None,
203 203 initial_call_detection=False, acl_repo_name=None):
204 204 self.realm = realm
205 205 self.initial_call = initial_call_detection
206 206 self.authfunc = authfunc
207 207 self.registry = registry
208 208 self.acl_repo_name = acl_repo_name
209 209 self._rc_auth_http_code = auth_http_code
210 210
211 211 def _get_response_from_code(self, http_code):
212 212 try:
213 213 return get_exception(safe_int(http_code))
214 214 except Exception:
215 215 log.exception('Failed to fetch response for code %s' % http_code)
216 216 return HTTPForbidden
217 217
218 218 def get_rc_realm(self):
219 219 return safe_str(self.registry.rhodecode_settings.get('rhodecode_realm'))
220 220
221 221 def build_authentication(self):
222 222 head = WWW_AUTHENTICATE.tuples('Basic realm="%s"' % self.realm)
223 223 if self._rc_auth_http_code and not self.initial_call:
224 224 # return alternative HTTP code if alternative http return code
225 225 # is specified in RhodeCode config, but ONLY if it's not the
226 226 # FIRST call
227 227 custom_response_klass = self._get_response_from_code(
228 228 self._rc_auth_http_code)
229 229 return custom_response_klass(headers=head)
230 230 return HTTPUnauthorized(headers=head)
231 231
232 232 def authenticate(self, environ):
233 233 authorization = AUTHORIZATION(environ)
234 234 if not authorization:
235 235 return self.build_authentication()
236 236 (authmeth, auth) = authorization.split(' ', 1)
237 237 if 'basic' != authmeth.lower():
238 238 return self.build_authentication()
239 239 auth = auth.strip().decode('base64')
240 240 _parts = auth.split(':', 1)
241 241 if len(_parts) == 2:
242 242 username, password = _parts
243 243 auth_data = self.authfunc(
244 244 username, password, environ, VCS_TYPE,
245 245 registry=self.registry, acl_repo_name=self.acl_repo_name)
246 246 if auth_data:
247 247 return {'username': username, 'auth_data': auth_data}
248 248 if username and password:
249 249 # we mark that we actually executed authentication once, at
250 250 # that point we can use the alternative auth code
251 251 self.initial_call = False
252 252
253 253 return self.build_authentication()
254 254
255 255 __call__ = authenticate
256 256
257 257
258 258 def calculate_version_hash(config):
259 259 return md5(
260 260 config.get('beaker.session.secret', '') +
261 261 rhodecode.__version__)[:8]
262 262
263 263
264 264 def get_current_lang(request):
265 265 # NOTE(marcink): remove after pyramid move
266 266 try:
267 267 return translation.get_lang()[0]
268 268 except:
269 269 pass
270 270
271 271 return getattr(request, '_LOCALE_', request.locale_name)
272 272
273 273
274 274 def attach_context_attributes(context, request, user_id):
275 275 """
276 276 Attach variables into template context called `c`.
277 277 """
278 278 config = request.registry.settings
279 279
280 280
281 281 rc_config = SettingsModel().get_all_settings(cache=True)
282 282
283 283 context.rhodecode_version = rhodecode.__version__
284 284 context.rhodecode_edition = config.get('rhodecode.edition')
285 285 # unique secret + version does not leak the version but keep consistency
286 286 context.rhodecode_version_hash = calculate_version_hash(config)
287 287
288 288 # Default language set for the incoming request
289 289 context.language = get_current_lang(request)
290 290
291 291 # Visual options
292 292 context.visual = AttributeDict({})
293 293
294 294 # DB stored Visual Items
295 295 context.visual.show_public_icon = str2bool(
296 296 rc_config.get('rhodecode_show_public_icon'))
297 297 context.visual.show_private_icon = str2bool(
298 298 rc_config.get('rhodecode_show_private_icon'))
299 299 context.visual.stylify_metatags = str2bool(
300 300 rc_config.get('rhodecode_stylify_metatags'))
301 301 context.visual.dashboard_items = safe_int(
302 302 rc_config.get('rhodecode_dashboard_items', 100))
303 303 context.visual.admin_grid_items = safe_int(
304 304 rc_config.get('rhodecode_admin_grid_items', 100))
305 305 context.visual.repository_fields = str2bool(
306 306 rc_config.get('rhodecode_repository_fields'))
307 307 context.visual.show_version = str2bool(
308 308 rc_config.get('rhodecode_show_version'))
309 309 context.visual.use_gravatar = str2bool(
310 310 rc_config.get('rhodecode_use_gravatar'))
311 311 context.visual.gravatar_url = rc_config.get('rhodecode_gravatar_url')
312 312 context.visual.default_renderer = rc_config.get(
313 313 'rhodecode_markup_renderer', 'rst')
314 314 context.visual.comment_types = ChangesetComment.COMMENT_TYPES
315 315 context.visual.rhodecode_support_url = \
316 316 rc_config.get('rhodecode_support_url') or h.route_url('rhodecode_support')
317 317
318 318 context.visual.affected_files_cut_off = 60
319 319
320 320 context.pre_code = rc_config.get('rhodecode_pre_code')
321 321 context.post_code = rc_config.get('rhodecode_post_code')
322 322 context.rhodecode_name = rc_config.get('rhodecode_title')
323 323 context.default_encodings = aslist(config.get('default_encoding'), sep=',')
324 324 # if we have specified default_encoding in the request, it has more
325 325 # priority
326 326 if request.GET.get('default_encoding'):
327 327 context.default_encodings.insert(0, request.GET.get('default_encoding'))
328 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 331 # INI stored
331 332 context.labs_active = str2bool(
332 333 config.get('labs_settings_active', 'false'))
333 334 context.visual.allow_repo_location_change = str2bool(
334 335 config.get('allow_repo_location_change', True))
335 336 context.visual.allow_custom_hooks_settings = str2bool(
336 337 config.get('allow_custom_hooks_settings', True))
337 338 context.debug_style = str2bool(config.get('debug_style', False))
338 339
339 340 context.rhodecode_instanceid = config.get('instance_id')
340 341
341 342 context.visual.cut_off_limit_diff = safe_int(
342 343 config.get('cut_off_limit_diff'))
343 344 context.visual.cut_off_limit_file = safe_int(
344 345 config.get('cut_off_limit_file'))
345 346
346 347 # AppEnlight
347 348 context.appenlight_enabled = str2bool(config.get('appenlight', 'false'))
348 349 context.appenlight_api_public_key = config.get(
349 350 'appenlight.api_public_key', '')
350 351 context.appenlight_server_url = config.get('appenlight.server_url', '')
351 352
352 353 # JS template context
353 354 context.template_context = {
354 355 'repo_name': None,
355 356 'repo_type': None,
356 357 'repo_landing_commit': None,
357 358 'rhodecode_user': {
358 359 'username': None,
359 360 'email': None,
360 361 'notification_status': False
361 362 },
362 363 'visual': {
363 364 'default_renderer': None
364 365 },
365 366 'commit_data': {
366 367 'commit_id': None
367 368 },
368 369 'pull_request_data': {'pull_request_id': None},
369 370 'timeago': {
370 371 'refresh_time': 120 * 1000,
371 372 'cutoff_limit': 1000 * 60 * 60 * 24 * 7
372 373 },
373 374 'pyramid_dispatch': {
374 375
375 376 },
376 377 'extra': {'plugins': {}}
377 378 }
378 379 # END CONFIG VARS
379 380
380 381 diffmode = 'sideside'
381 382 if request.GET.get('diffmode'):
382 383 if request.GET['diffmode'] == 'unified':
383 384 diffmode = 'unified'
384 385 elif request.session.get('diffmode'):
385 386 diffmode = request.session['diffmode']
386 387
387 388 context.diffmode = diffmode
388 389
389 390 if request.session.get('diffmode') != diffmode:
390 391 request.session['diffmode'] = diffmode
391 392
392 393 context.csrf_token = auth.get_csrf_token(session=request.session)
393 394 context.backends = rhodecode.BACKENDS.keys()
394 395 context.backends.sort()
395 396 context.unread_notifications = NotificationModel().get_unread_cnt_for_user(user_id)
396 397
397 398 # web case
398 399 if hasattr(request, 'user'):
399 400 context.auth_user = request.user
400 401 context.rhodecode_user = request.user
401 402
402 403 # api case
403 404 if hasattr(request, 'rpc_user'):
404 405 context.auth_user = request.rpc_user
405 406 context.rhodecode_user = request.rpc_user
406 407
407 408 # attach the whole call context to the request
408 409 request.call_context = context
409 410
410 411
411 412 def get_auth_user(request):
412 413 environ = request.environ
413 414 session = request.session
414 415
415 416 ip_addr = get_ip_addr(environ)
416 417 # make sure that we update permissions each time we call controller
417 418 _auth_token = (request.GET.get('auth_token', '') or
418 419 request.GET.get('api_key', ''))
419 420
420 421 if _auth_token:
421 422 # when using API_KEY we assume user exists, and
422 423 # doesn't need auth based on cookies.
423 424 auth_user = AuthUser(api_key=_auth_token, ip_addr=ip_addr)
424 425 authenticated = False
425 426 else:
426 427 cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
427 428 try:
428 429 auth_user = AuthUser(user_id=cookie_store.get('user_id', None),
429 430 ip_addr=ip_addr)
430 431 except UserCreationError as e:
431 432 h.flash(e, 'error')
432 433 # container auth or other auth functions that create users
433 434 # on the fly can throw this exception signaling that there's
434 435 # issue with user creation, explanation should be provided
435 436 # in Exception itself. We then create a simple blank
436 437 # AuthUser
437 438 auth_user = AuthUser(ip_addr=ip_addr)
438 439
439 440 # in case someone changes a password for user it triggers session
440 441 # flush and forces a re-login
441 442 if password_changed(auth_user, session):
442 443 session.invalidate()
443 444 cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
444 445 auth_user = AuthUser(ip_addr=ip_addr)
445 446
446 447 authenticated = cookie_store.get('is_authenticated')
447 448
448 449 if not auth_user.is_authenticated and auth_user.is_user_object:
449 450 # user is not authenticated and not empty
450 451 auth_user.set_authenticated(authenticated)
451 452
452 453 return auth_user
453 454
454 455
455 456 def h_filter(s):
456 457 """
457 458 Custom filter for Mako templates. Mako by standard uses `markupsafe.escape`
458 459 we wrap this with additional functionality that converts None to empty
459 460 strings
460 461 """
461 462 if s is None:
462 463 return markupsafe.Markup()
463 464 return markupsafe.escape(s)
464 465
465 466
466 467 def add_events_routes(config):
467 468 """
468 469 Adds routing that can be used in events. Because some events are triggered
469 470 outside of pyramid context, we need to bootstrap request with some
470 471 routing registered
471 472 """
472 473
473 474 from rhodecode.apps._base import ADMIN_PREFIX
474 475
475 476 config.add_route(name='home', pattern='/')
476 477
477 478 config.add_route(name='login', pattern=ADMIN_PREFIX + '/login')
478 479 config.add_route(name='logout', pattern=ADMIN_PREFIX + '/logout')
479 480 config.add_route(name='repo_summary', pattern='/{repo_name}')
480 481 config.add_route(name='repo_summary_explicit', pattern='/{repo_name}/summary')
481 482 config.add_route(name='repo_group_home', pattern='/{repo_group_name}')
482 483
483 484 config.add_route(name='pullrequest_show',
484 485 pattern='/{repo_name}/pull-request/{pull_request_id}')
485 486 config.add_route(name='pull_requests_global',
486 487 pattern='/pull-request/{pull_request_id}')
487 488 config.add_route(name='repo_commit',
488 489 pattern='/{repo_name}/changeset/{commit_id}')
489 490
490 491 config.add_route(name='repo_files',
491 492 pattern='/{repo_name}/files/{commit_id}/{f_path}')
492 493
493 494
494 495 def bootstrap_config(request):
495 496 import pyramid.testing
496 497 registry = pyramid.testing.Registry('RcTestRegistry')
497 498
498 499 config = pyramid.testing.setUp(registry=registry, request=request)
499 500
500 501 # allow pyramid lookup in testing
501 502 config.include('pyramid_mako')
502 503 config.include('pyramid_beaker')
503 504 config.include('rhodecode.lib.caches')
504 505
505 506 add_events_routes(config)
506 507
507 508 return config
508 509
509 510
510 511 def bootstrap_request(**kwargs):
511 512 import pyramid.testing
512 513
513 514 class TestRequest(pyramid.testing.DummyRequest):
514 515 application_url = kwargs.pop('application_url', 'http://example.com')
515 516 host = kwargs.pop('host', 'example.com:80')
516 517 domain = kwargs.pop('domain', 'example.com')
517 518
518 519 def translate(self, msg):
519 520 return msg
520 521
521 522 def plularize(self, singular, plural, n):
522 523 return singular
523 524
524 525 def get_partial_renderer(self, tmpl_name):
525 526
526 527 from rhodecode.lib.partial_renderer import get_partial_renderer
527 528 return get_partial_renderer(request=self, tmpl_name=tmpl_name)
528 529
529 530 _call_context = {}
530 531 @property
531 532 def call_context(self):
532 533 return self._call_context
533 534
534 535 class TestDummySession(pyramid.testing.DummySession):
535 536 def save(*arg, **kw):
536 537 pass
537 538
538 539 request = TestRequest(**kwargs)
539 540 request.session = TestDummySession()
540 541
541 542 return request
542 543
@@ -1,980 +1,984 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2011-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21
22 22 """
23 23 Some simple helper functions
24 24 """
25 25
26 26 import collections
27 27 import datetime
28 28 import dateutil.relativedelta
29 29 import hashlib
30 30 import logging
31 31 import re
32 32 import sys
33 33 import time
34 34 import urllib
35 35 import urlobject
36 36 import uuid
37 import getpass
37 38
38 39 import pygments.lexers
39 40 import sqlalchemy
40 41 import sqlalchemy.engine.url
41 42 import sqlalchemy.exc
42 43 import sqlalchemy.sql
43 44 import webob
44 45 import pyramid.threadlocal
45 46
46 47 import rhodecode
47 48 from rhodecode.translation import _, _pluralize
48 49
49 50
50 51 def md5(s):
51 52 return hashlib.md5(s).hexdigest()
52 53
53 54
54 55 def md5_safe(s):
55 56 return md5(safe_str(s))
56 57
57 58
58 59 def __get_lem(extra_mapping=None):
59 60 """
60 61 Get language extension map based on what's inside pygments lexers
61 62 """
62 63 d = collections.defaultdict(lambda: [])
63 64
64 65 def __clean(s):
65 66 s = s.lstrip('*')
66 67 s = s.lstrip('.')
67 68
68 69 if s.find('[') != -1:
69 70 exts = []
70 71 start, stop = s.find('['), s.find(']')
71 72
72 73 for suffix in s[start + 1:stop]:
73 74 exts.append(s[:s.find('[')] + suffix)
74 75 return [e.lower() for e in exts]
75 76 else:
76 77 return [s.lower()]
77 78
78 79 for lx, t in sorted(pygments.lexers.LEXERS.items()):
79 80 m = map(__clean, t[-2])
80 81 if m:
81 82 m = reduce(lambda x, y: x + y, m)
82 83 for ext in m:
83 84 desc = lx.replace('Lexer', '')
84 85 d[ext].append(desc)
85 86
86 87 data = dict(d)
87 88
88 89 extra_mapping = extra_mapping or {}
89 90 if extra_mapping:
90 91 for k, v in extra_mapping.items():
91 92 if k not in data:
92 93 # register new mapping2lexer
93 94 data[k] = [v]
94 95
95 96 return data
96 97
97 98
98 99 def str2bool(_str):
99 100 """
100 101 returns True/False value from given string, it tries to translate the
101 102 string into boolean
102 103
103 104 :param _str: string value to translate into boolean
104 105 :rtype: boolean
105 106 :returns: boolean from given string
106 107 """
107 108 if _str is None:
108 109 return False
109 110 if _str in (True, False):
110 111 return _str
111 112 _str = str(_str).strip().lower()
112 113 return _str in ('t', 'true', 'y', 'yes', 'on', '1')
113 114
114 115
115 116 def aslist(obj, sep=None, strip=True):
116 117 """
117 118 Returns given string separated by sep as list
118 119
119 120 :param obj:
120 121 :param sep:
121 122 :param strip:
122 123 """
123 124 if isinstance(obj, (basestring,)):
124 125 lst = obj.split(sep)
125 126 if strip:
126 127 lst = [v.strip() for v in lst]
127 128 return lst
128 129 elif isinstance(obj, (list, tuple)):
129 130 return obj
130 131 elif obj is None:
131 132 return []
132 133 else:
133 134 return [obj]
134 135
135 136
136 137 def convert_line_endings(line, mode):
137 138 """
138 139 Converts a given line "line end" accordingly to given mode
139 140
140 141 Available modes are::
141 142 0 - Unix
142 143 1 - Mac
143 144 2 - DOS
144 145
145 146 :param line: given line to convert
146 147 :param mode: mode to convert to
147 148 :rtype: str
148 149 :return: converted line according to mode
149 150 """
150 151 if mode == 0:
151 152 line = line.replace('\r\n', '\n')
152 153 line = line.replace('\r', '\n')
153 154 elif mode == 1:
154 155 line = line.replace('\r\n', '\r')
155 156 line = line.replace('\n', '\r')
156 157 elif mode == 2:
157 158 line = re.sub('\r(?!\n)|(?<!\r)\n', '\r\n', line)
158 159 return line
159 160
160 161
161 162 def detect_mode(line, default):
162 163 """
163 164 Detects line break for given line, if line break couldn't be found
164 165 given default value is returned
165 166
166 167 :param line: str line
167 168 :param default: default
168 169 :rtype: int
169 170 :return: value of line end on of 0 - Unix, 1 - Mac, 2 - DOS
170 171 """
171 172 if line.endswith('\r\n'):
172 173 return 2
173 174 elif line.endswith('\n'):
174 175 return 0
175 176 elif line.endswith('\r'):
176 177 return 1
177 178 else:
178 179 return default
179 180
180 181
181 182 def safe_int(val, default=None):
182 183 """
183 184 Returns int() of val if val is not convertable to int use default
184 185 instead
185 186
186 187 :param val:
187 188 :param default:
188 189 """
189 190
190 191 try:
191 192 val = int(val)
192 193 except (ValueError, TypeError):
193 194 val = default
194 195
195 196 return val
196 197
197 198
198 199 def safe_unicode(str_, from_encoding=None):
199 200 """
200 201 safe unicode function. Does few trick to turn str_ into unicode
201 202
202 203 In case of UnicodeDecode error, we try to return it with encoding detected
203 204 by chardet library if it fails fallback to unicode with errors replaced
204 205
205 206 :param str_: string to decode
206 207 :rtype: unicode
207 208 :returns: unicode object
208 209 """
209 210 if isinstance(str_, unicode):
210 211 return str_
211 212
212 213 if not from_encoding:
213 214 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
214 215 'utf8'), sep=',')
215 216 from_encoding = DEFAULT_ENCODINGS
216 217
217 218 if not isinstance(from_encoding, (list, tuple)):
218 219 from_encoding = [from_encoding]
219 220
220 221 try:
221 222 return unicode(str_)
222 223 except UnicodeDecodeError:
223 224 pass
224 225
225 226 for enc in from_encoding:
226 227 try:
227 228 return unicode(str_, enc)
228 229 except UnicodeDecodeError:
229 230 pass
230 231
231 232 try:
232 233 import chardet
233 234 encoding = chardet.detect(str_)['encoding']
234 235 if encoding is None:
235 236 raise Exception()
236 237 return str_.decode(encoding)
237 238 except (ImportError, UnicodeDecodeError, Exception):
238 239 return unicode(str_, from_encoding[0], 'replace')
239 240
240 241
241 242 def safe_str(unicode_, to_encoding=None):
242 243 """
243 244 safe str function. Does few trick to turn unicode_ into string
244 245
245 246 In case of UnicodeEncodeError, we try to return it with encoding detected
246 247 by chardet library if it fails fallback to string with errors replaced
247 248
248 249 :param unicode_: unicode to encode
249 250 :rtype: str
250 251 :returns: str object
251 252 """
252 253
253 254 # if it's not basestr cast to str
254 255 if not isinstance(unicode_, basestring):
255 256 return str(unicode_)
256 257
257 258 if isinstance(unicode_, str):
258 259 return unicode_
259 260
260 261 if not to_encoding:
261 262 DEFAULT_ENCODINGS = aslist(rhodecode.CONFIG.get('default_encoding',
262 263 'utf8'), sep=',')
263 264 to_encoding = DEFAULT_ENCODINGS
264 265
265 266 if not isinstance(to_encoding, (list, tuple)):
266 267 to_encoding = [to_encoding]
267 268
268 269 for enc in to_encoding:
269 270 try:
270 271 return unicode_.encode(enc)
271 272 except UnicodeEncodeError:
272 273 pass
273 274
274 275 try:
275 276 import chardet
276 277 encoding = chardet.detect(unicode_)['encoding']
277 278 if encoding is None:
278 279 raise UnicodeEncodeError()
279 280
280 281 return unicode_.encode(encoding)
281 282 except (ImportError, UnicodeEncodeError):
282 283 return unicode_.encode(to_encoding[0], 'replace')
283 284
284 285
285 286 def remove_suffix(s, suffix):
286 287 if s.endswith(suffix):
287 288 s = s[:-1 * len(suffix)]
288 289 return s
289 290
290 291
291 292 def remove_prefix(s, prefix):
292 293 if s.startswith(prefix):
293 294 s = s[len(prefix):]
294 295 return s
295 296
296 297
297 298 def find_calling_context(ignore_modules=None):
298 299 """
299 300 Look through the calling stack and return the frame which called
300 301 this function and is part of core module ( ie. rhodecode.* )
301 302
302 303 :param ignore_modules: list of modules to ignore eg. ['rhodecode.lib']
303 304 """
304 305
305 306 ignore_modules = ignore_modules or []
306 307
307 308 f = sys._getframe(2)
308 309 while f.f_back is not None:
309 310 name = f.f_globals.get('__name__')
310 311 if name and name.startswith(__name__.split('.')[0]):
311 312 if name not in ignore_modules:
312 313 return f
313 314 f = f.f_back
314 315 return None
315 316
316 317
317 318 def ping_connection(connection, branch):
318 319 if branch:
319 320 # "branch" refers to a sub-connection of a connection,
320 321 # we don't want to bother pinging on these.
321 322 return
322 323
323 324 # turn off "close with result". This flag is only used with
324 325 # "connectionless" execution, otherwise will be False in any case
325 326 save_should_close_with_result = connection.should_close_with_result
326 327 connection.should_close_with_result = False
327 328
328 329 try:
329 330 # run a SELECT 1. use a core select() so that
330 331 # the SELECT of a scalar value without a table is
331 332 # appropriately formatted for the backend
332 333 connection.scalar(sqlalchemy.sql.select([1]))
333 334 except sqlalchemy.exc.DBAPIError as err:
334 335 # catch SQLAlchemy's DBAPIError, which is a wrapper
335 336 # for the DBAPI's exception. It includes a .connection_invalidated
336 337 # attribute which specifies if this connection is a "disconnect"
337 338 # condition, which is based on inspection of the original exception
338 339 # by the dialect in use.
339 340 if err.connection_invalidated:
340 341 # run the same SELECT again - the connection will re-validate
341 342 # itself and establish a new connection. The disconnect detection
342 343 # here also causes the whole connection pool to be invalidated
343 344 # so that all stale connections are discarded.
344 345 connection.scalar(sqlalchemy.sql.select([1]))
345 346 else:
346 347 raise
347 348 finally:
348 349 # restore "close with result"
349 350 connection.should_close_with_result = save_should_close_with_result
350 351
351 352
352 353 def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs):
353 354 """Custom engine_from_config functions."""
354 355 log = logging.getLogger('sqlalchemy.engine')
355 356 engine = sqlalchemy.engine_from_config(configuration, prefix, **kwargs)
356 357
357 358 def color_sql(sql):
358 359 color_seq = '\033[1;33m' # This is yellow: code 33
359 360 normal = '\x1b[0m'
360 361 return ''.join([color_seq, sql, normal])
361 362
362 363 if configuration['debug']:
363 364 # attach events only for debug configuration
364 365
365 366 def before_cursor_execute(conn, cursor, statement,
366 367 parameters, context, executemany):
367 368 setattr(conn, 'query_start_time', time.time())
368 369 log.info(color_sql(">>>>> STARTING QUERY >>>>>"))
369 370 calling_context = find_calling_context(ignore_modules=[
370 371 'rhodecode.lib.caching_query',
371 372 'rhodecode.model.settings',
372 373 ])
373 374 if calling_context:
374 375 log.info(color_sql('call context %s:%s' % (
375 376 calling_context.f_code.co_filename,
376 377 calling_context.f_lineno,
377 378 )))
378 379
379 380 def after_cursor_execute(conn, cursor, statement,
380 381 parameters, context, executemany):
381 382 delattr(conn, 'query_start_time')
382 383
383 384 sqlalchemy.event.listen(engine, "engine_connect",
384 385 ping_connection)
385 386 sqlalchemy.event.listen(engine, "before_cursor_execute",
386 387 before_cursor_execute)
387 388 sqlalchemy.event.listen(engine, "after_cursor_execute",
388 389 after_cursor_execute)
389 390
390 391 return engine
391 392
392 393
393 394 def get_encryption_key(config):
394 395 secret = config.get('rhodecode.encrypted_values.secret')
395 396 default = config['beaker.session.secret']
396 397 return secret or default
397 398
398 399
399 400 def age(prevdate, now=None, show_short_version=False, show_suffix=True,
400 401 short_format=False):
401 402 """
402 403 Turns a datetime into an age string.
403 404 If show_short_version is True, this generates a shorter string with
404 405 an approximate age; ex. '1 day ago', rather than '1 day and 23 hours ago'.
405 406
406 407 * IMPORTANT*
407 408 Code of this function is written in special way so it's easier to
408 409 backport it to javascript. If you mean to update it, please also update
409 410 `jquery.timeago-extension.js` file
410 411
411 412 :param prevdate: datetime object
412 413 :param now: get current time, if not define we use
413 414 `datetime.datetime.now()`
414 415 :param show_short_version: if it should approximate the date and
415 416 return a shorter string
416 417 :param show_suffix:
417 418 :param short_format: show short format, eg 2D instead of 2 days
418 419 :rtype: unicode
419 420 :returns: unicode words describing age
420 421 """
421 422
422 423 def _get_relative_delta(now, prevdate):
423 424 base = dateutil.relativedelta.relativedelta(now, prevdate)
424 425 return {
425 426 'year': base.years,
426 427 'month': base.months,
427 428 'day': base.days,
428 429 'hour': base.hours,
429 430 'minute': base.minutes,
430 431 'second': base.seconds,
431 432 }
432 433
433 434 def _is_leap_year(year):
434 435 return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
435 436
436 437 def get_month(prevdate):
437 438 return prevdate.month
438 439
439 440 def get_year(prevdate):
440 441 return prevdate.year
441 442
442 443 now = now or datetime.datetime.now()
443 444 order = ['year', 'month', 'day', 'hour', 'minute', 'second']
444 445 deltas = {}
445 446 future = False
446 447
447 448 if prevdate > now:
448 449 now_old = now
449 450 now = prevdate
450 451 prevdate = now_old
451 452 future = True
452 453 if future:
453 454 prevdate = prevdate.replace(microsecond=0)
454 455 # Get date parts deltas
455 456 for part in order:
456 457 rel_delta = _get_relative_delta(now, prevdate)
457 458 deltas[part] = rel_delta[part]
458 459
459 460 # Fix negative offsets (there is 1 second between 10:59:59 and 11:00:00,
460 461 # not 1 hour, -59 minutes and -59 seconds)
461 462 offsets = [[5, 60], [4, 60], [3, 24]]
462 463 for element in offsets: # seconds, minutes, hours
463 464 num = element[0]
464 465 length = element[1]
465 466
466 467 part = order[num]
467 468 carry_part = order[num - 1]
468 469
469 470 if deltas[part] < 0:
470 471 deltas[part] += length
471 472 deltas[carry_part] -= 1
472 473
473 474 # Same thing for days except that the increment depends on the (variable)
474 475 # number of days in the month
475 476 month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
476 477 if deltas['day'] < 0:
477 478 if get_month(prevdate) == 2 and _is_leap_year(get_year(prevdate)):
478 479 deltas['day'] += 29
479 480 else:
480 481 deltas['day'] += month_lengths[get_month(prevdate) - 1]
481 482
482 483 deltas['month'] -= 1
483 484
484 485 if deltas['month'] < 0:
485 486 deltas['month'] += 12
486 487 deltas['year'] -= 1
487 488
488 489 # Format the result
489 490 if short_format:
490 491 fmt_funcs = {
491 492 'year': lambda d: u'%dy' % d,
492 493 'month': lambda d: u'%dm' % d,
493 494 'day': lambda d: u'%dd' % d,
494 495 'hour': lambda d: u'%dh' % d,
495 496 'minute': lambda d: u'%dmin' % d,
496 497 'second': lambda d: u'%dsec' % d,
497 498 }
498 499 else:
499 500 fmt_funcs = {
500 501 'year': lambda d: _pluralize(u'${num} year', u'${num} years', d, mapping={'num': d}).interpolate(),
501 502 'month': lambda d: _pluralize(u'${num} month', u'${num} months', d, mapping={'num': d}).interpolate(),
502 503 'day': lambda d: _pluralize(u'${num} day', u'${num} days', d, mapping={'num': d}).interpolate(),
503 504 'hour': lambda d: _pluralize(u'${num} hour', u'${num} hours', d, mapping={'num': d}).interpolate(),
504 505 'minute': lambda d: _pluralize(u'${num} minute', u'${num} minutes', d, mapping={'num': d}).interpolate(),
505 506 'second': lambda d: _pluralize(u'${num} second', u'${num} seconds', d, mapping={'num': d}).interpolate(),
506 507 }
507 508
508 509 i = 0
509 510 for part in order:
510 511 value = deltas[part]
511 512 if value != 0:
512 513
513 514 if i < 5:
514 515 sub_part = order[i + 1]
515 516 sub_value = deltas[sub_part]
516 517 else:
517 518 sub_value = 0
518 519
519 520 if sub_value == 0 or show_short_version:
520 521 _val = fmt_funcs[part](value)
521 522 if future:
522 523 if show_suffix:
523 524 return _(u'in ${ago}', mapping={'ago': _val})
524 525 else:
525 526 return _(_val)
526 527
527 528 else:
528 529 if show_suffix:
529 530 return _(u'${ago} ago', mapping={'ago': _val})
530 531 else:
531 532 return _(_val)
532 533
533 534 val = fmt_funcs[part](value)
534 535 val_detail = fmt_funcs[sub_part](sub_value)
535 536 mapping = {'val': val, 'detail': val_detail}
536 537
537 538 if short_format:
538 539 datetime_tmpl = _(u'${val}, ${detail}', mapping=mapping)
539 540 if show_suffix:
540 541 datetime_tmpl = _(u'${val}, ${detail} ago', mapping=mapping)
541 542 if future:
542 543 datetime_tmpl = _(u'in ${val}, ${detail}', mapping=mapping)
543 544 else:
544 545 datetime_tmpl = _(u'${val} and ${detail}', mapping=mapping)
545 546 if show_suffix:
546 547 datetime_tmpl = _(u'${val} and ${detail} ago', mapping=mapping)
547 548 if future:
548 549 datetime_tmpl = _(u'in ${val} and ${detail}', mapping=mapping)
549 550
550 551 return datetime_tmpl
551 552 i += 1
552 553 return _(u'just now')
553 554
554 555
555 556 def cleaned_uri(uri):
556 557 """
557 558 Quotes '[' and ']' from uri if there is only one of them.
558 559 according to RFC3986 we cannot use such chars in uri
559 560 :param uri:
560 561 :return: uri without this chars
561 562 """
562 563 return urllib.quote(uri, safe='@$:/')
563 564
564 565
565 566 def uri_filter(uri):
566 567 """
567 568 Removes user:password from given url string
568 569
569 570 :param uri:
570 571 :rtype: unicode
571 572 :returns: filtered list of strings
572 573 """
573 574 if not uri:
574 575 return ''
575 576
576 577 proto = ''
577 578
578 579 for pat in ('https://', 'http://'):
579 580 if uri.startswith(pat):
580 581 uri = uri[len(pat):]
581 582 proto = pat
582 583 break
583 584
584 585 # remove passwords and username
585 586 uri = uri[uri.find('@') + 1:]
586 587
587 588 # get the port
588 589 cred_pos = uri.find(':')
589 590 if cred_pos == -1:
590 591 host, port = uri, None
591 592 else:
592 593 host, port = uri[:cred_pos], uri[cred_pos + 1:]
593 594
594 595 return filter(None, [proto, host, port])
595 596
596 597
597 598 def credentials_filter(uri):
598 599 """
599 600 Returns a url with removed credentials
600 601
601 602 :param uri:
602 603 """
603 604
604 605 uri = uri_filter(uri)
605 606 # check if we have port
606 607 if len(uri) > 2 and uri[2]:
607 608 uri[2] = ':' + uri[2]
608 609
609 610 return ''.join(uri)
610 611
611 612
612 613 def get_clone_url(request, uri_tmpl, repo_name, repo_id, **override):
613 614 qualifed_home_url = request.route_url('home')
614 615 parsed_url = urlobject.URLObject(qualifed_home_url)
615 616 decoded_path = safe_unicode(urllib.unquote(parsed_url.path.rstrip('/')))
617
616 618 args = {
617 619 'scheme': parsed_url.scheme,
618 620 'user': '',
621 'sys_user': getpass.getuser(),
619 622 # path if we use proxy-prefix
620 623 'netloc': parsed_url.netloc+decoded_path,
624 'hostname': parsed_url.hostname,
621 625 'prefix': decoded_path,
622 626 'repo': repo_name,
623 627 'repoid': str(repo_id)
624 628 }
625 629 args.update(override)
626 630 args['user'] = urllib.quote(safe_str(args['user']))
627 631
628 632 for k, v in args.items():
629 633 uri_tmpl = uri_tmpl.replace('{%s}' % k, v)
630 634
631 635 # remove leading @ sign if it's present. Case of empty user
632 636 url_obj = urlobject.URLObject(uri_tmpl)
633 637 url = url_obj.with_netloc(url_obj.netloc.lstrip('@'))
634 638
635 639 return safe_unicode(url)
636 640
637 641
638 642 def get_commit_safe(repo, commit_id=None, commit_idx=None, pre_load=None):
639 643 """
640 644 Safe version of get_commit if this commit doesn't exists for a
641 645 repository it returns a Dummy one instead
642 646
643 647 :param repo: repository instance
644 648 :param commit_id: commit id as str
645 649 :param pre_load: optional list of commit attributes to load
646 650 """
647 651 # TODO(skreft): remove these circular imports
648 652 from rhodecode.lib.vcs.backends.base import BaseRepository, EmptyCommit
649 653 from rhodecode.lib.vcs.exceptions import RepositoryError
650 654 if not isinstance(repo, BaseRepository):
651 655 raise Exception('You must pass an Repository '
652 656 'object as first argument got %s', type(repo))
653 657
654 658 try:
655 659 commit = repo.get_commit(
656 660 commit_id=commit_id, commit_idx=commit_idx, pre_load=pre_load)
657 661 except (RepositoryError, LookupError):
658 662 commit = EmptyCommit()
659 663 return commit
660 664
661 665
662 666 def datetime_to_time(dt):
663 667 if dt:
664 668 return time.mktime(dt.timetuple())
665 669
666 670
667 671 def time_to_datetime(tm):
668 672 if tm:
669 673 if isinstance(tm, basestring):
670 674 try:
671 675 tm = float(tm)
672 676 except ValueError:
673 677 return
674 678 return datetime.datetime.fromtimestamp(tm)
675 679
676 680
677 681 def time_to_utcdatetime(tm):
678 682 if tm:
679 683 if isinstance(tm, basestring):
680 684 try:
681 685 tm = float(tm)
682 686 except ValueError:
683 687 return
684 688 return datetime.datetime.utcfromtimestamp(tm)
685 689
686 690
687 691 MENTIONS_REGEX = re.compile(
688 692 # ^@ or @ without any special chars in front
689 693 r'(?:^@|[^a-zA-Z0-9\-\_\.]@)'
690 694 # main body starts with letter, then can be . - _
691 695 r'([a-zA-Z0-9]{1}[a-zA-Z0-9\-\_\.]+)',
692 696 re.VERBOSE | re.MULTILINE)
693 697
694 698
695 699 def extract_mentioned_users(s):
696 700 """
697 701 Returns unique usernames from given string s that have @mention
698 702
699 703 :param s: string to get mentions
700 704 """
701 705 usrs = set()
702 706 for username in MENTIONS_REGEX.findall(s):
703 707 usrs.add(username)
704 708
705 709 return sorted(list(usrs), key=lambda k: k.lower())
706 710
707 711
708 712 class StrictAttributeDict(dict):
709 713 """
710 714 Strict Version of Attribute dict which raises an Attribute error when
711 715 requested attribute is not set
712 716 """
713 717 def __getattr__(self, attr):
714 718 try:
715 719 return self[attr]
716 720 except KeyError:
717 721 raise AttributeError('%s object has no attribute %s' % (
718 722 self.__class__, attr))
719 723 __setattr__ = dict.__setitem__
720 724 __delattr__ = dict.__delitem__
721 725
722 726
723 727 class AttributeDict(dict):
724 728 def __getattr__(self, attr):
725 729 return self.get(attr, None)
726 730 __setattr__ = dict.__setitem__
727 731 __delattr__ = dict.__delitem__
728 732
729 733
730 734 def fix_PATH(os_=None):
731 735 """
732 736 Get current active python path, and append it to PATH variable to fix
733 737 issues of subprocess calls and different python versions
734 738 """
735 739 if os_ is None:
736 740 import os
737 741 else:
738 742 os = os_
739 743
740 744 cur_path = os.path.split(sys.executable)[0]
741 745 if not os.environ['PATH'].startswith(cur_path):
742 746 os.environ['PATH'] = '%s:%s' % (cur_path, os.environ['PATH'])
743 747
744 748
745 749 def obfuscate_url_pw(engine):
746 750 _url = engine or ''
747 751 try:
748 752 _url = sqlalchemy.engine.url.make_url(engine)
749 753 if _url.password:
750 754 _url.password = 'XXXXX'
751 755 except Exception:
752 756 pass
753 757 return unicode(_url)
754 758
755 759
756 760 def get_server_url(environ):
757 761 req = webob.Request(environ)
758 762 return req.host_url + req.script_name
759 763
760 764
761 765 def unique_id(hexlen=32):
762 766 alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz"
763 767 return suuid(truncate_to=hexlen, alphabet=alphabet)
764 768
765 769
766 770 def suuid(url=None, truncate_to=22, alphabet=None):
767 771 """
768 772 Generate and return a short URL safe UUID.
769 773
770 774 If the url parameter is provided, set the namespace to the provided
771 775 URL and generate a UUID.
772 776
773 777 :param url to get the uuid for
774 778 :truncate_to: truncate the basic 22 UUID to shorter version
775 779
776 780 The IDs won't be universally unique any longer, but the probability of
777 781 a collision will still be very low.
778 782 """
779 783 # Define our alphabet.
780 784 _ALPHABET = alphabet or "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
781 785
782 786 # If no URL is given, generate a random UUID.
783 787 if url is None:
784 788 unique_id = uuid.uuid4().int
785 789 else:
786 790 unique_id = uuid.uuid3(uuid.NAMESPACE_URL, url).int
787 791
788 792 alphabet_length = len(_ALPHABET)
789 793 output = []
790 794 while unique_id > 0:
791 795 digit = unique_id % alphabet_length
792 796 output.append(_ALPHABET[digit])
793 797 unique_id = int(unique_id / alphabet_length)
794 798 return "".join(output)[:truncate_to]
795 799
796 800
797 801 def get_current_rhodecode_user(request=None):
798 802 """
799 803 Gets rhodecode user from request
800 804 """
801 805 pyramid_request = request or pyramid.threadlocal.get_current_request()
802 806
803 807 # web case
804 808 if pyramid_request and hasattr(pyramid_request, 'user'):
805 809 return pyramid_request.user
806 810
807 811 # api case
808 812 if pyramid_request and hasattr(pyramid_request, 'rpc_user'):
809 813 return pyramid_request.rpc_user
810 814
811 815 return None
812 816
813 817
814 818 def action_logger_generic(action, namespace=''):
815 819 """
816 820 A generic logger for actions useful to the system overview, tries to find
817 821 an acting user for the context of the call otherwise reports unknown user
818 822
819 823 :param action: logging message eg 'comment 5 deleted'
820 824 :param type: string
821 825
822 826 :param namespace: namespace of the logging message eg. 'repo.comments'
823 827 :param type: string
824 828
825 829 """
826 830
827 831 logger_name = 'rhodecode.actions'
828 832
829 833 if namespace:
830 834 logger_name += '.' + namespace
831 835
832 836 log = logging.getLogger(logger_name)
833 837
834 838 # get a user if we can
835 839 user = get_current_rhodecode_user()
836 840
837 841 logfunc = log.info
838 842
839 843 if not user:
840 844 user = '<unknown user>'
841 845 logfunc = log.warning
842 846
843 847 logfunc('Logging action by {}: {}'.format(user, action))
844 848
845 849
846 850 def escape_split(text, sep=',', maxsplit=-1):
847 851 r"""
848 852 Allows for escaping of the separator: e.g. arg='foo\, bar'
849 853
850 854 It should be noted that the way bash et. al. do command line parsing, those
851 855 single quotes are required.
852 856 """
853 857 escaped_sep = r'\%s' % sep
854 858
855 859 if escaped_sep not in text:
856 860 return text.split(sep, maxsplit)
857 861
858 862 before, _mid, after = text.partition(escaped_sep)
859 863 startlist = before.split(sep, maxsplit) # a regular split is fine here
860 864 unfinished = startlist[-1]
861 865 startlist = startlist[:-1]
862 866
863 867 # recurse because there may be more escaped separators
864 868 endlist = escape_split(after, sep, maxsplit)
865 869
866 870 # finish building the escaped value. we use endlist[0] becaue the first
867 871 # part of the string sent in recursion is the rest of the escaped value.
868 872 unfinished += sep + endlist[0]
869 873
870 874 return startlist + [unfinished] + endlist[1:] # put together all the parts
871 875
872 876
873 877 class OptionalAttr(object):
874 878 """
875 879 Special Optional Option that defines other attribute. Example::
876 880
877 881 def test(apiuser, userid=Optional(OAttr('apiuser')):
878 882 user = Optional.extract(userid)
879 883 # calls
880 884
881 885 """
882 886
883 887 def __init__(self, attr_name):
884 888 self.attr_name = attr_name
885 889
886 890 def __repr__(self):
887 891 return '<OptionalAttr:%s>' % self.attr_name
888 892
889 893 def __call__(self):
890 894 return self
891 895
892 896
893 897 # alias
894 898 OAttr = OptionalAttr
895 899
896 900
897 901 class Optional(object):
898 902 """
899 903 Defines an optional parameter::
900 904
901 905 param = param.getval() if isinstance(param, Optional) else param
902 906 param = param() if isinstance(param, Optional) else param
903 907
904 908 is equivalent of::
905 909
906 910 param = Optional.extract(param)
907 911
908 912 """
909 913
910 914 def __init__(self, type_):
911 915 self.type_ = type_
912 916
913 917 def __repr__(self):
914 918 return '<Optional:%s>' % self.type_.__repr__()
915 919
916 920 def __call__(self):
917 921 return self.getval()
918 922
919 923 def getval(self):
920 924 """
921 925 returns value from this Optional instance
922 926 """
923 927 if isinstance(self.type_, OAttr):
924 928 # use params name
925 929 return self.type_.attr_name
926 930 return self.type_
927 931
928 932 @classmethod
929 933 def extract(cls, val):
930 934 """
931 935 Extracts value from Optional() instance
932 936
933 937 :param val:
934 938 :return: original value if it's not Optional instance else
935 939 value of instance
936 940 """
937 941 if isinstance(val, cls):
938 942 return val.getval()
939 943 return val
940 944
941 945
942 946 def glob2re(pat):
943 947 """
944 948 Translate a shell PATTERN to a regular expression.
945 949
946 950 There is no way to quote meta-characters.
947 951 """
948 952
949 953 i, n = 0, len(pat)
950 954 res = ''
951 955 while i < n:
952 956 c = pat[i]
953 957 i = i+1
954 958 if c == '*':
955 959 #res = res + '.*'
956 960 res = res + '[^/]*'
957 961 elif c == '?':
958 962 #res = res + '.'
959 963 res = res + '[^/]'
960 964 elif c == '[':
961 965 j = i
962 966 if j < n and pat[j] == '!':
963 967 j = j+1
964 968 if j < n and pat[j] == ']':
965 969 j = j+1
966 970 while j < n and pat[j] != ']':
967 971 j = j+1
968 972 if j >= n:
969 973 res = res + '\\['
970 974 else:
971 975 stuff = pat[i:j].replace('\\','\\\\')
972 976 i = j+1
973 977 if stuff[0] == '!':
974 978 stuff = '^' + stuff[1:]
975 979 elif stuff[0] == '^':
976 980 stuff = '\\' + stuff
977 981 res = '%s[%s]' % (res, stuff)
978 982 else:
979 983 res = res + re.escape(c)
980 984 return res + '\Z(?ms)'
@@ -1,4453 +1,4463 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 Database Models for RhodeCode Enterprise
23 23 """
24 24
25 25 import re
26 26 import os
27 27 import time
28 28 import hashlib
29 29 import logging
30 30 import datetime
31 31 import warnings
32 32 import ipaddress
33 33 import functools
34 34 import traceback
35 35 import collections
36 36
37 37 from sqlalchemy import (
38 38 or_, and_, not_, func, TypeDecorator, event,
39 39 Index, Sequence, UniqueConstraint, ForeignKey, CheckConstraint, Column,
40 40 Boolean, String, Unicode, UnicodeText, DateTime, Integer, LargeBinary,
41 41 Text, Float, PickleType)
42 42 from sqlalchemy.sql.expression import true, false
43 43 from sqlalchemy.sql.functions import coalesce, count # noqa
44 44 from sqlalchemy.orm import (
45 45 relationship, joinedload, class_mapper, validates, aliased)
46 46 from sqlalchemy.ext.declarative import declared_attr
47 47 from sqlalchemy.ext.hybrid import hybrid_property
48 48 from sqlalchemy.exc import IntegrityError # noqa
49 49 from sqlalchemy.dialects.mysql import LONGTEXT
50 50 from beaker.cache import cache_region
51 51 from zope.cachedescriptors.property import Lazy as LazyProperty
52 52
53 53 from pyramid.threadlocal import get_current_request
54 54
55 55 from rhodecode.translation import _
56 56 from rhodecode.lib.vcs import get_vcs_instance
57 57 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
58 58 from rhodecode.lib.utils2 import (
59 59 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
60 60 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
61 61 glob2re, StrictAttributeDict, cleaned_uri)
62 62 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType, \
63 63 JsonRaw
64 64 from rhodecode.lib.ext_json import json
65 65 from rhodecode.lib.caching_query import FromCache
66 66 from rhodecode.lib.encrypt import AESCipher
67 67
68 68 from rhodecode.model.meta import Base, Session
69 69
70 70 URL_SEP = '/'
71 71 log = logging.getLogger(__name__)
72 72
73 73 # =============================================================================
74 74 # BASE CLASSES
75 75 # =============================================================================
76 76
77 77 # this is propagated from .ini file rhodecode.encrypted_values.secret or
78 78 # beaker.session.secret if first is not set.
79 79 # and initialized at environment.py
80 80 ENCRYPTION_KEY = None
81 81
82 82 # used to sort permissions by types, '#' used here is not allowed to be in
83 83 # usernames, and it's very early in sorted string.printable table.
84 84 PERMISSION_TYPE_SORT = {
85 85 'admin': '####',
86 86 'write': '###',
87 87 'read': '##',
88 88 'none': '#',
89 89 }
90 90
91 91
92 92 def display_user_sort(obj):
93 93 """
94 94 Sort function used to sort permissions in .permissions() function of
95 95 Repository, RepoGroup, UserGroup. Also it put the default user in front
96 96 of all other resources
97 97 """
98 98
99 99 if obj.username == User.DEFAULT_USER:
100 100 return '#####'
101 101 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
102 102 return prefix + obj.username
103 103
104 104
105 105 def display_user_group_sort(obj):
106 106 """
107 107 Sort function used to sort permissions in .permissions() function of
108 108 Repository, RepoGroup, UserGroup. Also it put the default user in front
109 109 of all other resources
110 110 """
111 111
112 112 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
113 113 return prefix + obj.users_group_name
114 114
115 115
116 116 def _hash_key(k):
117 117 return md5_safe(k)
118 118
119 119
120 120 def in_filter_generator(qry, items, limit=500):
121 121 """
122 122 Splits IN() into multiple with OR
123 123 e.g.::
124 124 cnt = Repository.query().filter(
125 125 or_(
126 126 *in_filter_generator(Repository.repo_id, range(100000))
127 127 )).count()
128 128 """
129 129 if not items:
130 130 # empty list will cause empty query which might cause security issues
131 131 # this can lead to hidden unpleasant results
132 132 items = [-1]
133 133
134 134 parts = []
135 135 for chunk in xrange(0, len(items), limit):
136 136 parts.append(
137 137 qry.in_(items[chunk: chunk + limit])
138 138 )
139 139
140 140 return parts
141 141
142 142
143 143 class EncryptedTextValue(TypeDecorator):
144 144 """
145 145 Special column for encrypted long text data, use like::
146 146
147 147 value = Column("encrypted_value", EncryptedValue(), nullable=False)
148 148
149 149 This column is intelligent so if value is in unencrypted form it return
150 150 unencrypted form, but on save it always encrypts
151 151 """
152 152 impl = Text
153 153
154 154 def process_bind_param(self, value, dialect):
155 155 if not value:
156 156 return value
157 157 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
158 158 # protect against double encrypting if someone manually starts
159 159 # doing
160 160 raise ValueError('value needs to be in unencrypted format, ie. '
161 161 'not starting with enc$aes')
162 162 return 'enc$aes_hmac$%s' % AESCipher(
163 163 ENCRYPTION_KEY, hmac=True).encrypt(value)
164 164
165 165 def process_result_value(self, value, dialect):
166 166 import rhodecode
167 167
168 168 if not value:
169 169 return value
170 170
171 171 parts = value.split('$', 3)
172 172 if not len(parts) == 3:
173 173 # probably not encrypted values
174 174 return value
175 175 else:
176 176 if parts[0] != 'enc':
177 177 # parts ok but without our header ?
178 178 return value
179 179 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
180 180 'rhodecode.encrypted_values.strict') or True)
181 181 # at that stage we know it's our encryption
182 182 if parts[1] == 'aes':
183 183 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
184 184 elif parts[1] == 'aes_hmac':
185 185 decrypted_data = AESCipher(
186 186 ENCRYPTION_KEY, hmac=True,
187 187 strict_verification=enc_strict_mode).decrypt(parts[2])
188 188 else:
189 189 raise ValueError(
190 190 'Encryption type part is wrong, must be `aes` '
191 191 'or `aes_hmac`, got `%s` instead' % (parts[1]))
192 192 return decrypted_data
193 193
194 194
195 195 class BaseModel(object):
196 196 """
197 197 Base Model for all classes
198 198 """
199 199
200 200 @classmethod
201 201 def _get_keys(cls):
202 202 """return column names for this model """
203 203 return class_mapper(cls).c.keys()
204 204
205 205 def get_dict(self):
206 206 """
207 207 return dict with keys and values corresponding
208 208 to this model data """
209 209
210 210 d = {}
211 211 for k in self._get_keys():
212 212 d[k] = getattr(self, k)
213 213
214 214 # also use __json__() if present to get additional fields
215 215 _json_attr = getattr(self, '__json__', None)
216 216 if _json_attr:
217 217 # update with attributes from __json__
218 218 if callable(_json_attr):
219 219 _json_attr = _json_attr()
220 220 for k, val in _json_attr.iteritems():
221 221 d[k] = val
222 222 return d
223 223
224 224 def get_appstruct(self):
225 225 """return list with keys and values tuples corresponding
226 226 to this model data """
227 227
228 228 lst = []
229 229 for k in self._get_keys():
230 230 lst.append((k, getattr(self, k),))
231 231 return lst
232 232
233 233 def populate_obj(self, populate_dict):
234 234 """populate model with data from given populate_dict"""
235 235
236 236 for k in self._get_keys():
237 237 if k in populate_dict:
238 238 setattr(self, k, populate_dict[k])
239 239
240 240 @classmethod
241 241 def query(cls):
242 242 return Session().query(cls)
243 243
244 244 @classmethod
245 245 def get(cls, id_):
246 246 if id_:
247 247 return cls.query().get(id_)
248 248
249 249 @classmethod
250 250 def get_or_404(cls, id_):
251 251 from pyramid.httpexceptions import HTTPNotFound
252 252
253 253 try:
254 254 id_ = int(id_)
255 255 except (TypeError, ValueError):
256 256 raise HTTPNotFound()
257 257
258 258 res = cls.query().get(id_)
259 259 if not res:
260 260 raise HTTPNotFound()
261 261 return res
262 262
263 263 @classmethod
264 264 def getAll(cls):
265 265 # deprecated and left for backward compatibility
266 266 return cls.get_all()
267 267
268 268 @classmethod
269 269 def get_all(cls):
270 270 return cls.query().all()
271 271
272 272 @classmethod
273 273 def delete(cls, id_):
274 274 obj = cls.query().get(id_)
275 275 Session().delete(obj)
276 276
277 277 @classmethod
278 278 def identity_cache(cls, session, attr_name, value):
279 279 exist_in_session = []
280 280 for (item_cls, pkey), instance in session.identity_map.items():
281 281 if cls == item_cls and getattr(instance, attr_name) == value:
282 282 exist_in_session.append(instance)
283 283 if exist_in_session:
284 284 if len(exist_in_session) == 1:
285 285 return exist_in_session[0]
286 286 log.exception(
287 287 'multiple objects with attr %s and '
288 288 'value %s found with same name: %r',
289 289 attr_name, value, exist_in_session)
290 290
291 291 def __repr__(self):
292 292 if hasattr(self, '__unicode__'):
293 293 # python repr needs to return str
294 294 try:
295 295 return safe_str(self.__unicode__())
296 296 except UnicodeDecodeError:
297 297 pass
298 298 return '<DB:%s>' % (self.__class__.__name__)
299 299
300 300
301 301 class RhodeCodeSetting(Base, BaseModel):
302 302 __tablename__ = 'rhodecode_settings'
303 303 __table_args__ = (
304 304 UniqueConstraint('app_settings_name'),
305 305 {'extend_existing': True, 'mysql_engine': 'InnoDB',
306 306 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
307 307 )
308 308
309 309 SETTINGS_TYPES = {
310 310 'str': safe_str,
311 311 'int': safe_int,
312 312 'unicode': safe_unicode,
313 313 'bool': str2bool,
314 314 'list': functools.partial(aslist, sep=',')
315 315 }
316 316 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
317 317 GLOBAL_CONF_KEY = 'app_settings'
318 318
319 319 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
320 320 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
321 321 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
322 322 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
323 323
324 324 def __init__(self, key='', val='', type='unicode'):
325 325 self.app_settings_name = key
326 326 self.app_settings_type = type
327 327 self.app_settings_value = val
328 328
329 329 @validates('_app_settings_value')
330 330 def validate_settings_value(self, key, val):
331 331 assert type(val) == unicode
332 332 return val
333 333
334 334 @hybrid_property
335 335 def app_settings_value(self):
336 336 v = self._app_settings_value
337 337 _type = self.app_settings_type
338 338 if _type:
339 339 _type = self.app_settings_type.split('.')[0]
340 340 # decode the encrypted value
341 341 if 'encrypted' in self.app_settings_type:
342 342 cipher = EncryptedTextValue()
343 343 v = safe_unicode(cipher.process_result_value(v, None))
344 344
345 345 converter = self.SETTINGS_TYPES.get(_type) or \
346 346 self.SETTINGS_TYPES['unicode']
347 347 return converter(v)
348 348
349 349 @app_settings_value.setter
350 350 def app_settings_value(self, val):
351 351 """
352 352 Setter that will always make sure we use unicode in app_settings_value
353 353
354 354 :param val:
355 355 """
356 356 val = safe_unicode(val)
357 357 # encode the encrypted value
358 358 if 'encrypted' in self.app_settings_type:
359 359 cipher = EncryptedTextValue()
360 360 val = safe_unicode(cipher.process_bind_param(val, None))
361 361 self._app_settings_value = val
362 362
363 363 @hybrid_property
364 364 def app_settings_type(self):
365 365 return self._app_settings_type
366 366
367 367 @app_settings_type.setter
368 368 def app_settings_type(self, val):
369 369 if val.split('.')[0] not in self.SETTINGS_TYPES:
370 370 raise Exception('type must be one of %s got %s'
371 371 % (self.SETTINGS_TYPES.keys(), val))
372 372 self._app_settings_type = val
373 373
374 374 def __unicode__(self):
375 375 return u"<%s('%s:%s[%s]')>" % (
376 376 self.__class__.__name__,
377 377 self.app_settings_name, self.app_settings_value,
378 378 self.app_settings_type
379 379 )
380 380
381 381
382 382 class RhodeCodeUi(Base, BaseModel):
383 383 __tablename__ = 'rhodecode_ui'
384 384 __table_args__ = (
385 385 UniqueConstraint('ui_key'),
386 386 {'extend_existing': True, 'mysql_engine': 'InnoDB',
387 387 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
388 388 )
389 389
390 390 HOOK_REPO_SIZE = 'changegroup.repo_size'
391 391 # HG
392 392 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
393 393 HOOK_PULL = 'outgoing.pull_logger'
394 394 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
395 395 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
396 396 HOOK_PUSH = 'changegroup.push_logger'
397 397 HOOK_PUSH_KEY = 'pushkey.key_push'
398 398
399 399 # TODO: johbo: Unify way how hooks are configured for git and hg,
400 400 # git part is currently hardcoded.
401 401
402 402 # SVN PATTERNS
403 403 SVN_BRANCH_ID = 'vcs_svn_branch'
404 404 SVN_TAG_ID = 'vcs_svn_tag'
405 405
406 406 ui_id = Column(
407 407 "ui_id", Integer(), nullable=False, unique=True, default=None,
408 408 primary_key=True)
409 409 ui_section = Column(
410 410 "ui_section", String(255), nullable=True, unique=None, default=None)
411 411 ui_key = Column(
412 412 "ui_key", String(255), nullable=True, unique=None, default=None)
413 413 ui_value = Column(
414 414 "ui_value", String(255), nullable=True, unique=None, default=None)
415 415 ui_active = Column(
416 416 "ui_active", Boolean(), nullable=True, unique=None, default=True)
417 417
418 418 def __repr__(self):
419 419 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
420 420 self.ui_key, self.ui_value)
421 421
422 422
423 423 class RepoRhodeCodeSetting(Base, BaseModel):
424 424 __tablename__ = 'repo_rhodecode_settings'
425 425 __table_args__ = (
426 426 UniqueConstraint(
427 427 'app_settings_name', 'repository_id',
428 428 name='uq_repo_rhodecode_setting_name_repo_id'),
429 429 {'extend_existing': True, 'mysql_engine': 'InnoDB',
430 430 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
431 431 )
432 432
433 433 repository_id = Column(
434 434 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
435 435 nullable=False)
436 436 app_settings_id = Column(
437 437 "app_settings_id", Integer(), nullable=False, unique=True,
438 438 default=None, primary_key=True)
439 439 app_settings_name = Column(
440 440 "app_settings_name", String(255), nullable=True, unique=None,
441 441 default=None)
442 442 _app_settings_value = Column(
443 443 "app_settings_value", String(4096), nullable=True, unique=None,
444 444 default=None)
445 445 _app_settings_type = Column(
446 446 "app_settings_type", String(255), nullable=True, unique=None,
447 447 default=None)
448 448
449 449 repository = relationship('Repository')
450 450
451 451 def __init__(self, repository_id, key='', val='', type='unicode'):
452 452 self.repository_id = repository_id
453 453 self.app_settings_name = key
454 454 self.app_settings_type = type
455 455 self.app_settings_value = val
456 456
457 457 @validates('_app_settings_value')
458 458 def validate_settings_value(self, key, val):
459 459 assert type(val) == unicode
460 460 return val
461 461
462 462 @hybrid_property
463 463 def app_settings_value(self):
464 464 v = self._app_settings_value
465 465 type_ = self.app_settings_type
466 466 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
467 467 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
468 468 return converter(v)
469 469
470 470 @app_settings_value.setter
471 471 def app_settings_value(self, val):
472 472 """
473 473 Setter that will always make sure we use unicode in app_settings_value
474 474
475 475 :param val:
476 476 """
477 477 self._app_settings_value = safe_unicode(val)
478 478
479 479 @hybrid_property
480 480 def app_settings_type(self):
481 481 return self._app_settings_type
482 482
483 483 @app_settings_type.setter
484 484 def app_settings_type(self, val):
485 485 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
486 486 if val not in SETTINGS_TYPES:
487 487 raise Exception('type must be one of %s got %s'
488 488 % (SETTINGS_TYPES.keys(), val))
489 489 self._app_settings_type = val
490 490
491 491 def __unicode__(self):
492 492 return u"<%s('%s:%s:%s[%s]')>" % (
493 493 self.__class__.__name__, self.repository.repo_name,
494 494 self.app_settings_name, self.app_settings_value,
495 495 self.app_settings_type
496 496 )
497 497
498 498
499 499 class RepoRhodeCodeUi(Base, BaseModel):
500 500 __tablename__ = 'repo_rhodecode_ui'
501 501 __table_args__ = (
502 502 UniqueConstraint(
503 503 'repository_id', 'ui_section', 'ui_key',
504 504 name='uq_repo_rhodecode_ui_repository_id_section_key'),
505 505 {'extend_existing': True, 'mysql_engine': 'InnoDB',
506 506 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
507 507 )
508 508
509 509 repository_id = Column(
510 510 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
511 511 nullable=False)
512 512 ui_id = Column(
513 513 "ui_id", Integer(), nullable=False, unique=True, default=None,
514 514 primary_key=True)
515 515 ui_section = Column(
516 516 "ui_section", String(255), nullable=True, unique=None, default=None)
517 517 ui_key = Column(
518 518 "ui_key", String(255), nullable=True, unique=None, default=None)
519 519 ui_value = Column(
520 520 "ui_value", String(255), nullable=True, unique=None, default=None)
521 521 ui_active = Column(
522 522 "ui_active", Boolean(), nullable=True, unique=None, default=True)
523 523
524 524 repository = relationship('Repository')
525 525
526 526 def __repr__(self):
527 527 return '<%s[%s:%s]%s=>%s]>' % (
528 528 self.__class__.__name__, self.repository.repo_name,
529 529 self.ui_section, self.ui_key, self.ui_value)
530 530
531 531
532 532 class User(Base, BaseModel):
533 533 __tablename__ = 'users'
534 534 __table_args__ = (
535 535 UniqueConstraint('username'), UniqueConstraint('email'),
536 536 Index('u_username_idx', 'username'),
537 537 Index('u_email_idx', 'email'),
538 538 {'extend_existing': True, 'mysql_engine': 'InnoDB',
539 539 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
540 540 )
541 541 DEFAULT_USER = 'default'
542 542 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
543 543 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
544 544
545 545 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
546 546 username = Column("username", String(255), nullable=True, unique=None, default=None)
547 547 password = Column("password", String(255), nullable=True, unique=None, default=None)
548 548 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
549 549 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
550 550 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
551 551 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
552 552 _email = Column("email", String(255), nullable=True, unique=None, default=None)
553 553 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
554 554 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
555 555
556 556 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
557 557 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
558 558 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
559 559 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
560 560 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
561 561 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
562 562
563 563 user_log = relationship('UserLog')
564 564 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
565 565
566 566 repositories = relationship('Repository')
567 567 repository_groups = relationship('RepoGroup')
568 568 user_groups = relationship('UserGroup')
569 569
570 570 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
571 571 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
572 572
573 573 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
574 574 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
575 575 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
576 576
577 577 group_member = relationship('UserGroupMember', cascade='all')
578 578
579 579 notifications = relationship('UserNotification', cascade='all')
580 580 # notifications assigned to this user
581 581 user_created_notifications = relationship('Notification', cascade='all')
582 582 # comments created by this user
583 583 user_comments = relationship('ChangesetComment', cascade='all')
584 584 # user profile extra info
585 585 user_emails = relationship('UserEmailMap', cascade='all')
586 586 user_ip_map = relationship('UserIpMap', cascade='all')
587 587 user_auth_tokens = relationship('UserApiKeys', cascade='all')
588 588 user_ssh_keys = relationship('UserSshKeys', cascade='all')
589 589
590 590 # gists
591 591 user_gists = relationship('Gist', cascade='all')
592 592 # user pull requests
593 593 user_pull_requests = relationship('PullRequest', cascade='all')
594 594 # external identities
595 595 extenal_identities = relationship(
596 596 'ExternalIdentity',
597 597 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
598 598 cascade='all')
599 599 # review rules
600 600 user_review_rules = relationship('RepoReviewRuleUser', cascade='all')
601 601
602 602 def __unicode__(self):
603 603 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
604 604 self.user_id, self.username)
605 605
606 606 @hybrid_property
607 607 def email(self):
608 608 return self._email
609 609
610 610 @email.setter
611 611 def email(self, val):
612 612 self._email = val.lower() if val else None
613 613
614 614 @hybrid_property
615 615 def first_name(self):
616 616 from rhodecode.lib import helpers as h
617 617 if self.name:
618 618 return h.escape(self.name)
619 619 return self.name
620 620
621 621 @hybrid_property
622 622 def last_name(self):
623 623 from rhodecode.lib import helpers as h
624 624 if self.lastname:
625 625 return h.escape(self.lastname)
626 626 return self.lastname
627 627
628 628 @hybrid_property
629 629 def api_key(self):
630 630 """
631 631 Fetch if exist an auth-token with role ALL connected to this user
632 632 """
633 633 user_auth_token = UserApiKeys.query()\
634 634 .filter(UserApiKeys.user_id == self.user_id)\
635 635 .filter(or_(UserApiKeys.expires == -1,
636 636 UserApiKeys.expires >= time.time()))\
637 637 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
638 638 if user_auth_token:
639 639 user_auth_token = user_auth_token.api_key
640 640
641 641 return user_auth_token
642 642
643 643 @api_key.setter
644 644 def api_key(self, val):
645 645 # don't allow to set API key this is deprecated for now
646 646 self._api_key = None
647 647
648 648 @property
649 649 def reviewer_pull_requests(self):
650 650 return PullRequestReviewers.query() \
651 651 .options(joinedload(PullRequestReviewers.pull_request)) \
652 652 .filter(PullRequestReviewers.user_id == self.user_id) \
653 653 .all()
654 654
655 655 @property
656 656 def firstname(self):
657 657 # alias for future
658 658 return self.name
659 659
660 660 @property
661 661 def emails(self):
662 662 other = UserEmailMap.query()\
663 663 .filter(UserEmailMap.user == self) \
664 664 .order_by(UserEmailMap.email_id.asc()) \
665 665 .all()
666 666 return [self.email] + [x.email for x in other]
667 667
668 668 @property
669 669 def auth_tokens(self):
670 670 auth_tokens = self.get_auth_tokens()
671 671 return [x.api_key for x in auth_tokens]
672 672
673 673 def get_auth_tokens(self):
674 674 return UserApiKeys.query()\
675 675 .filter(UserApiKeys.user == self)\
676 676 .order_by(UserApiKeys.user_api_key_id.asc())\
677 677 .all()
678 678
679 679 @LazyProperty
680 680 def feed_token(self):
681 681 return self.get_feed_token()
682 682
683 683 def get_feed_token(self, cache=True):
684 684 feed_tokens = UserApiKeys.query()\
685 685 .filter(UserApiKeys.user == self)\
686 686 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)
687 687 if cache:
688 688 feed_tokens = feed_tokens.options(
689 689 FromCache("long_term", "get_user_feed_token_%s" % self.user_id))
690 690
691 691 feed_tokens = feed_tokens.all()
692 692 if feed_tokens:
693 693 return feed_tokens[0].api_key
694 694 return 'NO_FEED_TOKEN_AVAILABLE'
695 695
696 696 @classmethod
697 697 def get(cls, user_id, cache=False):
698 698 if not user_id:
699 699 return
700 700
701 701 user = cls.query()
702 702 if cache:
703 703 user = user.options(
704 704 FromCache("sql_cache_short", "get_users_%s" % user_id))
705 705 return user.get(user_id)
706 706
707 707 @classmethod
708 708 def extra_valid_auth_tokens(cls, user, role=None):
709 709 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
710 710 .filter(or_(UserApiKeys.expires == -1,
711 711 UserApiKeys.expires >= time.time()))
712 712 if role:
713 713 tokens = tokens.filter(or_(UserApiKeys.role == role,
714 714 UserApiKeys.role == UserApiKeys.ROLE_ALL))
715 715 return tokens.all()
716 716
717 717 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
718 718 from rhodecode.lib import auth
719 719
720 720 log.debug('Trying to authenticate user: %s via auth-token, '
721 721 'and roles: %s', self, roles)
722 722
723 723 if not auth_token:
724 724 return False
725 725
726 726 crypto_backend = auth.crypto_backend()
727 727
728 728 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
729 729 tokens_q = UserApiKeys.query()\
730 730 .filter(UserApiKeys.user_id == self.user_id)\
731 731 .filter(or_(UserApiKeys.expires == -1,
732 732 UserApiKeys.expires >= time.time()))
733 733
734 734 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
735 735
736 736 plain_tokens = []
737 737 hash_tokens = []
738 738
739 739 for token in tokens_q.all():
740 740 # verify scope first
741 741 if token.repo_id:
742 742 # token has a scope, we need to verify it
743 743 if scope_repo_id != token.repo_id:
744 744 log.debug(
745 745 'Scope mismatch: token has a set repo scope: %s, '
746 746 'and calling scope is:%s, skipping further checks',
747 747 token.repo, scope_repo_id)
748 748 # token has a scope, and it doesn't match, skip token
749 749 continue
750 750
751 751 if token.api_key.startswith(crypto_backend.ENC_PREF):
752 752 hash_tokens.append(token.api_key)
753 753 else:
754 754 plain_tokens.append(token.api_key)
755 755
756 756 is_plain_match = auth_token in plain_tokens
757 757 if is_plain_match:
758 758 return True
759 759
760 760 for hashed in hash_tokens:
761 761 # TODO(marcink): this is expensive to calculate, but most secure
762 762 match = crypto_backend.hash_check(auth_token, hashed)
763 763 if match:
764 764 return True
765 765
766 766 return False
767 767
768 768 @property
769 769 def ip_addresses(self):
770 770 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
771 771 return [x.ip_addr for x in ret]
772 772
773 773 @property
774 774 def username_and_name(self):
775 775 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
776 776
777 777 @property
778 778 def username_or_name_or_email(self):
779 779 full_name = self.full_name if self.full_name is not ' ' else None
780 780 return self.username or full_name or self.email
781 781
782 782 @property
783 783 def full_name(self):
784 784 return '%s %s' % (self.first_name, self.last_name)
785 785
786 786 @property
787 787 def full_name_or_username(self):
788 788 return ('%s %s' % (self.first_name, self.last_name)
789 789 if (self.first_name and self.last_name) else self.username)
790 790
791 791 @property
792 792 def full_contact(self):
793 793 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
794 794
795 795 @property
796 796 def short_contact(self):
797 797 return '%s %s' % (self.first_name, self.last_name)
798 798
799 799 @property
800 800 def is_admin(self):
801 801 return self.admin
802 802
803 803 def AuthUser(self, **kwargs):
804 804 """
805 805 Returns instance of AuthUser for this user
806 806 """
807 807 from rhodecode.lib.auth import AuthUser
808 808 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
809 809
810 810 @hybrid_property
811 811 def user_data(self):
812 812 if not self._user_data:
813 813 return {}
814 814
815 815 try:
816 816 return json.loads(self._user_data)
817 817 except TypeError:
818 818 return {}
819 819
820 820 @user_data.setter
821 821 def user_data(self, val):
822 822 if not isinstance(val, dict):
823 823 raise Exception('user_data must be dict, got %s' % type(val))
824 824 try:
825 825 self._user_data = json.dumps(val)
826 826 except Exception:
827 827 log.error(traceback.format_exc())
828 828
829 829 @classmethod
830 830 def get_by_username(cls, username, case_insensitive=False,
831 831 cache=False, identity_cache=False):
832 832 session = Session()
833 833
834 834 if case_insensitive:
835 835 q = cls.query().filter(
836 836 func.lower(cls.username) == func.lower(username))
837 837 else:
838 838 q = cls.query().filter(cls.username == username)
839 839
840 840 if cache:
841 841 if identity_cache:
842 842 val = cls.identity_cache(session, 'username', username)
843 843 if val:
844 844 return val
845 845 else:
846 846 cache_key = "get_user_by_name_%s" % _hash_key(username)
847 847 q = q.options(
848 848 FromCache("sql_cache_short", cache_key))
849 849
850 850 return q.scalar()
851 851
852 852 @classmethod
853 853 def get_by_auth_token(cls, auth_token, cache=False):
854 854 q = UserApiKeys.query()\
855 855 .filter(UserApiKeys.api_key == auth_token)\
856 856 .filter(or_(UserApiKeys.expires == -1,
857 857 UserApiKeys.expires >= time.time()))
858 858 if cache:
859 859 q = q.options(
860 860 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
861 861
862 862 match = q.first()
863 863 if match:
864 864 return match.user
865 865
866 866 @classmethod
867 867 def get_by_email(cls, email, case_insensitive=False, cache=False):
868 868
869 869 if case_insensitive:
870 870 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
871 871
872 872 else:
873 873 q = cls.query().filter(cls.email == email)
874 874
875 875 email_key = _hash_key(email)
876 876 if cache:
877 877 q = q.options(
878 878 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
879 879
880 880 ret = q.scalar()
881 881 if ret is None:
882 882 q = UserEmailMap.query()
883 883 # try fetching in alternate email map
884 884 if case_insensitive:
885 885 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
886 886 else:
887 887 q = q.filter(UserEmailMap.email == email)
888 888 q = q.options(joinedload(UserEmailMap.user))
889 889 if cache:
890 890 q = q.options(
891 891 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
892 892 ret = getattr(q.scalar(), 'user', None)
893 893
894 894 return ret
895 895
896 896 @classmethod
897 897 def get_from_cs_author(cls, author):
898 898 """
899 899 Tries to get User objects out of commit author string
900 900
901 901 :param author:
902 902 """
903 903 from rhodecode.lib.helpers import email, author_name
904 904 # Valid email in the attribute passed, see if they're in the system
905 905 _email = email(author)
906 906 if _email:
907 907 user = cls.get_by_email(_email, case_insensitive=True)
908 908 if user:
909 909 return user
910 910 # Maybe we can match by username?
911 911 _author = author_name(author)
912 912 user = cls.get_by_username(_author, case_insensitive=True)
913 913 if user:
914 914 return user
915 915
916 916 def update_userdata(self, **kwargs):
917 917 usr = self
918 918 old = usr.user_data
919 919 old.update(**kwargs)
920 920 usr.user_data = old
921 921 Session().add(usr)
922 922 log.debug('updated userdata with ', kwargs)
923 923
924 924 def update_lastlogin(self):
925 925 """Update user lastlogin"""
926 926 self.last_login = datetime.datetime.now()
927 927 Session().add(self)
928 928 log.debug('updated user %s lastlogin', self.username)
929 929
930 930 def update_lastactivity(self):
931 931 """Update user lastactivity"""
932 932 self.last_activity = datetime.datetime.now()
933 933 Session().add(self)
934 934 log.debug('updated user `%s` last activity', self.username)
935 935
936 936 def update_password(self, new_password):
937 937 from rhodecode.lib.auth import get_crypt_password
938 938
939 939 self.password = get_crypt_password(new_password)
940 940 Session().add(self)
941 941
942 942 @classmethod
943 943 def get_first_super_admin(cls):
944 944 user = User.query().filter(User.admin == true()).first()
945 945 if user is None:
946 946 raise Exception('FATAL: Missing administrative account!')
947 947 return user
948 948
949 949 @classmethod
950 950 def get_all_super_admins(cls):
951 951 """
952 952 Returns all admin accounts sorted by username
953 953 """
954 954 return User.query().filter(User.admin == true())\
955 955 .order_by(User.username.asc()).all()
956 956
957 957 @classmethod
958 958 def get_default_user(cls, cache=False, refresh=False):
959 959 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
960 960 if user is None:
961 961 raise Exception('FATAL: Missing default account!')
962 962 if refresh:
963 963 # The default user might be based on outdated state which
964 964 # has been loaded from the cache.
965 965 # A call to refresh() ensures that the
966 966 # latest state from the database is used.
967 967 Session().refresh(user)
968 968 return user
969 969
970 970 def _get_default_perms(self, user, suffix=''):
971 971 from rhodecode.model.permission import PermissionModel
972 972 return PermissionModel().get_default_perms(user.user_perms, suffix)
973 973
974 974 def get_default_perms(self, suffix=''):
975 975 return self._get_default_perms(self, suffix)
976 976
977 977 def get_api_data(self, include_secrets=False, details='full'):
978 978 """
979 979 Common function for generating user related data for API
980 980
981 981 :param include_secrets: By default secrets in the API data will be replaced
982 982 by a placeholder value to prevent exposing this data by accident. In case
983 983 this data shall be exposed, set this flag to ``True``.
984 984
985 985 :param details: details can be 'basic|full' basic gives only a subset of
986 986 the available user information that includes user_id, name and emails.
987 987 """
988 988 user = self
989 989 user_data = self.user_data
990 990 data = {
991 991 'user_id': user.user_id,
992 992 'username': user.username,
993 993 'firstname': user.name,
994 994 'lastname': user.lastname,
995 995 'email': user.email,
996 996 'emails': user.emails,
997 997 }
998 998 if details == 'basic':
999 999 return data
1000 1000
1001 1001 auth_token_length = 40
1002 1002 auth_token_replacement = '*' * auth_token_length
1003 1003
1004 1004 extras = {
1005 1005 'auth_tokens': [auth_token_replacement],
1006 1006 'active': user.active,
1007 1007 'admin': user.admin,
1008 1008 'extern_type': user.extern_type,
1009 1009 'extern_name': user.extern_name,
1010 1010 'last_login': user.last_login,
1011 1011 'last_activity': user.last_activity,
1012 1012 'ip_addresses': user.ip_addresses,
1013 1013 'language': user_data.get('language')
1014 1014 }
1015 1015 data.update(extras)
1016 1016
1017 1017 if include_secrets:
1018 1018 data['auth_tokens'] = user.auth_tokens
1019 1019 return data
1020 1020
1021 1021 def __json__(self):
1022 1022 data = {
1023 1023 'full_name': self.full_name,
1024 1024 'full_name_or_username': self.full_name_or_username,
1025 1025 'short_contact': self.short_contact,
1026 1026 'full_contact': self.full_contact,
1027 1027 }
1028 1028 data.update(self.get_api_data())
1029 1029 return data
1030 1030
1031 1031
1032 1032 class UserApiKeys(Base, BaseModel):
1033 1033 __tablename__ = 'user_api_keys'
1034 1034 __table_args__ = (
1035 1035 Index('uak_api_key_idx', 'api_key', unique=True),
1036 1036 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
1037 1037 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1038 1038 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1039 1039 )
1040 1040 __mapper_args__ = {}
1041 1041
1042 1042 # ApiKey role
1043 1043 ROLE_ALL = 'token_role_all'
1044 1044 ROLE_HTTP = 'token_role_http'
1045 1045 ROLE_VCS = 'token_role_vcs'
1046 1046 ROLE_API = 'token_role_api'
1047 1047 ROLE_FEED = 'token_role_feed'
1048 1048 ROLE_PASSWORD_RESET = 'token_password_reset'
1049 1049
1050 1050 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
1051 1051
1052 1052 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1053 1053 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1054 1054 api_key = Column("api_key", String(255), nullable=False, unique=True)
1055 1055 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1056 1056 expires = Column('expires', Float(53), nullable=False)
1057 1057 role = Column('role', String(255), nullable=True)
1058 1058 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1059 1059
1060 1060 # scope columns
1061 1061 repo_id = Column(
1062 1062 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1063 1063 nullable=True, unique=None, default=None)
1064 1064 repo = relationship('Repository', lazy='joined')
1065 1065
1066 1066 repo_group_id = Column(
1067 1067 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1068 1068 nullable=True, unique=None, default=None)
1069 1069 repo_group = relationship('RepoGroup', lazy='joined')
1070 1070
1071 1071 user = relationship('User', lazy='joined')
1072 1072
1073 1073 def __unicode__(self):
1074 1074 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1075 1075
1076 1076 def __json__(self):
1077 1077 data = {
1078 1078 'auth_token': self.api_key,
1079 1079 'role': self.role,
1080 1080 'scope': self.scope_humanized,
1081 1081 'expired': self.expired
1082 1082 }
1083 1083 return data
1084 1084
1085 1085 def get_api_data(self, include_secrets=False):
1086 1086 data = self.__json__()
1087 1087 if include_secrets:
1088 1088 return data
1089 1089 else:
1090 1090 data['auth_token'] = self.token_obfuscated
1091 1091 return data
1092 1092
1093 1093 @hybrid_property
1094 1094 def description_safe(self):
1095 1095 from rhodecode.lib import helpers as h
1096 1096 return h.escape(self.description)
1097 1097
1098 1098 @property
1099 1099 def expired(self):
1100 1100 if self.expires == -1:
1101 1101 return False
1102 1102 return time.time() > self.expires
1103 1103
1104 1104 @classmethod
1105 1105 def _get_role_name(cls, role):
1106 1106 return {
1107 1107 cls.ROLE_ALL: _('all'),
1108 1108 cls.ROLE_HTTP: _('http/web interface'),
1109 1109 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1110 1110 cls.ROLE_API: _('api calls'),
1111 1111 cls.ROLE_FEED: _('feed access'),
1112 1112 }.get(role, role)
1113 1113
1114 1114 @property
1115 1115 def role_humanized(self):
1116 1116 return self._get_role_name(self.role)
1117 1117
1118 1118 def _get_scope(self):
1119 1119 if self.repo:
1120 1120 return repr(self.repo)
1121 1121 if self.repo_group:
1122 1122 return repr(self.repo_group) + ' (recursive)'
1123 1123 return 'global'
1124 1124
1125 1125 @property
1126 1126 def scope_humanized(self):
1127 1127 return self._get_scope()
1128 1128
1129 1129 @property
1130 1130 def token_obfuscated(self):
1131 1131 if self.api_key:
1132 1132 return self.api_key[:4] + "****"
1133 1133
1134 1134
1135 1135 class UserEmailMap(Base, BaseModel):
1136 1136 __tablename__ = 'user_email_map'
1137 1137 __table_args__ = (
1138 1138 Index('uem_email_idx', 'email'),
1139 1139 UniqueConstraint('email'),
1140 1140 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1141 1141 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1142 1142 )
1143 1143 __mapper_args__ = {}
1144 1144
1145 1145 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1146 1146 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1147 1147 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1148 1148 user = relationship('User', lazy='joined')
1149 1149
1150 1150 @validates('_email')
1151 1151 def validate_email(self, key, email):
1152 1152 # check if this email is not main one
1153 1153 main_email = Session().query(User).filter(User.email == email).scalar()
1154 1154 if main_email is not None:
1155 1155 raise AttributeError('email %s is present is user table' % email)
1156 1156 return email
1157 1157
1158 1158 @hybrid_property
1159 1159 def email(self):
1160 1160 return self._email
1161 1161
1162 1162 @email.setter
1163 1163 def email(self, val):
1164 1164 self._email = val.lower() if val else None
1165 1165
1166 1166
1167 1167 class UserIpMap(Base, BaseModel):
1168 1168 __tablename__ = 'user_ip_map'
1169 1169 __table_args__ = (
1170 1170 UniqueConstraint('user_id', 'ip_addr'),
1171 1171 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1172 1172 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1173 1173 )
1174 1174 __mapper_args__ = {}
1175 1175
1176 1176 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1177 1177 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1178 1178 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1179 1179 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1180 1180 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1181 1181 user = relationship('User', lazy='joined')
1182 1182
1183 1183 @hybrid_property
1184 1184 def description_safe(self):
1185 1185 from rhodecode.lib import helpers as h
1186 1186 return h.escape(self.description)
1187 1187
1188 1188 @classmethod
1189 1189 def _get_ip_range(cls, ip_addr):
1190 1190 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1191 1191 return [str(net.network_address), str(net.broadcast_address)]
1192 1192
1193 1193 def __json__(self):
1194 1194 return {
1195 1195 'ip_addr': self.ip_addr,
1196 1196 'ip_range': self._get_ip_range(self.ip_addr),
1197 1197 }
1198 1198
1199 1199 def __unicode__(self):
1200 1200 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1201 1201 self.user_id, self.ip_addr)
1202 1202
1203 1203
1204 1204 class UserSshKeys(Base, BaseModel):
1205 1205 __tablename__ = 'user_ssh_keys'
1206 1206 __table_args__ = (
1207 1207 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1208 1208
1209 1209 UniqueConstraint('ssh_key_fingerprint'),
1210 1210
1211 1211 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1212 1212 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1213 1213 )
1214 1214 __mapper_args__ = {}
1215 1215
1216 1216 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1217 1217 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1218 1218 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(255), nullable=False, unique=None, default=None)
1219 1219
1220 1220 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1221 1221
1222 1222 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1223 1223 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1224 1224 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1225 1225
1226 1226 user = relationship('User', lazy='joined')
1227 1227
1228 1228 def __json__(self):
1229 1229 data = {
1230 1230 'ssh_fingerprint': self.ssh_key_fingerprint,
1231 1231 'description': self.description,
1232 1232 'created_on': self.created_on
1233 1233 }
1234 1234 return data
1235 1235
1236 1236 def get_api_data(self):
1237 1237 data = self.__json__()
1238 1238 return data
1239 1239
1240 1240
1241 1241 class UserLog(Base, BaseModel):
1242 1242 __tablename__ = 'user_logs'
1243 1243 __table_args__ = (
1244 1244 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1245 1245 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1246 1246 )
1247 1247 VERSION_1 = 'v1'
1248 1248 VERSION_2 = 'v2'
1249 1249 VERSIONS = [VERSION_1, VERSION_2]
1250 1250
1251 1251 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1252 1252 user_id = Column("user_id", Integer(), ForeignKey('users.user_id',ondelete='SET NULL'), nullable=True, unique=None, default=None)
1253 1253 username = Column("username", String(255), nullable=True, unique=None, default=None)
1254 1254 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id', ondelete='SET NULL'), nullable=True, unique=None, default=None)
1255 1255 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1256 1256 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1257 1257 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1258 1258 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1259 1259
1260 1260 version = Column("version", String(255), nullable=True, default=VERSION_1)
1261 1261 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1262 1262 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=LONGTEXT()))))
1263 1263
1264 1264 def __unicode__(self):
1265 1265 return u"<%s('id:%s:%s')>" % (
1266 1266 self.__class__.__name__, self.repository_name, self.action)
1267 1267
1268 1268 def __json__(self):
1269 1269 return {
1270 1270 'user_id': self.user_id,
1271 1271 'username': self.username,
1272 1272 'repository_id': self.repository_id,
1273 1273 'repository_name': self.repository_name,
1274 1274 'user_ip': self.user_ip,
1275 1275 'action_date': self.action_date,
1276 1276 'action': self.action,
1277 1277 }
1278 1278
1279 1279 @hybrid_property
1280 1280 def entry_id(self):
1281 1281 return self.user_log_id
1282 1282
1283 1283 @property
1284 1284 def action_as_day(self):
1285 1285 return datetime.date(*self.action_date.timetuple()[:3])
1286 1286
1287 1287 user = relationship('User')
1288 1288 repository = relationship('Repository', cascade='')
1289 1289
1290 1290
1291 1291 class UserGroup(Base, BaseModel):
1292 1292 __tablename__ = 'users_groups'
1293 1293 __table_args__ = (
1294 1294 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1295 1295 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1296 1296 )
1297 1297
1298 1298 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1299 1299 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1300 1300 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1301 1301 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1302 1302 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1303 1303 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1304 1304 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1305 1305 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1306 1306
1307 1307 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1308 1308 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1309 1309 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1310 1310 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1311 1311 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1312 1312 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1313 1313
1314 1314 user_group_review_rules = relationship('RepoReviewRuleUserGroup', cascade='all')
1315 1315 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1316 1316
1317 1317 @classmethod
1318 1318 def _load_group_data(cls, column):
1319 1319 if not column:
1320 1320 return {}
1321 1321
1322 1322 try:
1323 1323 return json.loads(column) or {}
1324 1324 except TypeError:
1325 1325 return {}
1326 1326
1327 1327 @hybrid_property
1328 1328 def description_safe(self):
1329 1329 from rhodecode.lib import helpers as h
1330 1330 return h.escape(self.user_group_description)
1331 1331
1332 1332 @hybrid_property
1333 1333 def group_data(self):
1334 1334 return self._load_group_data(self._group_data)
1335 1335
1336 1336 @group_data.expression
1337 1337 def group_data(self, **kwargs):
1338 1338 return self._group_data
1339 1339
1340 1340 @group_data.setter
1341 1341 def group_data(self, val):
1342 1342 try:
1343 1343 self._group_data = json.dumps(val)
1344 1344 except Exception:
1345 1345 log.error(traceback.format_exc())
1346 1346
1347 1347 def __unicode__(self):
1348 1348 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1349 1349 self.users_group_id,
1350 1350 self.users_group_name)
1351 1351
1352 1352 @classmethod
1353 1353 def get_by_group_name(cls, group_name, cache=False,
1354 1354 case_insensitive=False):
1355 1355 if case_insensitive:
1356 1356 q = cls.query().filter(func.lower(cls.users_group_name) ==
1357 1357 func.lower(group_name))
1358 1358
1359 1359 else:
1360 1360 q = cls.query().filter(cls.users_group_name == group_name)
1361 1361 if cache:
1362 1362 q = q.options(
1363 1363 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1364 1364 return q.scalar()
1365 1365
1366 1366 @classmethod
1367 1367 def get(cls, user_group_id, cache=False):
1368 1368 if not user_group_id:
1369 1369 return
1370 1370
1371 1371 user_group = cls.query()
1372 1372 if cache:
1373 1373 user_group = user_group.options(
1374 1374 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1375 1375 return user_group.get(user_group_id)
1376 1376
1377 1377 def permissions(self, with_admins=True, with_owner=True):
1378 1378 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1379 1379 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1380 1380 joinedload(UserUserGroupToPerm.user),
1381 1381 joinedload(UserUserGroupToPerm.permission),)
1382 1382
1383 1383 # get owners and admins and permissions. We do a trick of re-writing
1384 1384 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1385 1385 # has a global reference and changing one object propagates to all
1386 1386 # others. This means if admin is also an owner admin_row that change
1387 1387 # would propagate to both objects
1388 1388 perm_rows = []
1389 1389 for _usr in q.all():
1390 1390 usr = AttributeDict(_usr.user.get_dict())
1391 1391 usr.permission = _usr.permission.permission_name
1392 1392 perm_rows.append(usr)
1393 1393
1394 1394 # filter the perm rows by 'default' first and then sort them by
1395 1395 # admin,write,read,none permissions sorted again alphabetically in
1396 1396 # each group
1397 1397 perm_rows = sorted(perm_rows, key=display_user_sort)
1398 1398
1399 1399 _admin_perm = 'usergroup.admin'
1400 1400 owner_row = []
1401 1401 if with_owner:
1402 1402 usr = AttributeDict(self.user.get_dict())
1403 1403 usr.owner_row = True
1404 1404 usr.permission = _admin_perm
1405 1405 owner_row.append(usr)
1406 1406
1407 1407 super_admin_rows = []
1408 1408 if with_admins:
1409 1409 for usr in User.get_all_super_admins():
1410 1410 # if this admin is also owner, don't double the record
1411 1411 if usr.user_id == owner_row[0].user_id:
1412 1412 owner_row[0].admin_row = True
1413 1413 else:
1414 1414 usr = AttributeDict(usr.get_dict())
1415 1415 usr.admin_row = True
1416 1416 usr.permission = _admin_perm
1417 1417 super_admin_rows.append(usr)
1418 1418
1419 1419 return super_admin_rows + owner_row + perm_rows
1420 1420
1421 1421 def permission_user_groups(self):
1422 1422 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1423 1423 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1424 1424 joinedload(UserGroupUserGroupToPerm.target_user_group),
1425 1425 joinedload(UserGroupUserGroupToPerm.permission),)
1426 1426
1427 1427 perm_rows = []
1428 1428 for _user_group in q.all():
1429 1429 usr = AttributeDict(_user_group.user_group.get_dict())
1430 1430 usr.permission = _user_group.permission.permission_name
1431 1431 perm_rows.append(usr)
1432 1432
1433 1433 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1434 1434 return perm_rows
1435 1435
1436 1436 def _get_default_perms(self, user_group, suffix=''):
1437 1437 from rhodecode.model.permission import PermissionModel
1438 1438 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1439 1439
1440 1440 def get_default_perms(self, suffix=''):
1441 1441 return self._get_default_perms(self, suffix)
1442 1442
1443 1443 def get_api_data(self, with_group_members=True, include_secrets=False):
1444 1444 """
1445 1445 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1446 1446 basically forwarded.
1447 1447
1448 1448 """
1449 1449 user_group = self
1450 1450 data = {
1451 1451 'users_group_id': user_group.users_group_id,
1452 1452 'group_name': user_group.users_group_name,
1453 1453 'group_description': user_group.user_group_description,
1454 1454 'active': user_group.users_group_active,
1455 1455 'owner': user_group.user.username,
1456 1456 'owner_email': user_group.user.email,
1457 1457 }
1458 1458
1459 1459 if with_group_members:
1460 1460 users = []
1461 1461 for user in user_group.members:
1462 1462 user = user.user
1463 1463 users.append(user.get_api_data(include_secrets=include_secrets))
1464 1464 data['users'] = users
1465 1465
1466 1466 return data
1467 1467
1468 1468
1469 1469 class UserGroupMember(Base, BaseModel):
1470 1470 __tablename__ = 'users_groups_members'
1471 1471 __table_args__ = (
1472 1472 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1473 1473 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1474 1474 )
1475 1475
1476 1476 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1477 1477 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1478 1478 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1479 1479
1480 1480 user = relationship('User', lazy='joined')
1481 1481 users_group = relationship('UserGroup')
1482 1482
1483 1483 def __init__(self, gr_id='', u_id=''):
1484 1484 self.users_group_id = gr_id
1485 1485 self.user_id = u_id
1486 1486
1487 1487
1488 1488 class RepositoryField(Base, BaseModel):
1489 1489 __tablename__ = 'repositories_fields'
1490 1490 __table_args__ = (
1491 1491 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1492 1492 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1493 1493 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1494 1494 )
1495 1495 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1496 1496
1497 1497 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1498 1498 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1499 1499 field_key = Column("field_key", String(250))
1500 1500 field_label = Column("field_label", String(1024), nullable=False)
1501 1501 field_value = Column("field_value", String(10000), nullable=False)
1502 1502 field_desc = Column("field_desc", String(1024), nullable=False)
1503 1503 field_type = Column("field_type", String(255), nullable=False, unique=None)
1504 1504 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1505 1505
1506 1506 repository = relationship('Repository')
1507 1507
1508 1508 @property
1509 1509 def field_key_prefixed(self):
1510 1510 return 'ex_%s' % self.field_key
1511 1511
1512 1512 @classmethod
1513 1513 def un_prefix_key(cls, key):
1514 1514 if key.startswith(cls.PREFIX):
1515 1515 return key[len(cls.PREFIX):]
1516 1516 return key
1517 1517
1518 1518 @classmethod
1519 1519 def get_by_key_name(cls, key, repo):
1520 1520 row = cls.query()\
1521 1521 .filter(cls.repository == repo)\
1522 1522 .filter(cls.field_key == key).scalar()
1523 1523 return row
1524 1524
1525 1525
1526 1526 class Repository(Base, BaseModel):
1527 1527 __tablename__ = 'repositories'
1528 1528 __table_args__ = (
1529 1529 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1530 1530 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1531 1531 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1532 1532 )
1533 1533 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1534 1534 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1535 DEFAULT_CLONE_URI_SSH = 'ssh://{sys_user}@{hostname}/{repo}'
1535 1536
1536 1537 STATE_CREATED = 'repo_state_created'
1537 1538 STATE_PENDING = 'repo_state_pending'
1538 1539 STATE_ERROR = 'repo_state_error'
1539 1540
1540 1541 LOCK_AUTOMATIC = 'lock_auto'
1541 1542 LOCK_API = 'lock_api'
1542 1543 LOCK_WEB = 'lock_web'
1543 1544 LOCK_PULL = 'lock_pull'
1544 1545
1545 1546 NAME_SEP = URL_SEP
1546 1547
1547 1548 repo_id = Column(
1548 1549 "repo_id", Integer(), nullable=False, unique=True, default=None,
1549 1550 primary_key=True)
1550 1551 _repo_name = Column(
1551 1552 "repo_name", Text(), nullable=False, default=None)
1552 1553 _repo_name_hash = Column(
1553 1554 "repo_name_hash", String(255), nullable=False, unique=True)
1554 1555 repo_state = Column("repo_state", String(255), nullable=True)
1555 1556
1556 1557 clone_uri = Column(
1557 1558 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1558 1559 default=None)
1559 1560 repo_type = Column(
1560 1561 "repo_type", String(255), nullable=False, unique=False, default=None)
1561 1562 user_id = Column(
1562 1563 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1563 1564 unique=False, default=None)
1564 1565 private = Column(
1565 1566 "private", Boolean(), nullable=True, unique=None, default=None)
1566 1567 enable_statistics = Column(
1567 1568 "statistics", Boolean(), nullable=True, unique=None, default=True)
1568 1569 enable_downloads = Column(
1569 1570 "downloads", Boolean(), nullable=True, unique=None, default=True)
1570 1571 description = Column(
1571 1572 "description", String(10000), nullable=True, unique=None, default=None)
1572 1573 created_on = Column(
1573 1574 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1574 1575 default=datetime.datetime.now)
1575 1576 updated_on = Column(
1576 1577 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1577 1578 default=datetime.datetime.now)
1578 1579 _landing_revision = Column(
1579 1580 "landing_revision", String(255), nullable=False, unique=False,
1580 1581 default=None)
1581 1582 enable_locking = Column(
1582 1583 "enable_locking", Boolean(), nullable=False, unique=None,
1583 1584 default=False)
1584 1585 _locked = Column(
1585 1586 "locked", String(255), nullable=True, unique=False, default=None)
1586 1587 _changeset_cache = Column(
1587 1588 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1588 1589
1589 1590 fork_id = Column(
1590 1591 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1591 1592 nullable=True, unique=False, default=None)
1592 1593 group_id = Column(
1593 1594 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1594 1595 unique=False, default=None)
1595 1596
1596 1597 user = relationship('User', lazy='joined')
1597 1598 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1598 1599 group = relationship('RepoGroup', lazy='joined')
1599 1600 repo_to_perm = relationship(
1600 1601 'UserRepoToPerm', cascade='all',
1601 1602 order_by='UserRepoToPerm.repo_to_perm_id')
1602 1603 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1603 1604 stats = relationship('Statistics', cascade='all', uselist=False)
1604 1605
1605 1606 followers = relationship(
1606 1607 'UserFollowing',
1607 1608 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1608 1609 cascade='all')
1609 1610 extra_fields = relationship(
1610 1611 'RepositoryField', cascade="all, delete, delete-orphan")
1611 1612 logs = relationship('UserLog')
1612 1613 comments = relationship(
1613 1614 'ChangesetComment', cascade="all, delete, delete-orphan")
1614 1615 pull_requests_source = relationship(
1615 1616 'PullRequest',
1616 1617 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1617 1618 cascade="all, delete, delete-orphan")
1618 1619 pull_requests_target = relationship(
1619 1620 'PullRequest',
1620 1621 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1621 1622 cascade="all, delete, delete-orphan")
1622 1623 ui = relationship('RepoRhodeCodeUi', cascade="all")
1623 1624 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1624 1625 integrations = relationship('Integration',
1625 1626 cascade="all, delete, delete-orphan")
1626 1627
1627 1628 scoped_tokens = relationship('UserApiKeys', cascade="all")
1628 1629
1629 1630 def __unicode__(self):
1630 1631 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1631 1632 safe_unicode(self.repo_name))
1632 1633
1633 1634 @hybrid_property
1634 1635 def description_safe(self):
1635 1636 from rhodecode.lib import helpers as h
1636 1637 return h.escape(self.description)
1637 1638
1638 1639 @hybrid_property
1639 1640 def landing_rev(self):
1640 1641 # always should return [rev_type, rev]
1641 1642 if self._landing_revision:
1642 1643 _rev_info = self._landing_revision.split(':')
1643 1644 if len(_rev_info) < 2:
1644 1645 _rev_info.insert(0, 'rev')
1645 1646 return [_rev_info[0], _rev_info[1]]
1646 1647 return [None, None]
1647 1648
1648 1649 @landing_rev.setter
1649 1650 def landing_rev(self, val):
1650 1651 if ':' not in val:
1651 1652 raise ValueError('value must be delimited with `:` and consist '
1652 1653 'of <rev_type>:<rev>, got %s instead' % val)
1653 1654 self._landing_revision = val
1654 1655
1655 1656 @hybrid_property
1656 1657 def locked(self):
1657 1658 if self._locked:
1658 1659 user_id, timelocked, reason = self._locked.split(':')
1659 1660 lock_values = int(user_id), timelocked, reason
1660 1661 else:
1661 1662 lock_values = [None, None, None]
1662 1663 return lock_values
1663 1664
1664 1665 @locked.setter
1665 1666 def locked(self, val):
1666 1667 if val and isinstance(val, (list, tuple)):
1667 1668 self._locked = ':'.join(map(str, val))
1668 1669 else:
1669 1670 self._locked = None
1670 1671
1671 1672 @hybrid_property
1672 1673 def changeset_cache(self):
1673 1674 from rhodecode.lib.vcs.backends.base import EmptyCommit
1674 1675 dummy = EmptyCommit().__json__()
1675 1676 if not self._changeset_cache:
1676 1677 return dummy
1677 1678 try:
1678 1679 return json.loads(self._changeset_cache)
1679 1680 except TypeError:
1680 1681 return dummy
1681 1682 except Exception:
1682 1683 log.error(traceback.format_exc())
1683 1684 return dummy
1684 1685
1685 1686 @changeset_cache.setter
1686 1687 def changeset_cache(self, val):
1687 1688 try:
1688 1689 self._changeset_cache = json.dumps(val)
1689 1690 except Exception:
1690 1691 log.error(traceback.format_exc())
1691 1692
1692 1693 @hybrid_property
1693 1694 def repo_name(self):
1694 1695 return self._repo_name
1695 1696
1696 1697 @repo_name.setter
1697 1698 def repo_name(self, value):
1698 1699 self._repo_name = value
1699 1700 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1700 1701
1701 1702 @classmethod
1702 1703 def normalize_repo_name(cls, repo_name):
1703 1704 """
1704 1705 Normalizes os specific repo_name to the format internally stored inside
1705 1706 database using URL_SEP
1706 1707
1707 1708 :param cls:
1708 1709 :param repo_name:
1709 1710 """
1710 1711 return cls.NAME_SEP.join(repo_name.split(os.sep))
1711 1712
1712 1713 @classmethod
1713 1714 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1714 1715 session = Session()
1715 1716 q = session.query(cls).filter(cls.repo_name == repo_name)
1716 1717
1717 1718 if cache:
1718 1719 if identity_cache:
1719 1720 val = cls.identity_cache(session, 'repo_name', repo_name)
1720 1721 if val:
1721 1722 return val
1722 1723 else:
1723 1724 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1724 1725 q = q.options(
1725 1726 FromCache("sql_cache_short", cache_key))
1726 1727
1727 1728 return q.scalar()
1728 1729
1729 1730 @classmethod
1730 1731 def get_by_id_or_repo_name(cls, repoid):
1731 1732 if isinstance(repoid, (int, long)):
1732 1733 try:
1733 1734 repo = cls.get(repoid)
1734 1735 except ValueError:
1735 1736 repo = None
1736 1737 else:
1737 1738 repo = cls.get_by_repo_name(repoid)
1738 1739 return repo
1739 1740
1740 1741 @classmethod
1741 1742 def get_by_full_path(cls, repo_full_path):
1742 1743 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1743 1744 repo_name = cls.normalize_repo_name(repo_name)
1744 1745 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1745 1746
1746 1747 @classmethod
1747 1748 def get_repo_forks(cls, repo_id):
1748 1749 return cls.query().filter(Repository.fork_id == repo_id)
1749 1750
1750 1751 @classmethod
1751 1752 def base_path(cls):
1752 1753 """
1753 1754 Returns base path when all repos are stored
1754 1755
1755 1756 :param cls:
1756 1757 """
1757 1758 q = Session().query(RhodeCodeUi)\
1758 1759 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1759 1760 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1760 1761 return q.one().ui_value
1761 1762
1762 1763 @classmethod
1763 1764 def is_valid(cls, repo_name):
1764 1765 """
1765 1766 returns True if given repo name is a valid filesystem repository
1766 1767
1767 1768 :param cls:
1768 1769 :param repo_name:
1769 1770 """
1770 1771 from rhodecode.lib.utils import is_valid_repo
1771 1772
1772 1773 return is_valid_repo(repo_name, cls.base_path())
1773 1774
1774 1775 @classmethod
1775 1776 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1776 1777 case_insensitive=True):
1777 1778 q = Repository.query()
1778 1779
1779 1780 if not isinstance(user_id, Optional):
1780 1781 q = q.filter(Repository.user_id == user_id)
1781 1782
1782 1783 if not isinstance(group_id, Optional):
1783 1784 q = q.filter(Repository.group_id == group_id)
1784 1785
1785 1786 if case_insensitive:
1786 1787 q = q.order_by(func.lower(Repository.repo_name))
1787 1788 else:
1788 1789 q = q.order_by(Repository.repo_name)
1789 1790 return q.all()
1790 1791
1791 1792 @property
1792 1793 def forks(self):
1793 1794 """
1794 1795 Return forks of this repo
1795 1796 """
1796 1797 return Repository.get_repo_forks(self.repo_id)
1797 1798
1798 1799 @property
1799 1800 def parent(self):
1800 1801 """
1801 1802 Returns fork parent
1802 1803 """
1803 1804 return self.fork
1804 1805
1805 1806 @property
1806 1807 def just_name(self):
1807 1808 return self.repo_name.split(self.NAME_SEP)[-1]
1808 1809
1809 1810 @property
1810 1811 def groups_with_parents(self):
1811 1812 groups = []
1812 1813 if self.group is None:
1813 1814 return groups
1814 1815
1815 1816 cur_gr = self.group
1816 1817 groups.insert(0, cur_gr)
1817 1818 while 1:
1818 1819 gr = getattr(cur_gr, 'parent_group', None)
1819 1820 cur_gr = cur_gr.parent_group
1820 1821 if gr is None:
1821 1822 break
1822 1823 groups.insert(0, gr)
1823 1824
1824 1825 return groups
1825 1826
1826 1827 @property
1827 1828 def groups_and_repo(self):
1828 1829 return self.groups_with_parents, self
1829 1830
1830 1831 @LazyProperty
1831 1832 def repo_path(self):
1832 1833 """
1833 1834 Returns base full path for that repository means where it actually
1834 1835 exists on a filesystem
1835 1836 """
1836 1837 q = Session().query(RhodeCodeUi).filter(
1837 1838 RhodeCodeUi.ui_key == self.NAME_SEP)
1838 1839 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1839 1840 return q.one().ui_value
1840 1841
1841 1842 @property
1842 1843 def repo_full_path(self):
1843 1844 p = [self.repo_path]
1844 1845 # we need to split the name by / since this is how we store the
1845 1846 # names in the database, but that eventually needs to be converted
1846 1847 # into a valid system path
1847 1848 p += self.repo_name.split(self.NAME_SEP)
1848 1849 return os.path.join(*map(safe_unicode, p))
1849 1850
1850 1851 @property
1851 1852 def cache_keys(self):
1852 1853 """
1853 1854 Returns associated cache keys for that repo
1854 1855 """
1855 1856 return CacheKey.query()\
1856 1857 .filter(CacheKey.cache_args == self.repo_name)\
1857 1858 .order_by(CacheKey.cache_key)\
1858 1859 .all()
1859 1860
1860 1861 def get_new_name(self, repo_name):
1861 1862 """
1862 1863 returns new full repository name based on assigned group and new new
1863 1864
1864 1865 :param group_name:
1865 1866 """
1866 1867 path_prefix = self.group.full_path_splitted if self.group else []
1867 1868 return self.NAME_SEP.join(path_prefix + [repo_name])
1868 1869
1869 1870 @property
1870 1871 def _config(self):
1871 1872 """
1872 1873 Returns db based config object.
1873 1874 """
1874 1875 from rhodecode.lib.utils import make_db_config
1875 1876 return make_db_config(clear_session=False, repo=self)
1876 1877
1877 1878 def permissions(self, with_admins=True, with_owner=True):
1878 1879 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1879 1880 q = q.options(joinedload(UserRepoToPerm.repository),
1880 1881 joinedload(UserRepoToPerm.user),
1881 1882 joinedload(UserRepoToPerm.permission),)
1882 1883
1883 1884 # get owners and admins and permissions. We do a trick of re-writing
1884 1885 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1885 1886 # has a global reference and changing one object propagates to all
1886 1887 # others. This means if admin is also an owner admin_row that change
1887 1888 # would propagate to both objects
1888 1889 perm_rows = []
1889 1890 for _usr in q.all():
1890 1891 usr = AttributeDict(_usr.user.get_dict())
1891 1892 usr.permission = _usr.permission.permission_name
1892 1893 perm_rows.append(usr)
1893 1894
1894 1895 # filter the perm rows by 'default' first and then sort them by
1895 1896 # admin,write,read,none permissions sorted again alphabetically in
1896 1897 # each group
1897 1898 perm_rows = sorted(perm_rows, key=display_user_sort)
1898 1899
1899 1900 _admin_perm = 'repository.admin'
1900 1901 owner_row = []
1901 1902 if with_owner:
1902 1903 usr = AttributeDict(self.user.get_dict())
1903 1904 usr.owner_row = True
1904 1905 usr.permission = _admin_perm
1905 1906 owner_row.append(usr)
1906 1907
1907 1908 super_admin_rows = []
1908 1909 if with_admins:
1909 1910 for usr in User.get_all_super_admins():
1910 1911 # if this admin is also owner, don't double the record
1911 1912 if usr.user_id == owner_row[0].user_id:
1912 1913 owner_row[0].admin_row = True
1913 1914 else:
1914 1915 usr = AttributeDict(usr.get_dict())
1915 1916 usr.admin_row = True
1916 1917 usr.permission = _admin_perm
1917 1918 super_admin_rows.append(usr)
1918 1919
1919 1920 return super_admin_rows + owner_row + perm_rows
1920 1921
1921 1922 def permission_user_groups(self):
1922 1923 q = UserGroupRepoToPerm.query().filter(
1923 1924 UserGroupRepoToPerm.repository == self)
1924 1925 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1925 1926 joinedload(UserGroupRepoToPerm.users_group),
1926 1927 joinedload(UserGroupRepoToPerm.permission),)
1927 1928
1928 1929 perm_rows = []
1929 1930 for _user_group in q.all():
1930 1931 usr = AttributeDict(_user_group.users_group.get_dict())
1931 1932 usr.permission = _user_group.permission.permission_name
1932 1933 perm_rows.append(usr)
1933 1934
1934 1935 perm_rows = sorted(perm_rows, key=display_user_group_sort)
1935 1936 return perm_rows
1936 1937
1937 1938 def get_api_data(self, include_secrets=False):
1938 1939 """
1939 1940 Common function for generating repo api data
1940 1941
1941 1942 :param include_secrets: See :meth:`User.get_api_data`.
1942 1943
1943 1944 """
1944 1945 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1945 1946 # move this methods on models level.
1946 1947 from rhodecode.model.settings import SettingsModel
1947 1948 from rhodecode.model.repo import RepoModel
1948 1949
1949 1950 repo = self
1950 1951 _user_id, _time, _reason = self.locked
1951 1952
1952 1953 data = {
1953 1954 'repo_id': repo.repo_id,
1954 1955 'repo_name': repo.repo_name,
1955 1956 'repo_type': repo.repo_type,
1956 1957 'clone_uri': repo.clone_uri or '',
1957 1958 'url': RepoModel().get_url(self),
1958 1959 'private': repo.private,
1959 1960 'created_on': repo.created_on,
1960 1961 'description': repo.description_safe,
1961 1962 'landing_rev': repo.landing_rev,
1962 1963 'owner': repo.user.username,
1963 1964 'fork_of': repo.fork.repo_name if repo.fork else None,
1964 1965 'fork_of_id': repo.fork.repo_id if repo.fork else None,
1965 1966 'enable_statistics': repo.enable_statistics,
1966 1967 'enable_locking': repo.enable_locking,
1967 1968 'enable_downloads': repo.enable_downloads,
1968 1969 'last_changeset': repo.changeset_cache,
1969 1970 'locked_by': User.get(_user_id).get_api_data(
1970 1971 include_secrets=include_secrets) if _user_id else None,
1971 1972 'locked_date': time_to_datetime(_time) if _time else None,
1972 1973 'lock_reason': _reason if _reason else None,
1973 1974 }
1974 1975
1975 1976 # TODO: mikhail: should be per-repo settings here
1976 1977 rc_config = SettingsModel().get_all_settings()
1977 1978 repository_fields = str2bool(
1978 1979 rc_config.get('rhodecode_repository_fields'))
1979 1980 if repository_fields:
1980 1981 for f in self.extra_fields:
1981 1982 data[f.field_key_prefixed] = f.field_value
1982 1983
1983 1984 return data
1984 1985
1985 1986 @classmethod
1986 1987 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1987 1988 if not lock_time:
1988 1989 lock_time = time.time()
1989 1990 if not lock_reason:
1990 1991 lock_reason = cls.LOCK_AUTOMATIC
1991 1992 repo.locked = [user_id, lock_time, lock_reason]
1992 1993 Session().add(repo)
1993 1994 Session().commit()
1994 1995
1995 1996 @classmethod
1996 1997 def unlock(cls, repo):
1997 1998 repo.locked = None
1998 1999 Session().add(repo)
1999 2000 Session().commit()
2000 2001
2001 2002 @classmethod
2002 2003 def getlock(cls, repo):
2003 2004 return repo.locked
2004 2005
2005 2006 def is_user_lock(self, user_id):
2006 2007 if self.lock[0]:
2007 2008 lock_user_id = safe_int(self.lock[0])
2008 2009 user_id = safe_int(user_id)
2009 2010 # both are ints, and they are equal
2010 2011 return all([lock_user_id, user_id]) and lock_user_id == user_id
2011 2012
2012 2013 return False
2013 2014
2014 2015 def get_locking_state(self, action, user_id, only_when_enabled=True):
2015 2016 """
2016 2017 Checks locking on this repository, if locking is enabled and lock is
2017 2018 present returns a tuple of make_lock, locked, locked_by.
2018 2019 make_lock can have 3 states None (do nothing) True, make lock
2019 2020 False release lock, This value is later propagated to hooks, which
2020 2021 do the locking. Think about this as signals passed to hooks what to do.
2021 2022
2022 2023 """
2023 2024 # TODO: johbo: This is part of the business logic and should be moved
2024 2025 # into the RepositoryModel.
2025 2026
2026 2027 if action not in ('push', 'pull'):
2027 2028 raise ValueError("Invalid action value: %s" % repr(action))
2028 2029
2029 2030 # defines if locked error should be thrown to user
2030 2031 currently_locked = False
2031 2032 # defines if new lock should be made, tri-state
2032 2033 make_lock = None
2033 2034 repo = self
2034 2035 user = User.get(user_id)
2035 2036
2036 2037 lock_info = repo.locked
2037 2038
2038 2039 if repo and (repo.enable_locking or not only_when_enabled):
2039 2040 if action == 'push':
2040 2041 # check if it's already locked !, if it is compare users
2041 2042 locked_by_user_id = lock_info[0]
2042 2043 if user.user_id == locked_by_user_id:
2043 2044 log.debug(
2044 2045 'Got `push` action from user %s, now unlocking', user)
2045 2046 # unlock if we have push from user who locked
2046 2047 make_lock = False
2047 2048 else:
2048 2049 # we're not the same user who locked, ban with
2049 2050 # code defined in settings (default is 423 HTTP Locked) !
2050 2051 log.debug('Repo %s is currently locked by %s', repo, user)
2051 2052 currently_locked = True
2052 2053 elif action == 'pull':
2053 2054 # [0] user [1] date
2054 2055 if lock_info[0] and lock_info[1]:
2055 2056 log.debug('Repo %s is currently locked by %s', repo, user)
2056 2057 currently_locked = True
2057 2058 else:
2058 2059 log.debug('Setting lock on repo %s by %s', repo, user)
2059 2060 make_lock = True
2060 2061
2061 2062 else:
2062 2063 log.debug('Repository %s do not have locking enabled', repo)
2063 2064
2064 2065 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
2065 2066 make_lock, currently_locked, lock_info)
2066 2067
2067 2068 from rhodecode.lib.auth import HasRepoPermissionAny
2068 2069 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
2069 2070 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
2070 2071 # if we don't have at least write permission we cannot make a lock
2071 2072 log.debug('lock state reset back to FALSE due to lack '
2072 2073 'of at least read permission')
2073 2074 make_lock = False
2074 2075
2075 2076 return make_lock, currently_locked, lock_info
2076 2077
2077 2078 @property
2078 2079 def last_db_change(self):
2079 2080 return self.updated_on
2080 2081
2081 2082 @property
2082 2083 def clone_uri_hidden(self):
2083 2084 clone_uri = self.clone_uri
2084 2085 if clone_uri:
2085 2086 import urlobject
2086 2087 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2087 2088 if url_obj.password:
2088 2089 clone_uri = url_obj.with_password('*****')
2089 2090 return clone_uri
2090 2091
2091 2092 def clone_url(self, **override):
2092 2093 from rhodecode.model.settings import SettingsModel
2093 2094
2094 2095 uri_tmpl = None
2095 2096 if 'with_id' in override:
2096 2097 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2097 2098 del override['with_id']
2098 2099
2099 2100 if 'uri_tmpl' in override:
2100 2101 uri_tmpl = override['uri_tmpl']
2101 2102 del override['uri_tmpl']
2102 2103
2104 ssh = False
2105 if 'ssh' in override:
2106 ssh = True
2107 del override['ssh']
2108
2103 2109 # we didn't override our tmpl from **overrides
2104 2110 if not uri_tmpl:
2105 2111 rc_config = SettingsModel().get_all_settings(cache=True)
2106 uri_tmpl = rc_config.get(
2107 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2112 if ssh:
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 2119 request = get_current_request()
2110 2120 return get_clone_url(request=request,
2111 2121 uri_tmpl=uri_tmpl,
2112 2122 repo_name=self.repo_name,
2113 2123 repo_id=self.repo_id, **override)
2114 2124
2115 2125 def set_state(self, state):
2116 2126 self.repo_state = state
2117 2127 Session().add(self)
2118 2128 #==========================================================================
2119 2129 # SCM PROPERTIES
2120 2130 #==========================================================================
2121 2131
2122 2132 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2123 2133 return get_commit_safe(
2124 2134 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2125 2135
2126 2136 def get_changeset(self, rev=None, pre_load=None):
2127 2137 warnings.warn("Use get_commit", DeprecationWarning)
2128 2138 commit_id = None
2129 2139 commit_idx = None
2130 2140 if isinstance(rev, basestring):
2131 2141 commit_id = rev
2132 2142 else:
2133 2143 commit_idx = rev
2134 2144 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2135 2145 pre_load=pre_load)
2136 2146
2137 2147 def get_landing_commit(self):
2138 2148 """
2139 2149 Returns landing commit, or if that doesn't exist returns the tip
2140 2150 """
2141 2151 _rev_type, _rev = self.landing_rev
2142 2152 commit = self.get_commit(_rev)
2143 2153 if isinstance(commit, EmptyCommit):
2144 2154 return self.get_commit()
2145 2155 return commit
2146 2156
2147 2157 def update_commit_cache(self, cs_cache=None, config=None):
2148 2158 """
2149 2159 Update cache of last changeset for repository, keys should be::
2150 2160
2151 2161 short_id
2152 2162 raw_id
2153 2163 revision
2154 2164 parents
2155 2165 message
2156 2166 date
2157 2167 author
2158 2168
2159 2169 :param cs_cache:
2160 2170 """
2161 2171 from rhodecode.lib.vcs.backends.base import BaseChangeset
2162 2172 if cs_cache is None:
2163 2173 # use no-cache version here
2164 2174 scm_repo = self.scm_instance(cache=False, config=config)
2165 2175 if scm_repo:
2166 2176 cs_cache = scm_repo.get_commit(
2167 2177 pre_load=["author", "date", "message", "parents"])
2168 2178 else:
2169 2179 cs_cache = EmptyCommit()
2170 2180
2171 2181 if isinstance(cs_cache, BaseChangeset):
2172 2182 cs_cache = cs_cache.__json__()
2173 2183
2174 2184 def is_outdated(new_cs_cache):
2175 2185 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2176 2186 new_cs_cache['revision'] != self.changeset_cache['revision']):
2177 2187 return True
2178 2188 return False
2179 2189
2180 2190 # check if we have maybe already latest cached revision
2181 2191 if is_outdated(cs_cache) or not self.changeset_cache:
2182 2192 _default = datetime.datetime.fromtimestamp(0)
2183 2193 last_change = cs_cache.get('date') or _default
2184 2194 log.debug('updated repo %s with new cs cache %s',
2185 2195 self.repo_name, cs_cache)
2186 2196 self.updated_on = last_change
2187 2197 self.changeset_cache = cs_cache
2188 2198 Session().add(self)
2189 2199 Session().commit()
2190 2200 else:
2191 2201 log.debug('Skipping update_commit_cache for repo:`%s` '
2192 2202 'commit already with latest changes', self.repo_name)
2193 2203
2194 2204 @property
2195 2205 def tip(self):
2196 2206 return self.get_commit('tip')
2197 2207
2198 2208 @property
2199 2209 def author(self):
2200 2210 return self.tip.author
2201 2211
2202 2212 @property
2203 2213 def last_change(self):
2204 2214 return self.scm_instance().last_change
2205 2215
2206 2216 def get_comments(self, revisions=None):
2207 2217 """
2208 2218 Returns comments for this repository grouped by revisions
2209 2219
2210 2220 :param revisions: filter query by revisions only
2211 2221 """
2212 2222 cmts = ChangesetComment.query()\
2213 2223 .filter(ChangesetComment.repo == self)
2214 2224 if revisions:
2215 2225 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2216 2226 grouped = collections.defaultdict(list)
2217 2227 for cmt in cmts.all():
2218 2228 grouped[cmt.revision].append(cmt)
2219 2229 return grouped
2220 2230
2221 2231 def statuses(self, revisions=None):
2222 2232 """
2223 2233 Returns statuses for this repository
2224 2234
2225 2235 :param revisions: list of revisions to get statuses for
2226 2236 """
2227 2237 statuses = ChangesetStatus.query()\
2228 2238 .filter(ChangesetStatus.repo == self)\
2229 2239 .filter(ChangesetStatus.version == 0)
2230 2240
2231 2241 if revisions:
2232 2242 # Try doing the filtering in chunks to avoid hitting limits
2233 2243 size = 500
2234 2244 status_results = []
2235 2245 for chunk in xrange(0, len(revisions), size):
2236 2246 status_results += statuses.filter(
2237 2247 ChangesetStatus.revision.in_(
2238 2248 revisions[chunk: chunk+size])
2239 2249 ).all()
2240 2250 else:
2241 2251 status_results = statuses.all()
2242 2252
2243 2253 grouped = {}
2244 2254
2245 2255 # maybe we have open new pullrequest without a status?
2246 2256 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2247 2257 status_lbl = ChangesetStatus.get_status_lbl(stat)
2248 2258 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2249 2259 for rev in pr.revisions:
2250 2260 pr_id = pr.pull_request_id
2251 2261 pr_repo = pr.target_repo.repo_name
2252 2262 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2253 2263
2254 2264 for stat in status_results:
2255 2265 pr_id = pr_repo = None
2256 2266 if stat.pull_request:
2257 2267 pr_id = stat.pull_request.pull_request_id
2258 2268 pr_repo = stat.pull_request.target_repo.repo_name
2259 2269 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2260 2270 pr_id, pr_repo]
2261 2271 return grouped
2262 2272
2263 2273 # ==========================================================================
2264 2274 # SCM CACHE INSTANCE
2265 2275 # ==========================================================================
2266 2276
2267 2277 def scm_instance(self, **kwargs):
2268 2278 import rhodecode
2269 2279
2270 2280 # Passing a config will not hit the cache currently only used
2271 2281 # for repo2dbmapper
2272 2282 config = kwargs.pop('config', None)
2273 2283 cache = kwargs.pop('cache', None)
2274 2284 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2275 2285 # if cache is NOT defined use default global, else we have a full
2276 2286 # control over cache behaviour
2277 2287 if cache is None and full_cache and not config:
2278 2288 return self._get_instance_cached()
2279 2289 return self._get_instance(cache=bool(cache), config=config)
2280 2290
2281 2291 def _get_instance_cached(self):
2282 2292 @cache_region('long_term')
2283 2293 def _get_repo(cache_key):
2284 2294 return self._get_instance()
2285 2295
2286 2296 invalidator_context = CacheKey.repo_context_cache(
2287 2297 _get_repo, self.repo_name, None, thread_scoped=True)
2288 2298
2289 2299 with invalidator_context as context:
2290 2300 context.invalidate()
2291 2301 repo = context.compute()
2292 2302
2293 2303 return repo
2294 2304
2295 2305 def _get_instance(self, cache=True, config=None):
2296 2306 config = config or self._config
2297 2307 custom_wire = {
2298 2308 'cache': cache # controls the vcs.remote cache
2299 2309 }
2300 2310 repo = get_vcs_instance(
2301 2311 repo_path=safe_str(self.repo_full_path),
2302 2312 config=config,
2303 2313 with_wire=custom_wire,
2304 2314 create=False,
2305 2315 _vcs_alias=self.repo_type)
2306 2316
2307 2317 return repo
2308 2318
2309 2319 def __json__(self):
2310 2320 return {'landing_rev': self.landing_rev}
2311 2321
2312 2322 def get_dict(self):
2313 2323
2314 2324 # Since we transformed `repo_name` to a hybrid property, we need to
2315 2325 # keep compatibility with the code which uses `repo_name` field.
2316 2326
2317 2327 result = super(Repository, self).get_dict()
2318 2328 result['repo_name'] = result.pop('_repo_name', None)
2319 2329 return result
2320 2330
2321 2331
2322 2332 class RepoGroup(Base, BaseModel):
2323 2333 __tablename__ = 'groups'
2324 2334 __table_args__ = (
2325 2335 UniqueConstraint('group_name', 'group_parent_id'),
2326 2336 CheckConstraint('group_id != group_parent_id'),
2327 2337 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2328 2338 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2329 2339 )
2330 2340 __mapper_args__ = {'order_by': 'group_name'}
2331 2341
2332 2342 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2333 2343
2334 2344 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2335 2345 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2336 2346 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2337 2347 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2338 2348 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2339 2349 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2340 2350 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2341 2351 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2342 2352 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2343 2353
2344 2354 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2345 2355 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2346 2356 parent_group = relationship('RepoGroup', remote_side=group_id)
2347 2357 user = relationship('User')
2348 2358 integrations = relationship('Integration',
2349 2359 cascade="all, delete, delete-orphan")
2350 2360
2351 2361 def __init__(self, group_name='', parent_group=None):
2352 2362 self.group_name = group_name
2353 2363 self.parent_group = parent_group
2354 2364
2355 2365 def __unicode__(self):
2356 2366 return u"<%s('id:%s:%s')>" % (
2357 2367 self.__class__.__name__, self.group_id, self.group_name)
2358 2368
2359 2369 @hybrid_property
2360 2370 def description_safe(self):
2361 2371 from rhodecode.lib import helpers as h
2362 2372 return h.escape(self.group_description)
2363 2373
2364 2374 @classmethod
2365 2375 def _generate_choice(cls, repo_group):
2366 2376 from webhelpers.html import literal as _literal
2367 2377 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2368 2378 return repo_group.group_id, _name(repo_group.full_path_splitted)
2369 2379
2370 2380 @classmethod
2371 2381 def groups_choices(cls, groups=None, show_empty_group=True):
2372 2382 if not groups:
2373 2383 groups = cls.query().all()
2374 2384
2375 2385 repo_groups = []
2376 2386 if show_empty_group:
2377 2387 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2378 2388
2379 2389 repo_groups.extend([cls._generate_choice(x) for x in groups])
2380 2390
2381 2391 repo_groups = sorted(
2382 2392 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2383 2393 return repo_groups
2384 2394
2385 2395 @classmethod
2386 2396 def url_sep(cls):
2387 2397 return URL_SEP
2388 2398
2389 2399 @classmethod
2390 2400 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2391 2401 if case_insensitive:
2392 2402 gr = cls.query().filter(func.lower(cls.group_name)
2393 2403 == func.lower(group_name))
2394 2404 else:
2395 2405 gr = cls.query().filter(cls.group_name == group_name)
2396 2406 if cache:
2397 2407 name_key = _hash_key(group_name)
2398 2408 gr = gr.options(
2399 2409 FromCache("sql_cache_short", "get_group_%s" % name_key))
2400 2410 return gr.scalar()
2401 2411
2402 2412 @classmethod
2403 2413 def get_user_personal_repo_group(cls, user_id):
2404 2414 user = User.get(user_id)
2405 2415 if user.username == User.DEFAULT_USER:
2406 2416 return None
2407 2417
2408 2418 return cls.query()\
2409 2419 .filter(cls.personal == true()) \
2410 2420 .filter(cls.user == user).scalar()
2411 2421
2412 2422 @classmethod
2413 2423 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2414 2424 case_insensitive=True):
2415 2425 q = RepoGroup.query()
2416 2426
2417 2427 if not isinstance(user_id, Optional):
2418 2428 q = q.filter(RepoGroup.user_id == user_id)
2419 2429
2420 2430 if not isinstance(group_id, Optional):
2421 2431 q = q.filter(RepoGroup.group_parent_id == group_id)
2422 2432
2423 2433 if case_insensitive:
2424 2434 q = q.order_by(func.lower(RepoGroup.group_name))
2425 2435 else:
2426 2436 q = q.order_by(RepoGroup.group_name)
2427 2437 return q.all()
2428 2438
2429 2439 @property
2430 2440 def parents(self):
2431 2441 parents_recursion_limit = 10
2432 2442 groups = []
2433 2443 if self.parent_group is None:
2434 2444 return groups
2435 2445 cur_gr = self.parent_group
2436 2446 groups.insert(0, cur_gr)
2437 2447 cnt = 0
2438 2448 while 1:
2439 2449 cnt += 1
2440 2450 gr = getattr(cur_gr, 'parent_group', None)
2441 2451 cur_gr = cur_gr.parent_group
2442 2452 if gr is None:
2443 2453 break
2444 2454 if cnt == parents_recursion_limit:
2445 2455 # this will prevent accidental infinit loops
2446 2456 log.error(('more than %s parents found for group %s, stopping '
2447 2457 'recursive parent fetching' % (parents_recursion_limit, self)))
2448 2458 break
2449 2459
2450 2460 groups.insert(0, gr)
2451 2461 return groups
2452 2462
2453 2463 @property
2454 2464 def last_db_change(self):
2455 2465 return self.updated_on
2456 2466
2457 2467 @property
2458 2468 def children(self):
2459 2469 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2460 2470
2461 2471 @property
2462 2472 def name(self):
2463 2473 return self.group_name.split(RepoGroup.url_sep())[-1]
2464 2474
2465 2475 @property
2466 2476 def full_path(self):
2467 2477 return self.group_name
2468 2478
2469 2479 @property
2470 2480 def full_path_splitted(self):
2471 2481 return self.group_name.split(RepoGroup.url_sep())
2472 2482
2473 2483 @property
2474 2484 def repositories(self):
2475 2485 return Repository.query()\
2476 2486 .filter(Repository.group == self)\
2477 2487 .order_by(Repository.repo_name)
2478 2488
2479 2489 @property
2480 2490 def repositories_recursive_count(self):
2481 2491 cnt = self.repositories.count()
2482 2492
2483 2493 def children_count(group):
2484 2494 cnt = 0
2485 2495 for child in group.children:
2486 2496 cnt += child.repositories.count()
2487 2497 cnt += children_count(child)
2488 2498 return cnt
2489 2499
2490 2500 return cnt + children_count(self)
2491 2501
2492 2502 def _recursive_objects(self, include_repos=True):
2493 2503 all_ = []
2494 2504
2495 2505 def _get_members(root_gr):
2496 2506 if include_repos:
2497 2507 for r in root_gr.repositories:
2498 2508 all_.append(r)
2499 2509 childs = root_gr.children.all()
2500 2510 if childs:
2501 2511 for gr in childs:
2502 2512 all_.append(gr)
2503 2513 _get_members(gr)
2504 2514
2505 2515 _get_members(self)
2506 2516 return [self] + all_
2507 2517
2508 2518 def recursive_groups_and_repos(self):
2509 2519 """
2510 2520 Recursive return all groups, with repositories in those groups
2511 2521 """
2512 2522 return self._recursive_objects()
2513 2523
2514 2524 def recursive_groups(self):
2515 2525 """
2516 2526 Returns all children groups for this group including children of children
2517 2527 """
2518 2528 return self._recursive_objects(include_repos=False)
2519 2529
2520 2530 def get_new_name(self, group_name):
2521 2531 """
2522 2532 returns new full group name based on parent and new name
2523 2533
2524 2534 :param group_name:
2525 2535 """
2526 2536 path_prefix = (self.parent_group.full_path_splitted if
2527 2537 self.parent_group else [])
2528 2538 return RepoGroup.url_sep().join(path_prefix + [group_name])
2529 2539
2530 2540 def permissions(self, with_admins=True, with_owner=True):
2531 2541 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2532 2542 q = q.options(joinedload(UserRepoGroupToPerm.group),
2533 2543 joinedload(UserRepoGroupToPerm.user),
2534 2544 joinedload(UserRepoGroupToPerm.permission),)
2535 2545
2536 2546 # get owners and admins and permissions. We do a trick of re-writing
2537 2547 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2538 2548 # has a global reference and changing one object propagates to all
2539 2549 # others. This means if admin is also an owner admin_row that change
2540 2550 # would propagate to both objects
2541 2551 perm_rows = []
2542 2552 for _usr in q.all():
2543 2553 usr = AttributeDict(_usr.user.get_dict())
2544 2554 usr.permission = _usr.permission.permission_name
2545 2555 perm_rows.append(usr)
2546 2556
2547 2557 # filter the perm rows by 'default' first and then sort them by
2548 2558 # admin,write,read,none permissions sorted again alphabetically in
2549 2559 # each group
2550 2560 perm_rows = sorted(perm_rows, key=display_user_sort)
2551 2561
2552 2562 _admin_perm = 'group.admin'
2553 2563 owner_row = []
2554 2564 if with_owner:
2555 2565 usr = AttributeDict(self.user.get_dict())
2556 2566 usr.owner_row = True
2557 2567 usr.permission = _admin_perm
2558 2568 owner_row.append(usr)
2559 2569
2560 2570 super_admin_rows = []
2561 2571 if with_admins:
2562 2572 for usr in User.get_all_super_admins():
2563 2573 # if this admin is also owner, don't double the record
2564 2574 if usr.user_id == owner_row[0].user_id:
2565 2575 owner_row[0].admin_row = True
2566 2576 else:
2567 2577 usr = AttributeDict(usr.get_dict())
2568 2578 usr.admin_row = True
2569 2579 usr.permission = _admin_perm
2570 2580 super_admin_rows.append(usr)
2571 2581
2572 2582 return super_admin_rows + owner_row + perm_rows
2573 2583
2574 2584 def permission_user_groups(self):
2575 2585 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2576 2586 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2577 2587 joinedload(UserGroupRepoGroupToPerm.users_group),
2578 2588 joinedload(UserGroupRepoGroupToPerm.permission),)
2579 2589
2580 2590 perm_rows = []
2581 2591 for _user_group in q.all():
2582 2592 usr = AttributeDict(_user_group.users_group.get_dict())
2583 2593 usr.permission = _user_group.permission.permission_name
2584 2594 perm_rows.append(usr)
2585 2595
2586 2596 perm_rows = sorted(perm_rows, key=display_user_group_sort)
2587 2597 return perm_rows
2588 2598
2589 2599 def get_api_data(self):
2590 2600 """
2591 2601 Common function for generating api data
2592 2602
2593 2603 """
2594 2604 group = self
2595 2605 data = {
2596 2606 'group_id': group.group_id,
2597 2607 'group_name': group.group_name,
2598 2608 'group_description': group.description_safe,
2599 2609 'parent_group': group.parent_group.group_name if group.parent_group else None,
2600 2610 'repositories': [x.repo_name for x in group.repositories],
2601 2611 'owner': group.user.username,
2602 2612 }
2603 2613 return data
2604 2614
2605 2615
2606 2616 class Permission(Base, BaseModel):
2607 2617 __tablename__ = 'permissions'
2608 2618 __table_args__ = (
2609 2619 Index('p_perm_name_idx', 'permission_name'),
2610 2620 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2611 2621 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2612 2622 )
2613 2623 PERMS = [
2614 2624 ('hg.admin', _('RhodeCode Super Administrator')),
2615 2625
2616 2626 ('repository.none', _('Repository no access')),
2617 2627 ('repository.read', _('Repository read access')),
2618 2628 ('repository.write', _('Repository write access')),
2619 2629 ('repository.admin', _('Repository admin access')),
2620 2630
2621 2631 ('group.none', _('Repository group no access')),
2622 2632 ('group.read', _('Repository group read access')),
2623 2633 ('group.write', _('Repository group write access')),
2624 2634 ('group.admin', _('Repository group admin access')),
2625 2635
2626 2636 ('usergroup.none', _('User group no access')),
2627 2637 ('usergroup.read', _('User group read access')),
2628 2638 ('usergroup.write', _('User group write access')),
2629 2639 ('usergroup.admin', _('User group admin access')),
2630 2640
2631 2641 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2632 2642 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2633 2643
2634 2644 ('hg.usergroup.create.false', _('User Group creation disabled')),
2635 2645 ('hg.usergroup.create.true', _('User Group creation enabled')),
2636 2646
2637 2647 ('hg.create.none', _('Repository creation disabled')),
2638 2648 ('hg.create.repository', _('Repository creation enabled')),
2639 2649 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2640 2650 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2641 2651
2642 2652 ('hg.fork.none', _('Repository forking disabled')),
2643 2653 ('hg.fork.repository', _('Repository forking enabled')),
2644 2654
2645 2655 ('hg.register.none', _('Registration disabled')),
2646 2656 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2647 2657 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2648 2658
2649 2659 ('hg.password_reset.enabled', _('Password reset enabled')),
2650 2660 ('hg.password_reset.hidden', _('Password reset hidden')),
2651 2661 ('hg.password_reset.disabled', _('Password reset disabled')),
2652 2662
2653 2663 ('hg.extern_activate.manual', _('Manual activation of external account')),
2654 2664 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2655 2665
2656 2666 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2657 2667 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2658 2668 ]
2659 2669
2660 2670 # definition of system default permissions for DEFAULT user
2661 2671 DEFAULT_USER_PERMISSIONS = [
2662 2672 'repository.read',
2663 2673 'group.read',
2664 2674 'usergroup.read',
2665 2675 'hg.create.repository',
2666 2676 'hg.repogroup.create.false',
2667 2677 'hg.usergroup.create.false',
2668 2678 'hg.create.write_on_repogroup.true',
2669 2679 'hg.fork.repository',
2670 2680 'hg.register.manual_activate',
2671 2681 'hg.password_reset.enabled',
2672 2682 'hg.extern_activate.auto',
2673 2683 'hg.inherit_default_perms.true',
2674 2684 ]
2675 2685
2676 2686 # defines which permissions are more important higher the more important
2677 2687 # Weight defines which permissions are more important.
2678 2688 # The higher number the more important.
2679 2689 PERM_WEIGHTS = {
2680 2690 'repository.none': 0,
2681 2691 'repository.read': 1,
2682 2692 'repository.write': 3,
2683 2693 'repository.admin': 4,
2684 2694
2685 2695 'group.none': 0,
2686 2696 'group.read': 1,
2687 2697 'group.write': 3,
2688 2698 'group.admin': 4,
2689 2699
2690 2700 'usergroup.none': 0,
2691 2701 'usergroup.read': 1,
2692 2702 'usergroup.write': 3,
2693 2703 'usergroup.admin': 4,
2694 2704
2695 2705 'hg.repogroup.create.false': 0,
2696 2706 'hg.repogroup.create.true': 1,
2697 2707
2698 2708 'hg.usergroup.create.false': 0,
2699 2709 'hg.usergroup.create.true': 1,
2700 2710
2701 2711 'hg.fork.none': 0,
2702 2712 'hg.fork.repository': 1,
2703 2713 'hg.create.none': 0,
2704 2714 'hg.create.repository': 1
2705 2715 }
2706 2716
2707 2717 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2708 2718 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2709 2719 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2710 2720
2711 2721 def __unicode__(self):
2712 2722 return u"<%s('%s:%s')>" % (
2713 2723 self.__class__.__name__, self.permission_id, self.permission_name
2714 2724 )
2715 2725
2716 2726 @classmethod
2717 2727 def get_by_key(cls, key):
2718 2728 return cls.query().filter(cls.permission_name == key).scalar()
2719 2729
2720 2730 @classmethod
2721 2731 def get_default_repo_perms(cls, user_id, repo_id=None):
2722 2732 q = Session().query(UserRepoToPerm, Repository, Permission)\
2723 2733 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2724 2734 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2725 2735 .filter(UserRepoToPerm.user_id == user_id)
2726 2736 if repo_id:
2727 2737 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2728 2738 return q.all()
2729 2739
2730 2740 @classmethod
2731 2741 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2732 2742 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2733 2743 .join(
2734 2744 Permission,
2735 2745 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2736 2746 .join(
2737 2747 Repository,
2738 2748 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2739 2749 .join(
2740 2750 UserGroup,
2741 2751 UserGroupRepoToPerm.users_group_id ==
2742 2752 UserGroup.users_group_id)\
2743 2753 .join(
2744 2754 UserGroupMember,
2745 2755 UserGroupRepoToPerm.users_group_id ==
2746 2756 UserGroupMember.users_group_id)\
2747 2757 .filter(
2748 2758 UserGroupMember.user_id == user_id,
2749 2759 UserGroup.users_group_active == true())
2750 2760 if repo_id:
2751 2761 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2752 2762 return q.all()
2753 2763
2754 2764 @classmethod
2755 2765 def get_default_group_perms(cls, user_id, repo_group_id=None):
2756 2766 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2757 2767 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2758 2768 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2759 2769 .filter(UserRepoGroupToPerm.user_id == user_id)
2760 2770 if repo_group_id:
2761 2771 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2762 2772 return q.all()
2763 2773
2764 2774 @classmethod
2765 2775 def get_default_group_perms_from_user_group(
2766 2776 cls, user_id, repo_group_id=None):
2767 2777 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2768 2778 .join(
2769 2779 Permission,
2770 2780 UserGroupRepoGroupToPerm.permission_id ==
2771 2781 Permission.permission_id)\
2772 2782 .join(
2773 2783 RepoGroup,
2774 2784 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2775 2785 .join(
2776 2786 UserGroup,
2777 2787 UserGroupRepoGroupToPerm.users_group_id ==
2778 2788 UserGroup.users_group_id)\
2779 2789 .join(
2780 2790 UserGroupMember,
2781 2791 UserGroupRepoGroupToPerm.users_group_id ==
2782 2792 UserGroupMember.users_group_id)\
2783 2793 .filter(
2784 2794 UserGroupMember.user_id == user_id,
2785 2795 UserGroup.users_group_active == true())
2786 2796 if repo_group_id:
2787 2797 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2788 2798 return q.all()
2789 2799
2790 2800 @classmethod
2791 2801 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2792 2802 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2793 2803 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2794 2804 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2795 2805 .filter(UserUserGroupToPerm.user_id == user_id)
2796 2806 if user_group_id:
2797 2807 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2798 2808 return q.all()
2799 2809
2800 2810 @classmethod
2801 2811 def get_default_user_group_perms_from_user_group(
2802 2812 cls, user_id, user_group_id=None):
2803 2813 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2804 2814 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2805 2815 .join(
2806 2816 Permission,
2807 2817 UserGroupUserGroupToPerm.permission_id ==
2808 2818 Permission.permission_id)\
2809 2819 .join(
2810 2820 TargetUserGroup,
2811 2821 UserGroupUserGroupToPerm.target_user_group_id ==
2812 2822 TargetUserGroup.users_group_id)\
2813 2823 .join(
2814 2824 UserGroup,
2815 2825 UserGroupUserGroupToPerm.user_group_id ==
2816 2826 UserGroup.users_group_id)\
2817 2827 .join(
2818 2828 UserGroupMember,
2819 2829 UserGroupUserGroupToPerm.user_group_id ==
2820 2830 UserGroupMember.users_group_id)\
2821 2831 .filter(
2822 2832 UserGroupMember.user_id == user_id,
2823 2833 UserGroup.users_group_active == true())
2824 2834 if user_group_id:
2825 2835 q = q.filter(
2826 2836 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2827 2837
2828 2838 return q.all()
2829 2839
2830 2840
2831 2841 class UserRepoToPerm(Base, BaseModel):
2832 2842 __tablename__ = 'repo_to_perm'
2833 2843 __table_args__ = (
2834 2844 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2835 2845 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2836 2846 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2837 2847 )
2838 2848 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2839 2849 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2840 2850 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2841 2851 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2842 2852
2843 2853 user = relationship('User')
2844 2854 repository = relationship('Repository')
2845 2855 permission = relationship('Permission')
2846 2856
2847 2857 @classmethod
2848 2858 def create(cls, user, repository, permission):
2849 2859 n = cls()
2850 2860 n.user = user
2851 2861 n.repository = repository
2852 2862 n.permission = permission
2853 2863 Session().add(n)
2854 2864 return n
2855 2865
2856 2866 def __unicode__(self):
2857 2867 return u'<%s => %s >' % (self.user, self.repository)
2858 2868
2859 2869
2860 2870 class UserUserGroupToPerm(Base, BaseModel):
2861 2871 __tablename__ = 'user_user_group_to_perm'
2862 2872 __table_args__ = (
2863 2873 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2864 2874 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2865 2875 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2866 2876 )
2867 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 2878 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2869 2879 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2870 2880 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2871 2881
2872 2882 user = relationship('User')
2873 2883 user_group = relationship('UserGroup')
2874 2884 permission = relationship('Permission')
2875 2885
2876 2886 @classmethod
2877 2887 def create(cls, user, user_group, permission):
2878 2888 n = cls()
2879 2889 n.user = user
2880 2890 n.user_group = user_group
2881 2891 n.permission = permission
2882 2892 Session().add(n)
2883 2893 return n
2884 2894
2885 2895 def __unicode__(self):
2886 2896 return u'<%s => %s >' % (self.user, self.user_group)
2887 2897
2888 2898
2889 2899 class UserToPerm(Base, BaseModel):
2890 2900 __tablename__ = 'user_to_perm'
2891 2901 __table_args__ = (
2892 2902 UniqueConstraint('user_id', 'permission_id'),
2893 2903 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2894 2904 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2895 2905 )
2896 2906 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2897 2907 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2898 2908 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2899 2909
2900 2910 user = relationship('User')
2901 2911 permission = relationship('Permission', lazy='joined')
2902 2912
2903 2913 def __unicode__(self):
2904 2914 return u'<%s => %s >' % (self.user, self.permission)
2905 2915
2906 2916
2907 2917 class UserGroupRepoToPerm(Base, BaseModel):
2908 2918 __tablename__ = 'users_group_repo_to_perm'
2909 2919 __table_args__ = (
2910 2920 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2911 2921 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2912 2922 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2913 2923 )
2914 2924 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2915 2925 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2916 2926 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2917 2927 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2918 2928
2919 2929 users_group = relationship('UserGroup')
2920 2930 permission = relationship('Permission')
2921 2931 repository = relationship('Repository')
2922 2932
2923 2933 @classmethod
2924 2934 def create(cls, users_group, repository, permission):
2925 2935 n = cls()
2926 2936 n.users_group = users_group
2927 2937 n.repository = repository
2928 2938 n.permission = permission
2929 2939 Session().add(n)
2930 2940 return n
2931 2941
2932 2942 def __unicode__(self):
2933 2943 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2934 2944
2935 2945
2936 2946 class UserGroupUserGroupToPerm(Base, BaseModel):
2937 2947 __tablename__ = 'user_group_user_group_to_perm'
2938 2948 __table_args__ = (
2939 2949 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2940 2950 CheckConstraint('target_user_group_id != user_group_id'),
2941 2951 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2942 2952 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2943 2953 )
2944 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 2955 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2946 2956 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2947 2957 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2948 2958
2949 2959 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2950 2960 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2951 2961 permission = relationship('Permission')
2952 2962
2953 2963 @classmethod
2954 2964 def create(cls, target_user_group, user_group, permission):
2955 2965 n = cls()
2956 2966 n.target_user_group = target_user_group
2957 2967 n.user_group = user_group
2958 2968 n.permission = permission
2959 2969 Session().add(n)
2960 2970 return n
2961 2971
2962 2972 def __unicode__(self):
2963 2973 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2964 2974
2965 2975
2966 2976 class UserGroupToPerm(Base, BaseModel):
2967 2977 __tablename__ = 'users_group_to_perm'
2968 2978 __table_args__ = (
2969 2979 UniqueConstraint('users_group_id', 'permission_id',),
2970 2980 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2971 2981 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2972 2982 )
2973 2983 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2974 2984 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2975 2985 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2976 2986
2977 2987 users_group = relationship('UserGroup')
2978 2988 permission = relationship('Permission')
2979 2989
2980 2990
2981 2991 class UserRepoGroupToPerm(Base, BaseModel):
2982 2992 __tablename__ = 'user_repo_group_to_perm'
2983 2993 __table_args__ = (
2984 2994 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2985 2995 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2986 2996 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2987 2997 )
2988 2998
2989 2999 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2990 3000 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2991 3001 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2992 3002 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2993 3003
2994 3004 user = relationship('User')
2995 3005 group = relationship('RepoGroup')
2996 3006 permission = relationship('Permission')
2997 3007
2998 3008 @classmethod
2999 3009 def create(cls, user, repository_group, permission):
3000 3010 n = cls()
3001 3011 n.user = user
3002 3012 n.group = repository_group
3003 3013 n.permission = permission
3004 3014 Session().add(n)
3005 3015 return n
3006 3016
3007 3017
3008 3018 class UserGroupRepoGroupToPerm(Base, BaseModel):
3009 3019 __tablename__ = 'users_group_repo_group_to_perm'
3010 3020 __table_args__ = (
3011 3021 UniqueConstraint('users_group_id', 'group_id'),
3012 3022 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3013 3023 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3014 3024 )
3015 3025
3016 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 3027 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
3018 3028 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
3019 3029 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
3020 3030
3021 3031 users_group = relationship('UserGroup')
3022 3032 permission = relationship('Permission')
3023 3033 group = relationship('RepoGroup')
3024 3034
3025 3035 @classmethod
3026 3036 def create(cls, user_group, repository_group, permission):
3027 3037 n = cls()
3028 3038 n.users_group = user_group
3029 3039 n.group = repository_group
3030 3040 n.permission = permission
3031 3041 Session().add(n)
3032 3042 return n
3033 3043
3034 3044 def __unicode__(self):
3035 3045 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
3036 3046
3037 3047
3038 3048 class Statistics(Base, BaseModel):
3039 3049 __tablename__ = 'statistics'
3040 3050 __table_args__ = (
3041 3051 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3042 3052 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3043 3053 )
3044 3054 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3045 3055 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
3046 3056 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
3047 3057 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
3048 3058 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
3049 3059 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
3050 3060
3051 3061 repository = relationship('Repository', single_parent=True)
3052 3062
3053 3063
3054 3064 class UserFollowing(Base, BaseModel):
3055 3065 __tablename__ = 'user_followings'
3056 3066 __table_args__ = (
3057 3067 UniqueConstraint('user_id', 'follows_repository_id'),
3058 3068 UniqueConstraint('user_id', 'follows_user_id'),
3059 3069 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3060 3070 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3061 3071 )
3062 3072
3063 3073 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3064 3074 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
3065 3075 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
3066 3076 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
3067 3077 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
3068 3078
3069 3079 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
3070 3080
3071 3081 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
3072 3082 follows_repository = relationship('Repository', order_by='Repository.repo_name')
3073 3083
3074 3084 @classmethod
3075 3085 def get_repo_followers(cls, repo_id):
3076 3086 return cls.query().filter(cls.follows_repo_id == repo_id)
3077 3087
3078 3088
3079 3089 class CacheKey(Base, BaseModel):
3080 3090 __tablename__ = 'cache_invalidation'
3081 3091 __table_args__ = (
3082 3092 UniqueConstraint('cache_key'),
3083 3093 Index('key_idx', 'cache_key'),
3084 3094 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3085 3095 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3086 3096 )
3087 3097 CACHE_TYPE_ATOM = 'ATOM'
3088 3098 CACHE_TYPE_RSS = 'RSS'
3089 3099 CACHE_TYPE_README = 'README'
3090 3100
3091 3101 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3092 3102 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3093 3103 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3094 3104 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3095 3105
3096 3106 def __init__(self, cache_key, cache_args=''):
3097 3107 self.cache_key = cache_key
3098 3108 self.cache_args = cache_args
3099 3109 self.cache_active = False
3100 3110
3101 3111 def __unicode__(self):
3102 3112 return u"<%s('%s:%s[%s]')>" % (
3103 3113 self.__class__.__name__,
3104 3114 self.cache_id, self.cache_key, self.cache_active)
3105 3115
3106 3116 def _cache_key_partition(self):
3107 3117 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3108 3118 return prefix, repo_name, suffix
3109 3119
3110 3120 def get_prefix(self):
3111 3121 """
3112 3122 Try to extract prefix from existing cache key. The key could consist
3113 3123 of prefix, repo_name, suffix
3114 3124 """
3115 3125 # this returns prefix, repo_name, suffix
3116 3126 return self._cache_key_partition()[0]
3117 3127
3118 3128 def get_suffix(self):
3119 3129 """
3120 3130 get suffix that might have been used in _get_cache_key to
3121 3131 generate self.cache_key. Only used for informational purposes
3122 3132 in repo_edit.mako.
3123 3133 """
3124 3134 # prefix, repo_name, suffix
3125 3135 return self._cache_key_partition()[2]
3126 3136
3127 3137 @classmethod
3128 3138 def delete_all_cache(cls):
3129 3139 """
3130 3140 Delete all cache keys from database.
3131 3141 Should only be run when all instances are down and all entries
3132 3142 thus stale.
3133 3143 """
3134 3144 cls.query().delete()
3135 3145 Session().commit()
3136 3146
3137 3147 @classmethod
3138 3148 def get_cache_key(cls, repo_name, cache_type):
3139 3149 """
3140 3150
3141 3151 Generate a cache key for this process of RhodeCode instance.
3142 3152 Prefix most likely will be process id or maybe explicitly set
3143 3153 instance_id from .ini file.
3144 3154 """
3145 3155 import rhodecode
3146 3156 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
3147 3157
3148 3158 repo_as_unicode = safe_unicode(repo_name)
3149 3159 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
3150 3160 if cache_type else repo_as_unicode
3151 3161
3152 3162 return u'{}{}'.format(prefix, key)
3153 3163
3154 3164 @classmethod
3155 3165 def set_invalidate(cls, repo_name, delete=False):
3156 3166 """
3157 3167 Mark all caches of a repo as invalid in the database.
3158 3168 """
3159 3169
3160 3170 try:
3161 3171 qry = Session().query(cls).filter(cls.cache_args == repo_name)
3162 3172 if delete:
3163 3173 log.debug('cache objects deleted for repo %s',
3164 3174 safe_str(repo_name))
3165 3175 qry.delete()
3166 3176 else:
3167 3177 log.debug('cache objects marked as invalid for repo %s',
3168 3178 safe_str(repo_name))
3169 3179 qry.update({"cache_active": False})
3170 3180
3171 3181 Session().commit()
3172 3182 except Exception:
3173 3183 log.exception(
3174 3184 'Cache key invalidation failed for repository %s',
3175 3185 safe_str(repo_name))
3176 3186 Session().rollback()
3177 3187
3178 3188 @classmethod
3179 3189 def get_active_cache(cls, cache_key):
3180 3190 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3181 3191 if inv_obj:
3182 3192 return inv_obj
3183 3193 return None
3184 3194
3185 3195 @classmethod
3186 3196 def repo_context_cache(cls, compute_func, repo_name, cache_type,
3187 3197 thread_scoped=False):
3188 3198 """
3189 3199 @cache_region('long_term')
3190 3200 def _heavy_calculation(cache_key):
3191 3201 return 'result'
3192 3202
3193 3203 cache_context = CacheKey.repo_context_cache(
3194 3204 _heavy_calculation, repo_name, cache_type)
3195 3205
3196 3206 with cache_context as context:
3197 3207 context.invalidate()
3198 3208 computed = context.compute()
3199 3209
3200 3210 assert computed == 'result'
3201 3211 """
3202 3212 from rhodecode.lib import caches
3203 3213 return caches.InvalidationContext(
3204 3214 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
3205 3215
3206 3216
3207 3217 class ChangesetComment(Base, BaseModel):
3208 3218 __tablename__ = 'changeset_comments'
3209 3219 __table_args__ = (
3210 3220 Index('cc_revision_idx', 'revision'),
3211 3221 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3212 3222 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3213 3223 )
3214 3224
3215 3225 COMMENT_OUTDATED = u'comment_outdated'
3216 3226 COMMENT_TYPE_NOTE = u'note'
3217 3227 COMMENT_TYPE_TODO = u'todo'
3218 3228 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3219 3229
3220 3230 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3221 3231 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3222 3232 revision = Column('revision', String(40), nullable=True)
3223 3233 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3224 3234 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3225 3235 line_no = Column('line_no', Unicode(10), nullable=True)
3226 3236 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3227 3237 f_path = Column('f_path', Unicode(1000), nullable=True)
3228 3238 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3229 3239 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3230 3240 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3231 3241 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3232 3242 renderer = Column('renderer', Unicode(64), nullable=True)
3233 3243 display_state = Column('display_state', Unicode(128), nullable=True)
3234 3244
3235 3245 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3236 3246 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3237 3247 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3238 3248 author = relationship('User', lazy='joined')
3239 3249 repo = relationship('Repository')
3240 3250 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3241 3251 pull_request = relationship('PullRequest', lazy='joined')
3242 3252 pull_request_version = relationship('PullRequestVersion')
3243 3253
3244 3254 @classmethod
3245 3255 def get_users(cls, revision=None, pull_request_id=None):
3246 3256 """
3247 3257 Returns user associated with this ChangesetComment. ie those
3248 3258 who actually commented
3249 3259
3250 3260 :param cls:
3251 3261 :param revision:
3252 3262 """
3253 3263 q = Session().query(User)\
3254 3264 .join(ChangesetComment.author)
3255 3265 if revision:
3256 3266 q = q.filter(cls.revision == revision)
3257 3267 elif pull_request_id:
3258 3268 q = q.filter(cls.pull_request_id == pull_request_id)
3259 3269 return q.all()
3260 3270
3261 3271 @classmethod
3262 3272 def get_index_from_version(cls, pr_version, versions):
3263 3273 num_versions = [x.pull_request_version_id for x in versions]
3264 3274 try:
3265 3275 return num_versions.index(pr_version) +1
3266 3276 except (IndexError, ValueError):
3267 3277 return
3268 3278
3269 3279 @property
3270 3280 def outdated(self):
3271 3281 return self.display_state == self.COMMENT_OUTDATED
3272 3282
3273 3283 def outdated_at_version(self, version):
3274 3284 """
3275 3285 Checks if comment is outdated for given pull request version
3276 3286 """
3277 3287 return self.outdated and self.pull_request_version_id != version
3278 3288
3279 3289 def older_than_version(self, version):
3280 3290 """
3281 3291 Checks if comment is made from previous version than given
3282 3292 """
3283 3293 if version is None:
3284 3294 return self.pull_request_version_id is not None
3285 3295
3286 3296 return self.pull_request_version_id < version
3287 3297
3288 3298 @property
3289 3299 def resolved(self):
3290 3300 return self.resolved_by[0] if self.resolved_by else None
3291 3301
3292 3302 @property
3293 3303 def is_todo(self):
3294 3304 return self.comment_type == self.COMMENT_TYPE_TODO
3295 3305
3296 3306 @property
3297 3307 def is_inline(self):
3298 3308 return self.line_no and self.f_path
3299 3309
3300 3310 def get_index_version(self, versions):
3301 3311 return self.get_index_from_version(
3302 3312 self.pull_request_version_id, versions)
3303 3313
3304 3314 def __repr__(self):
3305 3315 if self.comment_id:
3306 3316 return '<DB:Comment #%s>' % self.comment_id
3307 3317 else:
3308 3318 return '<DB:Comment at %#x>' % id(self)
3309 3319
3310 3320 def get_api_data(self):
3311 3321 comment = self
3312 3322 data = {
3313 3323 'comment_id': comment.comment_id,
3314 3324 'comment_type': comment.comment_type,
3315 3325 'comment_text': comment.text,
3316 3326 'comment_status': comment.status_change,
3317 3327 'comment_f_path': comment.f_path,
3318 3328 'comment_lineno': comment.line_no,
3319 3329 'comment_author': comment.author,
3320 3330 'comment_created_on': comment.created_on
3321 3331 }
3322 3332 return data
3323 3333
3324 3334 def __json__(self):
3325 3335 data = dict()
3326 3336 data.update(self.get_api_data())
3327 3337 return data
3328 3338
3329 3339
3330 3340 class ChangesetStatus(Base, BaseModel):
3331 3341 __tablename__ = 'changeset_statuses'
3332 3342 __table_args__ = (
3333 3343 Index('cs_revision_idx', 'revision'),
3334 3344 Index('cs_version_idx', 'version'),
3335 3345 UniqueConstraint('repo_id', 'revision', 'version'),
3336 3346 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3337 3347 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3338 3348 )
3339 3349 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3340 3350 STATUS_APPROVED = 'approved'
3341 3351 STATUS_REJECTED = 'rejected'
3342 3352 STATUS_UNDER_REVIEW = 'under_review'
3343 3353
3344 3354 STATUSES = [
3345 3355 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3346 3356 (STATUS_APPROVED, _("Approved")),
3347 3357 (STATUS_REJECTED, _("Rejected")),
3348 3358 (STATUS_UNDER_REVIEW, _("Under Review")),
3349 3359 ]
3350 3360
3351 3361 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3352 3362 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3353 3363 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3354 3364 revision = Column('revision', String(40), nullable=False)
3355 3365 status = Column('status', String(128), nullable=False, default=DEFAULT)
3356 3366 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3357 3367 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3358 3368 version = Column('version', Integer(), nullable=False, default=0)
3359 3369 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3360 3370
3361 3371 author = relationship('User', lazy='joined')
3362 3372 repo = relationship('Repository')
3363 3373 comment = relationship('ChangesetComment', lazy='joined')
3364 3374 pull_request = relationship('PullRequest', lazy='joined')
3365 3375
3366 3376 def __unicode__(self):
3367 3377 return u"<%s('%s[v%s]:%s')>" % (
3368 3378 self.__class__.__name__,
3369 3379 self.status, self.version, self.author
3370 3380 )
3371 3381
3372 3382 @classmethod
3373 3383 def get_status_lbl(cls, value):
3374 3384 return dict(cls.STATUSES).get(value)
3375 3385
3376 3386 @property
3377 3387 def status_lbl(self):
3378 3388 return ChangesetStatus.get_status_lbl(self.status)
3379 3389
3380 3390 def get_api_data(self):
3381 3391 status = self
3382 3392 data = {
3383 3393 'status_id': status.changeset_status_id,
3384 3394 'status': status.status,
3385 3395 }
3386 3396 return data
3387 3397
3388 3398 def __json__(self):
3389 3399 data = dict()
3390 3400 data.update(self.get_api_data())
3391 3401 return data
3392 3402
3393 3403
3394 3404 class _PullRequestBase(BaseModel):
3395 3405 """
3396 3406 Common attributes of pull request and version entries.
3397 3407 """
3398 3408
3399 3409 # .status values
3400 3410 STATUS_NEW = u'new'
3401 3411 STATUS_OPEN = u'open'
3402 3412 STATUS_CLOSED = u'closed'
3403 3413
3404 3414 title = Column('title', Unicode(255), nullable=True)
3405 3415 description = Column(
3406 3416 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3407 3417 nullable=True)
3408 3418 # new/open/closed status of pull request (not approve/reject/etc)
3409 3419 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3410 3420 created_on = Column(
3411 3421 'created_on', DateTime(timezone=False), nullable=False,
3412 3422 default=datetime.datetime.now)
3413 3423 updated_on = Column(
3414 3424 'updated_on', DateTime(timezone=False), nullable=False,
3415 3425 default=datetime.datetime.now)
3416 3426
3417 3427 @declared_attr
3418 3428 def user_id(cls):
3419 3429 return Column(
3420 3430 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3421 3431 unique=None)
3422 3432
3423 3433 # 500 revisions max
3424 3434 _revisions = Column(
3425 3435 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3426 3436
3427 3437 @declared_attr
3428 3438 def source_repo_id(cls):
3429 3439 # TODO: dan: rename column to source_repo_id
3430 3440 return Column(
3431 3441 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3432 3442 nullable=False)
3433 3443
3434 3444 source_ref = Column('org_ref', Unicode(255), nullable=False)
3435 3445
3436 3446 @declared_attr
3437 3447 def target_repo_id(cls):
3438 3448 # TODO: dan: rename column to target_repo_id
3439 3449 return Column(
3440 3450 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3441 3451 nullable=False)
3442 3452
3443 3453 target_ref = Column('other_ref', Unicode(255), nullable=False)
3444 3454 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3445 3455
3446 3456 # TODO: dan: rename column to last_merge_source_rev
3447 3457 _last_merge_source_rev = Column(
3448 3458 'last_merge_org_rev', String(40), nullable=True)
3449 3459 # TODO: dan: rename column to last_merge_target_rev
3450 3460 _last_merge_target_rev = Column(
3451 3461 'last_merge_other_rev', String(40), nullable=True)
3452 3462 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3453 3463 merge_rev = Column('merge_rev', String(40), nullable=True)
3454 3464
3455 3465 reviewer_data = Column(
3456 3466 'reviewer_data_json', MutationObj.as_mutable(
3457 3467 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3458 3468
3459 3469 @property
3460 3470 def reviewer_data_json(self):
3461 3471 return json.dumps(self.reviewer_data)
3462 3472
3463 3473 @hybrid_property
3464 3474 def description_safe(self):
3465 3475 from rhodecode.lib import helpers as h
3466 3476 return h.escape(self.description)
3467 3477
3468 3478 @hybrid_property
3469 3479 def revisions(self):
3470 3480 return self._revisions.split(':') if self._revisions else []
3471 3481
3472 3482 @revisions.setter
3473 3483 def revisions(self, val):
3474 3484 self._revisions = ':'.join(val)
3475 3485
3476 3486 @hybrid_property
3477 3487 def last_merge_status(self):
3478 3488 return safe_int(self._last_merge_status)
3479 3489
3480 3490 @last_merge_status.setter
3481 3491 def last_merge_status(self, val):
3482 3492 self._last_merge_status = val
3483 3493
3484 3494 @declared_attr
3485 3495 def author(cls):
3486 3496 return relationship('User', lazy='joined')
3487 3497
3488 3498 @declared_attr
3489 3499 def source_repo(cls):
3490 3500 return relationship(
3491 3501 'Repository',
3492 3502 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3493 3503
3494 3504 @property
3495 3505 def source_ref_parts(self):
3496 3506 return self.unicode_to_reference(self.source_ref)
3497 3507
3498 3508 @declared_attr
3499 3509 def target_repo(cls):
3500 3510 return relationship(
3501 3511 'Repository',
3502 3512 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3503 3513
3504 3514 @property
3505 3515 def target_ref_parts(self):
3506 3516 return self.unicode_to_reference(self.target_ref)
3507 3517
3508 3518 @property
3509 3519 def shadow_merge_ref(self):
3510 3520 return self.unicode_to_reference(self._shadow_merge_ref)
3511 3521
3512 3522 @shadow_merge_ref.setter
3513 3523 def shadow_merge_ref(self, ref):
3514 3524 self._shadow_merge_ref = self.reference_to_unicode(ref)
3515 3525
3516 3526 def unicode_to_reference(self, raw):
3517 3527 """
3518 3528 Convert a unicode (or string) to a reference object.
3519 3529 If unicode evaluates to False it returns None.
3520 3530 """
3521 3531 if raw:
3522 3532 refs = raw.split(':')
3523 3533 return Reference(*refs)
3524 3534 else:
3525 3535 return None
3526 3536
3527 3537 def reference_to_unicode(self, ref):
3528 3538 """
3529 3539 Convert a reference object to unicode.
3530 3540 If reference is None it returns None.
3531 3541 """
3532 3542 if ref:
3533 3543 return u':'.join(ref)
3534 3544 else:
3535 3545 return None
3536 3546
3537 3547 def get_api_data(self, with_merge_state=True):
3538 3548 from rhodecode.model.pull_request import PullRequestModel
3539 3549
3540 3550 pull_request = self
3541 3551 if with_merge_state:
3542 3552 merge_status = PullRequestModel().merge_status(pull_request)
3543 3553 merge_state = {
3544 3554 'status': merge_status[0],
3545 3555 'message': safe_unicode(merge_status[1]),
3546 3556 }
3547 3557 else:
3548 3558 merge_state = {'status': 'not_available',
3549 3559 'message': 'not_available'}
3550 3560
3551 3561 merge_data = {
3552 3562 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3553 3563 'reference': (
3554 3564 pull_request.shadow_merge_ref._asdict()
3555 3565 if pull_request.shadow_merge_ref else None),
3556 3566 }
3557 3567
3558 3568 data = {
3559 3569 'pull_request_id': pull_request.pull_request_id,
3560 3570 'url': PullRequestModel().get_url(pull_request),
3561 3571 'title': pull_request.title,
3562 3572 'description': pull_request.description,
3563 3573 'status': pull_request.status,
3564 3574 'created_on': pull_request.created_on,
3565 3575 'updated_on': pull_request.updated_on,
3566 3576 'commit_ids': pull_request.revisions,
3567 3577 'review_status': pull_request.calculated_review_status(),
3568 3578 'mergeable': merge_state,
3569 3579 'source': {
3570 3580 'clone_url': pull_request.source_repo.clone_url(),
3571 3581 'repository': pull_request.source_repo.repo_name,
3572 3582 'reference': {
3573 3583 'name': pull_request.source_ref_parts.name,
3574 3584 'type': pull_request.source_ref_parts.type,
3575 3585 'commit_id': pull_request.source_ref_parts.commit_id,
3576 3586 },
3577 3587 },
3578 3588 'target': {
3579 3589 'clone_url': pull_request.target_repo.clone_url(),
3580 3590 'repository': pull_request.target_repo.repo_name,
3581 3591 'reference': {
3582 3592 'name': pull_request.target_ref_parts.name,
3583 3593 'type': pull_request.target_ref_parts.type,
3584 3594 'commit_id': pull_request.target_ref_parts.commit_id,
3585 3595 },
3586 3596 },
3587 3597 'merge': merge_data,
3588 3598 'author': pull_request.author.get_api_data(include_secrets=False,
3589 3599 details='basic'),
3590 3600 'reviewers': [
3591 3601 {
3592 3602 'user': reviewer.get_api_data(include_secrets=False,
3593 3603 details='basic'),
3594 3604 'reasons': reasons,
3595 3605 'review_status': st[0][1].status if st else 'not_reviewed',
3596 3606 }
3597 3607 for obj, reviewer, reasons, mandatory, st in
3598 3608 pull_request.reviewers_statuses()
3599 3609 ]
3600 3610 }
3601 3611
3602 3612 return data
3603 3613
3604 3614
3605 3615 class PullRequest(Base, _PullRequestBase):
3606 3616 __tablename__ = 'pull_requests'
3607 3617 __table_args__ = (
3608 3618 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3609 3619 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3610 3620 )
3611 3621
3612 3622 pull_request_id = Column(
3613 3623 'pull_request_id', Integer(), nullable=False, primary_key=True)
3614 3624
3615 3625 def __repr__(self):
3616 3626 if self.pull_request_id:
3617 3627 return '<DB:PullRequest #%s>' % self.pull_request_id
3618 3628 else:
3619 3629 return '<DB:PullRequest at %#x>' % id(self)
3620 3630
3621 3631 reviewers = relationship('PullRequestReviewers',
3622 3632 cascade="all, delete, delete-orphan")
3623 3633 statuses = relationship('ChangesetStatus',
3624 3634 cascade="all, delete, delete-orphan")
3625 3635 comments = relationship('ChangesetComment',
3626 3636 cascade="all, delete, delete-orphan")
3627 3637 versions = relationship('PullRequestVersion',
3628 3638 cascade="all, delete, delete-orphan",
3629 3639 lazy='dynamic')
3630 3640
3631 3641 @classmethod
3632 3642 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3633 3643 internal_methods=None):
3634 3644
3635 3645 class PullRequestDisplay(object):
3636 3646 """
3637 3647 Special object wrapper for showing PullRequest data via Versions
3638 3648 It mimics PR object as close as possible. This is read only object
3639 3649 just for display
3640 3650 """
3641 3651
3642 3652 def __init__(self, attrs, internal=None):
3643 3653 self.attrs = attrs
3644 3654 # internal have priority over the given ones via attrs
3645 3655 self.internal = internal or ['versions']
3646 3656
3647 3657 def __getattr__(self, item):
3648 3658 if item in self.internal:
3649 3659 return getattr(self, item)
3650 3660 try:
3651 3661 return self.attrs[item]
3652 3662 except KeyError:
3653 3663 raise AttributeError(
3654 3664 '%s object has no attribute %s' % (self, item))
3655 3665
3656 3666 def __repr__(self):
3657 3667 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3658 3668
3659 3669 def versions(self):
3660 3670 return pull_request_obj.versions.order_by(
3661 3671 PullRequestVersion.pull_request_version_id).all()
3662 3672
3663 3673 def is_closed(self):
3664 3674 return pull_request_obj.is_closed()
3665 3675
3666 3676 @property
3667 3677 def pull_request_version_id(self):
3668 3678 return getattr(pull_request_obj, 'pull_request_version_id', None)
3669 3679
3670 3680 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3671 3681
3672 3682 attrs.author = StrictAttributeDict(
3673 3683 pull_request_obj.author.get_api_data())
3674 3684 if pull_request_obj.target_repo:
3675 3685 attrs.target_repo = StrictAttributeDict(
3676 3686 pull_request_obj.target_repo.get_api_data())
3677 3687 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3678 3688
3679 3689 if pull_request_obj.source_repo:
3680 3690 attrs.source_repo = StrictAttributeDict(
3681 3691 pull_request_obj.source_repo.get_api_data())
3682 3692 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3683 3693
3684 3694 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3685 3695 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3686 3696 attrs.revisions = pull_request_obj.revisions
3687 3697
3688 3698 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3689 3699 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3690 3700 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3691 3701
3692 3702 return PullRequestDisplay(attrs, internal=internal_methods)
3693 3703
3694 3704 def is_closed(self):
3695 3705 return self.status == self.STATUS_CLOSED
3696 3706
3697 3707 def __json__(self):
3698 3708 return {
3699 3709 'revisions': self.revisions,
3700 3710 }
3701 3711
3702 3712 def calculated_review_status(self):
3703 3713 from rhodecode.model.changeset_status import ChangesetStatusModel
3704 3714 return ChangesetStatusModel().calculated_review_status(self)
3705 3715
3706 3716 def reviewers_statuses(self):
3707 3717 from rhodecode.model.changeset_status import ChangesetStatusModel
3708 3718 return ChangesetStatusModel().reviewers_statuses(self)
3709 3719
3710 3720 @property
3711 3721 def workspace_id(self):
3712 3722 from rhodecode.model.pull_request import PullRequestModel
3713 3723 return PullRequestModel()._workspace_id(self)
3714 3724
3715 3725 def get_shadow_repo(self):
3716 3726 workspace_id = self.workspace_id
3717 3727 vcs_obj = self.target_repo.scm_instance()
3718 3728 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3719 3729 workspace_id)
3720 3730 return vcs_obj._get_shadow_instance(shadow_repository_path)
3721 3731
3722 3732
3723 3733 class PullRequestVersion(Base, _PullRequestBase):
3724 3734 __tablename__ = 'pull_request_versions'
3725 3735 __table_args__ = (
3726 3736 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3727 3737 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3728 3738 )
3729 3739
3730 3740 pull_request_version_id = Column(
3731 3741 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3732 3742 pull_request_id = Column(
3733 3743 'pull_request_id', Integer(),
3734 3744 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3735 3745 pull_request = relationship('PullRequest')
3736 3746
3737 3747 def __repr__(self):
3738 3748 if self.pull_request_version_id:
3739 3749 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3740 3750 else:
3741 3751 return '<DB:PullRequestVersion at %#x>' % id(self)
3742 3752
3743 3753 @property
3744 3754 def reviewers(self):
3745 3755 return self.pull_request.reviewers
3746 3756
3747 3757 @property
3748 3758 def versions(self):
3749 3759 return self.pull_request.versions
3750 3760
3751 3761 def is_closed(self):
3752 3762 # calculate from original
3753 3763 return self.pull_request.status == self.STATUS_CLOSED
3754 3764
3755 3765 def calculated_review_status(self):
3756 3766 return self.pull_request.calculated_review_status()
3757 3767
3758 3768 def reviewers_statuses(self):
3759 3769 return self.pull_request.reviewers_statuses()
3760 3770
3761 3771
3762 3772 class PullRequestReviewers(Base, BaseModel):
3763 3773 __tablename__ = 'pull_request_reviewers'
3764 3774 __table_args__ = (
3765 3775 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3766 3776 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3767 3777 )
3768 3778
3769 3779 @hybrid_property
3770 3780 def reasons(self):
3771 3781 if not self._reasons:
3772 3782 return []
3773 3783 return self._reasons
3774 3784
3775 3785 @reasons.setter
3776 3786 def reasons(self, val):
3777 3787 val = val or []
3778 3788 if any(not isinstance(x, basestring) for x in val):
3779 3789 raise Exception('invalid reasons type, must be list of strings')
3780 3790 self._reasons = val
3781 3791
3782 3792 pull_requests_reviewers_id = Column(
3783 3793 'pull_requests_reviewers_id', Integer(), nullable=False,
3784 3794 primary_key=True)
3785 3795 pull_request_id = Column(
3786 3796 "pull_request_id", Integer(),
3787 3797 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3788 3798 user_id = Column(
3789 3799 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3790 3800 _reasons = Column(
3791 3801 'reason', MutationList.as_mutable(
3792 3802 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3793 3803
3794 3804 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3795 3805 user = relationship('User')
3796 3806 pull_request = relationship('PullRequest')
3797 3807
3798 3808 rule_data = Column(
3799 3809 'rule_data_json',
3800 3810 JsonType(dialect_map=dict(mysql=UnicodeText(16384))))
3801 3811
3802 3812 def rule_user_group_data(self):
3803 3813 """
3804 3814 Returns the voting user group rule data for this reviewer
3805 3815 """
3806 3816
3807 3817 if self.rule_data and 'vote_rule' in self.rule_data:
3808 3818 user_group_data = {}
3809 3819 if 'rule_user_group_entry_id' in self.rule_data:
3810 3820 # means a group with voting rules !
3811 3821 user_group_data['id'] = self.rule_data['rule_user_group_entry_id']
3812 3822 user_group_data['name'] = self.rule_data['rule_name']
3813 3823 user_group_data['vote_rule'] = self.rule_data['vote_rule']
3814 3824
3815 3825 return user_group_data
3816 3826
3817 3827 def __unicode__(self):
3818 3828 return u"<%s('id:%s')>" % (self.__class__.__name__,
3819 3829 self.pull_requests_reviewers_id)
3820 3830
3821 3831
3822 3832 class Notification(Base, BaseModel):
3823 3833 __tablename__ = 'notifications'
3824 3834 __table_args__ = (
3825 3835 Index('notification_type_idx', 'type'),
3826 3836 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3827 3837 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3828 3838 )
3829 3839
3830 3840 TYPE_CHANGESET_COMMENT = u'cs_comment'
3831 3841 TYPE_MESSAGE = u'message'
3832 3842 TYPE_MENTION = u'mention'
3833 3843 TYPE_REGISTRATION = u'registration'
3834 3844 TYPE_PULL_REQUEST = u'pull_request'
3835 3845 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3836 3846
3837 3847 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3838 3848 subject = Column('subject', Unicode(512), nullable=True)
3839 3849 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3840 3850 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3841 3851 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3842 3852 type_ = Column('type', Unicode(255))
3843 3853
3844 3854 created_by_user = relationship('User')
3845 3855 notifications_to_users = relationship('UserNotification', lazy='joined',
3846 3856 cascade="all, delete, delete-orphan")
3847 3857
3848 3858 @property
3849 3859 def recipients(self):
3850 3860 return [x.user for x in UserNotification.query()\
3851 3861 .filter(UserNotification.notification == self)\
3852 3862 .order_by(UserNotification.user_id.asc()).all()]
3853 3863
3854 3864 @classmethod
3855 3865 def create(cls, created_by, subject, body, recipients, type_=None):
3856 3866 if type_ is None:
3857 3867 type_ = Notification.TYPE_MESSAGE
3858 3868
3859 3869 notification = cls()
3860 3870 notification.created_by_user = created_by
3861 3871 notification.subject = subject
3862 3872 notification.body = body
3863 3873 notification.type_ = type_
3864 3874 notification.created_on = datetime.datetime.now()
3865 3875
3866 3876 for u in recipients:
3867 3877 assoc = UserNotification()
3868 3878 assoc.notification = notification
3869 3879
3870 3880 # if created_by is inside recipients mark his notification
3871 3881 # as read
3872 3882 if u.user_id == created_by.user_id:
3873 3883 assoc.read = True
3874 3884
3875 3885 u.notifications.append(assoc)
3876 3886 Session().add(notification)
3877 3887
3878 3888 return notification
3879 3889
3880 3890
3881 3891 class UserNotification(Base, BaseModel):
3882 3892 __tablename__ = 'user_to_notification'
3883 3893 __table_args__ = (
3884 3894 UniqueConstraint('user_id', 'notification_id'),
3885 3895 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3886 3896 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3887 3897 )
3888 3898 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3889 3899 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3890 3900 read = Column('read', Boolean, default=False)
3891 3901 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3892 3902
3893 3903 user = relationship('User', lazy="joined")
3894 3904 notification = relationship('Notification', lazy="joined",
3895 3905 order_by=lambda: Notification.created_on.desc(),)
3896 3906
3897 3907 def mark_as_read(self):
3898 3908 self.read = True
3899 3909 Session().add(self)
3900 3910
3901 3911
3902 3912 class Gist(Base, BaseModel):
3903 3913 __tablename__ = 'gists'
3904 3914 __table_args__ = (
3905 3915 Index('g_gist_access_id_idx', 'gist_access_id'),
3906 3916 Index('g_created_on_idx', 'created_on'),
3907 3917 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3908 3918 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3909 3919 )
3910 3920 GIST_PUBLIC = u'public'
3911 3921 GIST_PRIVATE = u'private'
3912 3922 DEFAULT_FILENAME = u'gistfile1.txt'
3913 3923
3914 3924 ACL_LEVEL_PUBLIC = u'acl_public'
3915 3925 ACL_LEVEL_PRIVATE = u'acl_private'
3916 3926
3917 3927 gist_id = Column('gist_id', Integer(), primary_key=True)
3918 3928 gist_access_id = Column('gist_access_id', Unicode(250))
3919 3929 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3920 3930 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3921 3931 gist_expires = Column('gist_expires', Float(53), nullable=False)
3922 3932 gist_type = Column('gist_type', Unicode(128), nullable=False)
3923 3933 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3924 3934 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3925 3935 acl_level = Column('acl_level', Unicode(128), nullable=True)
3926 3936
3927 3937 owner = relationship('User')
3928 3938
3929 3939 def __repr__(self):
3930 3940 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3931 3941
3932 3942 @hybrid_property
3933 3943 def description_safe(self):
3934 3944 from rhodecode.lib import helpers as h
3935 3945 return h.escape(self.gist_description)
3936 3946
3937 3947 @classmethod
3938 3948 def get_or_404(cls, id_):
3939 3949 from pyramid.httpexceptions import HTTPNotFound
3940 3950
3941 3951 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3942 3952 if not res:
3943 3953 raise HTTPNotFound()
3944 3954 return res
3945 3955
3946 3956 @classmethod
3947 3957 def get_by_access_id(cls, gist_access_id):
3948 3958 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3949 3959
3950 3960 def gist_url(self):
3951 3961 from rhodecode.model.gist import GistModel
3952 3962 return GistModel().get_url(self)
3953 3963
3954 3964 @classmethod
3955 3965 def base_path(cls):
3956 3966 """
3957 3967 Returns base path when all gists are stored
3958 3968
3959 3969 :param cls:
3960 3970 """
3961 3971 from rhodecode.model.gist import GIST_STORE_LOC
3962 3972 q = Session().query(RhodeCodeUi)\
3963 3973 .filter(RhodeCodeUi.ui_key == URL_SEP)
3964 3974 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3965 3975 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3966 3976
3967 3977 def get_api_data(self):
3968 3978 """
3969 3979 Common function for generating gist related data for API
3970 3980 """
3971 3981 gist = self
3972 3982 data = {
3973 3983 'gist_id': gist.gist_id,
3974 3984 'type': gist.gist_type,
3975 3985 'access_id': gist.gist_access_id,
3976 3986 'description': gist.gist_description,
3977 3987 'url': gist.gist_url(),
3978 3988 'expires': gist.gist_expires,
3979 3989 'created_on': gist.created_on,
3980 3990 'modified_at': gist.modified_at,
3981 3991 'content': None,
3982 3992 'acl_level': gist.acl_level,
3983 3993 }
3984 3994 return data
3985 3995
3986 3996 def __json__(self):
3987 3997 data = dict(
3988 3998 )
3989 3999 data.update(self.get_api_data())
3990 4000 return data
3991 4001 # SCM functions
3992 4002
3993 4003 def scm_instance(self, **kwargs):
3994 4004 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3995 4005 return get_vcs_instance(
3996 4006 repo_path=safe_str(full_repo_path), create=False)
3997 4007
3998 4008
3999 4009 class ExternalIdentity(Base, BaseModel):
4000 4010 __tablename__ = 'external_identities'
4001 4011 __table_args__ = (
4002 4012 Index('local_user_id_idx', 'local_user_id'),
4003 4013 Index('external_id_idx', 'external_id'),
4004 4014 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4005 4015 'mysql_charset': 'utf8'})
4006 4016
4007 4017 external_id = Column('external_id', Unicode(255), default=u'',
4008 4018 primary_key=True)
4009 4019 external_username = Column('external_username', Unicode(1024), default=u'')
4010 4020 local_user_id = Column('local_user_id', Integer(),
4011 4021 ForeignKey('users.user_id'), primary_key=True)
4012 4022 provider_name = Column('provider_name', Unicode(255), default=u'',
4013 4023 primary_key=True)
4014 4024 access_token = Column('access_token', String(1024), default=u'')
4015 4025 alt_token = Column('alt_token', String(1024), default=u'')
4016 4026 token_secret = Column('token_secret', String(1024), default=u'')
4017 4027
4018 4028 @classmethod
4019 4029 def by_external_id_and_provider(cls, external_id, provider_name,
4020 4030 local_user_id=None):
4021 4031 """
4022 4032 Returns ExternalIdentity instance based on search params
4023 4033
4024 4034 :param external_id:
4025 4035 :param provider_name:
4026 4036 :return: ExternalIdentity
4027 4037 """
4028 4038 query = cls.query()
4029 4039 query = query.filter(cls.external_id == external_id)
4030 4040 query = query.filter(cls.provider_name == provider_name)
4031 4041 if local_user_id:
4032 4042 query = query.filter(cls.local_user_id == local_user_id)
4033 4043 return query.first()
4034 4044
4035 4045 @classmethod
4036 4046 def user_by_external_id_and_provider(cls, external_id, provider_name):
4037 4047 """
4038 4048 Returns User instance based on search params
4039 4049
4040 4050 :param external_id:
4041 4051 :param provider_name:
4042 4052 :return: User
4043 4053 """
4044 4054 query = User.query()
4045 4055 query = query.filter(cls.external_id == external_id)
4046 4056 query = query.filter(cls.provider_name == provider_name)
4047 4057 query = query.filter(User.user_id == cls.local_user_id)
4048 4058 return query.first()
4049 4059
4050 4060 @classmethod
4051 4061 def by_local_user_id(cls, local_user_id):
4052 4062 """
4053 4063 Returns all tokens for user
4054 4064
4055 4065 :param local_user_id:
4056 4066 :return: ExternalIdentity
4057 4067 """
4058 4068 query = cls.query()
4059 4069 query = query.filter(cls.local_user_id == local_user_id)
4060 4070 return query
4061 4071
4062 4072
4063 4073 class Integration(Base, BaseModel):
4064 4074 __tablename__ = 'integrations'
4065 4075 __table_args__ = (
4066 4076 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4067 4077 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
4068 4078 )
4069 4079
4070 4080 integration_id = Column('integration_id', Integer(), primary_key=True)
4071 4081 integration_type = Column('integration_type', String(255))
4072 4082 enabled = Column('enabled', Boolean(), nullable=False)
4073 4083 name = Column('name', String(255), nullable=False)
4074 4084 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
4075 4085 default=False)
4076 4086
4077 4087 settings = Column(
4078 4088 'settings_json', MutationObj.as_mutable(
4079 4089 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
4080 4090 repo_id = Column(
4081 4091 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
4082 4092 nullable=True, unique=None, default=None)
4083 4093 repo = relationship('Repository', lazy='joined')
4084 4094
4085 4095 repo_group_id = Column(
4086 4096 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
4087 4097 nullable=True, unique=None, default=None)
4088 4098 repo_group = relationship('RepoGroup', lazy='joined')
4089 4099
4090 4100 @property
4091 4101 def scope(self):
4092 4102 if self.repo:
4093 4103 return repr(self.repo)
4094 4104 if self.repo_group:
4095 4105 if self.child_repos_only:
4096 4106 return repr(self.repo_group) + ' (child repos only)'
4097 4107 else:
4098 4108 return repr(self.repo_group) + ' (recursive)'
4099 4109 if self.child_repos_only:
4100 4110 return 'root_repos'
4101 4111 return 'global'
4102 4112
4103 4113 def __repr__(self):
4104 4114 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4105 4115
4106 4116
4107 4117 class RepoReviewRuleUser(Base, BaseModel):
4108 4118 __tablename__ = 'repo_review_rules_users'
4109 4119 __table_args__ = (
4110 4120 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4111 4121 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4112 4122 )
4113 4123
4114 4124 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4115 4125 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4116 4126 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4117 4127 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4118 4128 user = relationship('User')
4119 4129
4120 4130 def rule_data(self):
4121 4131 return {
4122 4132 'mandatory': self.mandatory
4123 4133 }
4124 4134
4125 4135
4126 4136 class RepoReviewRuleUserGroup(Base, BaseModel):
4127 4137 __tablename__ = 'repo_review_rules_users_groups'
4128 4138 __table_args__ = (
4129 4139 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4130 4140 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4131 4141 )
4132 4142 VOTE_RULE_ALL = -1
4133 4143
4134 4144 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4135 4145 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4136 4146 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4137 4147 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4138 4148 vote_rule = Column("vote_rule", Integer(), nullable=True, default=VOTE_RULE_ALL)
4139 4149 users_group = relationship('UserGroup')
4140 4150
4141 4151 def rule_data(self):
4142 4152 return {
4143 4153 'mandatory': self.mandatory,
4144 4154 'vote_rule': self.vote_rule
4145 4155 }
4146 4156
4147 4157 @property
4148 4158 def vote_rule_label(self):
4149 4159 if not self.vote_rule or self.vote_rule == self.VOTE_RULE_ALL:
4150 4160 return 'all must vote'
4151 4161 else:
4152 4162 return 'min. vote {}'.format(self.vote_rule)
4153 4163
4154 4164
4155 4165 class RepoReviewRule(Base, BaseModel):
4156 4166 __tablename__ = 'repo_review_rules'
4157 4167 __table_args__ = (
4158 4168 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4159 4169 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4160 4170 )
4161 4171
4162 4172 repo_review_rule_id = Column(
4163 4173 'repo_review_rule_id', Integer(), primary_key=True)
4164 4174 repo_id = Column(
4165 4175 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4166 4176 repo = relationship('Repository', backref='review_rules')
4167 4177
4168 4178 review_rule_name = Column('review_rule_name', String(255))
4169 4179 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4170 4180 _target_branch_pattern = Column("target_branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4171 4181 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4172 4182
4173 4183 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4174 4184 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4175 4185 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4176 4186 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4177 4187
4178 4188 rule_users = relationship('RepoReviewRuleUser')
4179 4189 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4180 4190
4181 4191 def _validate_glob(self, value):
4182 4192 re.compile('^' + glob2re(value) + '$')
4183 4193
4184 4194 @hybrid_property
4185 4195 def source_branch_pattern(self):
4186 4196 return self._branch_pattern or '*'
4187 4197
4188 4198 @source_branch_pattern.setter
4189 4199 def source_branch_pattern(self, value):
4190 4200 self._validate_glob(value)
4191 4201 self._branch_pattern = value or '*'
4192 4202
4193 4203 @hybrid_property
4194 4204 def target_branch_pattern(self):
4195 4205 return self._target_branch_pattern or '*'
4196 4206
4197 4207 @target_branch_pattern.setter
4198 4208 def target_branch_pattern(self, value):
4199 4209 self._validate_glob(value)
4200 4210 self._target_branch_pattern = value or '*'
4201 4211
4202 4212 @hybrid_property
4203 4213 def file_pattern(self):
4204 4214 return self._file_pattern or '*'
4205 4215
4206 4216 @file_pattern.setter
4207 4217 def file_pattern(self, value):
4208 4218 self._validate_glob(value)
4209 4219 self._file_pattern = value or '*'
4210 4220
4211 4221 def matches(self, source_branch, target_branch, files_changed):
4212 4222 """
4213 4223 Check if this review rule matches a branch/files in a pull request
4214 4224
4215 4225 :param branch: branch name for the commit
4216 4226 :param files_changed: list of file paths changed in the pull request
4217 4227 """
4218 4228
4219 4229 source_branch = source_branch or ''
4220 4230 target_branch = target_branch or ''
4221 4231 files_changed = files_changed or []
4222 4232
4223 4233 branch_matches = True
4224 4234 if source_branch or target_branch:
4225 4235 source_branch_regex = re.compile(
4226 4236 '^' + glob2re(self.source_branch_pattern) + '$')
4227 4237 target_branch_regex = re.compile(
4228 4238 '^' + glob2re(self.target_branch_pattern) + '$')
4229 4239
4230 4240 branch_matches = (
4231 4241 bool(source_branch_regex.search(source_branch)) and
4232 4242 bool(target_branch_regex.search(target_branch))
4233 4243 )
4234 4244
4235 4245 files_matches = True
4236 4246 if self.file_pattern != '*':
4237 4247 files_matches = False
4238 4248 file_regex = re.compile(glob2re(self.file_pattern))
4239 4249 for filename in files_changed:
4240 4250 if file_regex.search(filename):
4241 4251 files_matches = True
4242 4252 break
4243 4253
4244 4254 return branch_matches and files_matches
4245 4255
4246 4256 @property
4247 4257 def review_users(self):
4248 4258 """ Returns the users which this rule applies to """
4249 4259
4250 4260 users = collections.OrderedDict()
4251 4261
4252 4262 for rule_user in self.rule_users:
4253 4263 if rule_user.user.active:
4254 4264 if rule_user.user not in users:
4255 4265 users[rule_user.user.username] = {
4256 4266 'user': rule_user.user,
4257 4267 'source': 'user',
4258 4268 'source_data': {},
4259 4269 'data': rule_user.rule_data()
4260 4270 }
4261 4271
4262 4272 for rule_user_group in self.rule_user_groups:
4263 4273 source_data = {
4264 4274 'user_group_id': rule_user_group.users_group.users_group_id,
4265 4275 'name': rule_user_group.users_group.users_group_name,
4266 4276 'members': len(rule_user_group.users_group.members)
4267 4277 }
4268 4278 for member in rule_user_group.users_group.members:
4269 4279 if member.user.active:
4270 4280 key = member.user.username
4271 4281 if key in users:
4272 4282 # skip this member as we have him already
4273 4283 # this prevents from override the "first" matched
4274 4284 # users with duplicates in multiple groups
4275 4285 continue
4276 4286
4277 4287 users[key] = {
4278 4288 'user': member.user,
4279 4289 'source': 'user_group',
4280 4290 'source_data': source_data,
4281 4291 'data': rule_user_group.rule_data()
4282 4292 }
4283 4293
4284 4294 return users
4285 4295
4286 4296 def user_group_vote_rule(self):
4287 4297 rules = []
4288 4298 if self.rule_user_groups:
4289 4299 for user_group in self.rule_user_groups:
4290 4300 rules.append(user_group)
4291 4301 return rules
4292 4302
4293 4303 def __repr__(self):
4294 4304 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4295 4305 self.repo_review_rule_id, self.repo)
4296 4306
4297 4307
4298 4308 class ScheduleEntry(Base, BaseModel):
4299 4309 __tablename__ = 'schedule_entries'
4300 4310 __table_args__ = (
4301 4311 UniqueConstraint('schedule_name', name='s_schedule_name_idx'),
4302 4312 UniqueConstraint('task_uid', name='s_task_uid_idx'),
4303 4313 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4304 4314 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4305 4315 )
4306 4316 schedule_types = ['crontab', 'timedelta', 'integer']
4307 4317 schedule_entry_id = Column('schedule_entry_id', Integer(), primary_key=True)
4308 4318
4309 4319 schedule_name = Column("schedule_name", String(255), nullable=False, unique=None, default=None)
4310 4320 schedule_description = Column("schedule_description", String(10000), nullable=True, unique=None, default=None)
4311 4321 schedule_enabled = Column("schedule_enabled", Boolean(), nullable=False, unique=None, default=True)
4312 4322
4313 4323 _schedule_type = Column("schedule_type", String(255), nullable=False, unique=None, default=None)
4314 4324 schedule_definition = Column('schedule_definition_json', MutationObj.as_mutable(JsonType(default=lambda: "", dialect_map=dict(mysql=LONGTEXT()))))
4315 4325
4316 4326 schedule_last_run = Column('schedule_last_run', DateTime(timezone=False), nullable=True, unique=None, default=None)
4317 4327 schedule_total_run_count = Column('schedule_total_run_count', Integer(), nullable=True, unique=None, default=0)
4318 4328
4319 4329 # task
4320 4330 task_uid = Column("task_uid", String(255), nullable=False, unique=None, default=None)
4321 4331 task_dot_notation = Column("task_dot_notation", String(4096), nullable=False, unique=None, default=None)
4322 4332 task_args = Column('task_args_json', MutationObj.as_mutable(JsonType(default=list, dialect_map=dict(mysql=LONGTEXT()))))
4323 4333 task_kwargs = Column('task_kwargs_json', MutationObj.as_mutable(JsonType(default=dict, dialect_map=dict(mysql=LONGTEXT()))))
4324 4334
4325 4335 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
4326 4336 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=None)
4327 4337
4328 4338 @hybrid_property
4329 4339 def schedule_type(self):
4330 4340 return self._schedule_type
4331 4341
4332 4342 @schedule_type.setter
4333 4343 def schedule_type(self, val):
4334 4344 if val not in self.schedule_types:
4335 4345 raise ValueError('Value must be on of `{}` and got `{}`'.format(
4336 4346 val, self.schedule_type))
4337 4347
4338 4348 self._schedule_type = val
4339 4349
4340 4350 @classmethod
4341 4351 def get_uid(cls, obj):
4342 4352 args = obj.task_args
4343 4353 kwargs = obj.task_kwargs
4344 4354 if isinstance(args, JsonRaw):
4345 4355 try:
4346 4356 args = json.loads(args)
4347 4357 except ValueError:
4348 4358 args = tuple()
4349 4359
4350 4360 if isinstance(kwargs, JsonRaw):
4351 4361 try:
4352 4362 kwargs = json.loads(kwargs)
4353 4363 except ValueError:
4354 4364 kwargs = dict()
4355 4365
4356 4366 dot_notation = obj.task_dot_notation
4357 4367 val = '.'.join(map(safe_str, [
4358 4368 sorted(dot_notation), args, sorted(kwargs.items())]))
4359 4369 return hashlib.sha1(val).hexdigest()
4360 4370
4361 4371 @classmethod
4362 4372 def get_by_schedule_name(cls, schedule_name):
4363 4373 return cls.query().filter(cls.schedule_name == schedule_name).scalar()
4364 4374
4365 4375 @classmethod
4366 4376 def get_by_schedule_id(cls, schedule_id):
4367 4377 return cls.query().filter(cls.schedule_entry_id == schedule_id).scalar()
4368 4378
4369 4379 @property
4370 4380 def task(self):
4371 4381 return self.task_dot_notation
4372 4382
4373 4383 @property
4374 4384 def schedule(self):
4375 4385 from rhodecode.lib.celerylib.utils import raw_2_schedule
4376 4386 schedule = raw_2_schedule(self.schedule_definition, self.schedule_type)
4377 4387 return schedule
4378 4388
4379 4389 @property
4380 4390 def args(self):
4381 4391 try:
4382 4392 return list(self.task_args or [])
4383 4393 except ValueError:
4384 4394 return list()
4385 4395
4386 4396 @property
4387 4397 def kwargs(self):
4388 4398 try:
4389 4399 return dict(self.task_kwargs or {})
4390 4400 except ValueError:
4391 4401 return dict()
4392 4402
4393 4403 def _as_raw(self, val):
4394 4404 if hasattr(val, 'de_coerce'):
4395 4405 val = val.de_coerce()
4396 4406 if val:
4397 4407 val = json.dumps(val)
4398 4408
4399 4409 return val
4400 4410
4401 4411 @property
4402 4412 def schedule_definition_raw(self):
4403 4413 return self._as_raw(self.schedule_definition)
4404 4414
4405 4415 @property
4406 4416 def args_raw(self):
4407 4417 return self._as_raw(self.task_args)
4408 4418
4409 4419 @property
4410 4420 def kwargs_raw(self):
4411 4421 return self._as_raw(self.task_kwargs)
4412 4422
4413 4423 def __repr__(self):
4414 4424 return '<DB:ScheduleEntry({}:{})>'.format(
4415 4425 self.schedule_entry_id, self.schedule_name)
4416 4426
4417 4427
4418 4428 @event.listens_for(ScheduleEntry, 'before_update')
4419 4429 def update_task_uid(mapper, connection, target):
4420 4430 target.task_uid = ScheduleEntry.get_uid(target)
4421 4431
4422 4432
4423 4433 @event.listens_for(ScheduleEntry, 'before_insert')
4424 4434 def set_task_uid(mapper, connection, target):
4425 4435 target.task_uid = ScheduleEntry.get_uid(target)
4426 4436
4427 4437
4428 4438 class DbMigrateVersion(Base, BaseModel):
4429 4439 __tablename__ = 'db_migrate_version'
4430 4440 __table_args__ = (
4431 4441 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4432 4442 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4433 4443 )
4434 4444 repository_id = Column('repository_id', String(250), primary_key=True)
4435 4445 repository_path = Column('repository_path', Text)
4436 4446 version = Column('version', Integer)
4437 4447
4438 4448
4439 4449 class DbSession(Base, BaseModel):
4440 4450 __tablename__ = 'db_session'
4441 4451 __table_args__ = (
4442 4452 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4443 4453 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4444 4454 )
4445 4455
4446 4456 def __repr__(self):
4447 4457 return '<DB:DbSession({})>'.format(self.id)
4448 4458
4449 4459 id = Column('id', Integer())
4450 4460 namespace = Column('namespace', String(255), primary_key=True)
4451 4461 accessed = Column('accessed', DateTime, nullable=False)
4452 4462 created = Column('created', DateTime, nullable=False)
4453 4463 data = Column('data', PickleType, nullable=False)
@@ -1,615 +1,616 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 """
22 22 this is forms validation classes
23 23 http://formencode.org/module-formencode.validators.html
24 24 for list off all availible validators
25 25
26 26 we can create our own validators
27 27
28 28 The table below outlines the options which can be used in a schema in addition to the validators themselves
29 29 pre_validators [] These validators will be applied before the schema
30 30 chained_validators [] These validators will be applied after the schema
31 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 32 filter_extra_fields False If True, then keys that aren't associated with a validator are removed
33 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 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 37 <name> = formencode.validators.<name of validator>
38 38 <name> must equal form name
39 39 list=[1,2,3,4,5]
40 40 for SELECT use formencode.All(OneOf(list), Int())
41 41
42 42 """
43 43
44 44 import deform
45 45 import logging
46 46 import formencode
47 47
48 48 from pkg_resources import resource_filename
49 49 from formencode import All, Pipe
50 50
51 51 from pyramid.threadlocal import get_current_request
52 52
53 53 from rhodecode import BACKENDS
54 54 from rhodecode.lib import helpers
55 55 from rhodecode.model import validators as v
56 56
57 57 log = logging.getLogger(__name__)
58 58
59 59
60 60 deform_templates = resource_filename('deform', 'templates')
61 61 rhodecode_templates = resource_filename('rhodecode', 'templates/forms')
62 62 search_path = (rhodecode_templates, deform_templates)
63 63
64 64
65 65 class RhodecodeFormZPTRendererFactory(deform.ZPTRendererFactory):
66 66 """ Subclass of ZPTRendererFactory to add rhodecode context variables """
67 67 def __call__(self, template_name, **kw):
68 68 kw['h'] = helpers
69 69 kw['request'] = get_current_request()
70 70 return self.load(template_name)(**kw)
71 71
72 72
73 73 form_renderer = RhodecodeFormZPTRendererFactory(search_path)
74 74 deform.Form.set_default_renderer(form_renderer)
75 75
76 76
77 77 def LoginForm(localizer):
78 78 _ = localizer
79 79
80 80 class _LoginForm(formencode.Schema):
81 81 allow_extra_fields = True
82 82 filter_extra_fields = True
83 83 username = v.UnicodeString(
84 84 strip=True,
85 85 min=1,
86 86 not_empty=True,
87 87 messages={
88 88 'empty': _(u'Please enter a login'),
89 89 'tooShort': _(u'Enter a value %(min)i characters long or more')
90 90 }
91 91 )
92 92
93 93 password = v.UnicodeString(
94 94 strip=False,
95 95 min=3,
96 96 max=72,
97 97 not_empty=True,
98 98 messages={
99 99 'empty': _(u'Please enter a password'),
100 100 'tooShort': _(u'Enter %(min)i characters or more')}
101 101 )
102 102
103 103 remember = v.StringBoolean(if_missing=False)
104 104
105 105 chained_validators = [v.ValidAuth(localizer)]
106 106 return _LoginForm
107 107
108 108
109 109 def UserForm(localizer, edit=False, available_languages=None, old_data=None):
110 110 old_data = old_data or {}
111 111 available_languages = available_languages or []
112 112 _ = localizer
113 113
114 114 class _UserForm(formencode.Schema):
115 115 allow_extra_fields = True
116 116 filter_extra_fields = True
117 117 username = All(v.UnicodeString(strip=True, min=1, not_empty=True),
118 118 v.ValidUsername(localizer, edit, old_data))
119 119 if edit:
120 120 new_password = All(
121 121 v.ValidPassword(localizer),
122 122 v.UnicodeString(strip=False, min=6, max=72, not_empty=False)
123 123 )
124 124 password_confirmation = All(
125 125 v.ValidPassword(localizer),
126 126 v.UnicodeString(strip=False, min=6, max=72, not_empty=False),
127 127 )
128 128 admin = v.StringBoolean(if_missing=False)
129 129 else:
130 130 password = All(
131 131 v.ValidPassword(localizer),
132 132 v.UnicodeString(strip=False, min=6, max=72, not_empty=True)
133 133 )
134 134 password_confirmation = All(
135 135 v.ValidPassword(localizer),
136 136 v.UnicodeString(strip=False, min=6, max=72, not_empty=False)
137 137 )
138 138
139 139 password_change = v.StringBoolean(if_missing=False)
140 140 create_repo_group = v.StringBoolean(if_missing=False)
141 141
142 142 active = v.StringBoolean(if_missing=False)
143 143 firstname = v.UnicodeString(strip=True, min=1, not_empty=False)
144 144 lastname = v.UnicodeString(strip=True, min=1, not_empty=False)
145 145 email = All(v.UniqSystemEmail(localizer, old_data), v.Email(not_empty=True))
146 146 extern_name = v.UnicodeString(strip=True)
147 147 extern_type = v.UnicodeString(strip=True)
148 148 language = v.OneOf(available_languages, hideList=False,
149 149 testValueList=True, if_missing=None)
150 150 chained_validators = [v.ValidPasswordsMatch(localizer)]
151 151 return _UserForm
152 152
153 153
154 154 def UserGroupForm(localizer, edit=False, old_data=None, allow_disabled=False):
155 155 old_data = old_data or {}
156 156 _ = localizer
157 157
158 158 class _UserGroupForm(formencode.Schema):
159 159 allow_extra_fields = True
160 160 filter_extra_fields = True
161 161
162 162 users_group_name = All(
163 163 v.UnicodeString(strip=True, min=1, not_empty=True),
164 164 v.ValidUserGroup(localizer, edit, old_data)
165 165 )
166 166 user_group_description = v.UnicodeString(strip=True, min=1,
167 167 not_empty=False)
168 168
169 169 users_group_active = v.StringBoolean(if_missing=False)
170 170
171 171 if edit:
172 172 # this is user group owner
173 173 user = All(
174 174 v.UnicodeString(not_empty=True),
175 175 v.ValidRepoUser(localizer, allow_disabled))
176 176 return _UserGroupForm
177 177
178 178
179 179 def RepoGroupForm(localizer, edit=False, old_data=None, available_groups=None,
180 180 can_create_in_root=False, allow_disabled=False):
181 181 _ = localizer
182 182 old_data = old_data or {}
183 183 available_groups = available_groups or []
184 184
185 185 class _RepoGroupForm(formencode.Schema):
186 186 allow_extra_fields = True
187 187 filter_extra_fields = False
188 188
189 189 group_name = All(v.UnicodeString(strip=True, min=1, not_empty=True),
190 190 v.SlugifyName(localizer),)
191 191 group_description = v.UnicodeString(strip=True, min=1,
192 192 not_empty=False)
193 193 group_copy_permissions = v.StringBoolean(if_missing=False)
194 194
195 195 group_parent_id = v.OneOf(available_groups, hideList=False,
196 196 testValueList=True, not_empty=True)
197 197 enable_locking = v.StringBoolean(if_missing=False)
198 198 chained_validators = [
199 199 v.ValidRepoGroup(localizer, edit, old_data, can_create_in_root)]
200 200
201 201 if edit:
202 202 # this is repo group owner
203 203 user = All(
204 204 v.UnicodeString(not_empty=True),
205 205 v.ValidRepoUser(localizer, allow_disabled))
206 206 return _RepoGroupForm
207 207
208 208
209 209 def RegisterForm(localizer, edit=False, old_data=None):
210 210 _ = localizer
211 211 old_data = old_data or {}
212 212
213 213 class _RegisterForm(formencode.Schema):
214 214 allow_extra_fields = True
215 215 filter_extra_fields = True
216 216 username = All(
217 217 v.ValidUsername(localizer, edit, old_data),
218 218 v.UnicodeString(strip=True, min=1, not_empty=True)
219 219 )
220 220 password = All(
221 221 v.ValidPassword(localizer),
222 222 v.UnicodeString(strip=False, min=6, max=72, not_empty=True)
223 223 )
224 224 password_confirmation = All(
225 225 v.ValidPassword(localizer),
226 226 v.UnicodeString(strip=False, min=6, max=72, not_empty=True)
227 227 )
228 228 active = v.StringBoolean(if_missing=False)
229 229 firstname = v.UnicodeString(strip=True, min=1, not_empty=False)
230 230 lastname = v.UnicodeString(strip=True, min=1, not_empty=False)
231 231 email = All(v.UniqSystemEmail(localizer, old_data), v.Email(not_empty=True))
232 232
233 233 chained_validators = [v.ValidPasswordsMatch(localizer)]
234 234 return _RegisterForm
235 235
236 236
237 237 def PasswordResetForm(localizer):
238 238 _ = localizer
239 239
240 240 class _PasswordResetForm(formencode.Schema):
241 241 allow_extra_fields = True
242 242 filter_extra_fields = True
243 243 email = All(v.ValidSystemEmail(localizer), v.Email(not_empty=True))
244 244 return _PasswordResetForm
245 245
246 246
247 247 def RepoForm(localizer, edit=False, old_data=None, repo_groups=None,
248 248 landing_revs=None, allow_disabled=False):
249 249 _ = localizer
250 250 old_data = old_data or {}
251 251 repo_groups = repo_groups or []
252 252 landing_revs = landing_revs or []
253 253 supported_backends = BACKENDS.keys()
254 254
255 255 class _RepoForm(formencode.Schema):
256 256 allow_extra_fields = True
257 257 filter_extra_fields = False
258 258 repo_name = All(v.UnicodeString(strip=True, min=1, not_empty=True),
259 259 v.SlugifyName(localizer), v.CannotHaveGitSuffix(localizer))
260 260 repo_group = All(v.CanWriteGroup(localizer, old_data),
261 261 v.OneOf(repo_groups, hideList=True))
262 262 repo_type = v.OneOf(supported_backends, required=False,
263 263 if_missing=old_data.get('repo_type'))
264 264 repo_description = v.UnicodeString(strip=True, min=1, not_empty=False)
265 265 repo_private = v.StringBoolean(if_missing=False)
266 266 repo_landing_rev = v.OneOf(landing_revs, hideList=True)
267 267 repo_copy_permissions = v.StringBoolean(if_missing=False)
268 268 clone_uri = All(v.UnicodeString(strip=True, min=1, not_empty=False))
269 269
270 270 repo_enable_statistics = v.StringBoolean(if_missing=False)
271 271 repo_enable_downloads = v.StringBoolean(if_missing=False)
272 272 repo_enable_locking = v.StringBoolean(if_missing=False)
273 273
274 274 if edit:
275 275 # this is repo owner
276 276 user = All(
277 277 v.UnicodeString(not_empty=True),
278 278 v.ValidRepoUser(localizer, allow_disabled))
279 279 clone_uri_change = v.UnicodeString(
280 280 not_empty=False, if_missing=v.Missing)
281 281
282 282 chained_validators = [v.ValidCloneUri(localizer),
283 283 v.ValidRepoName(localizer, edit, old_data)]
284 284 return _RepoForm
285 285
286 286
287 287 def RepoPermsForm(localizer):
288 288 _ = localizer
289 289
290 290 class _RepoPermsForm(formencode.Schema):
291 291 allow_extra_fields = True
292 292 filter_extra_fields = False
293 293 chained_validators = [v.ValidPerms(localizer, type_='repo')]
294 294 return _RepoPermsForm
295 295
296 296
297 297 def RepoGroupPermsForm(localizer, valid_recursive_choices):
298 298 _ = localizer
299 299
300 300 class _RepoGroupPermsForm(formencode.Schema):
301 301 allow_extra_fields = True
302 302 filter_extra_fields = False
303 303 recursive = v.OneOf(valid_recursive_choices)
304 304 chained_validators = [v.ValidPerms(localizer, type_='repo_group')]
305 305 return _RepoGroupPermsForm
306 306
307 307
308 308 def UserGroupPermsForm(localizer):
309 309 _ = localizer
310 310
311 311 class _UserPermsForm(formencode.Schema):
312 312 allow_extra_fields = True
313 313 filter_extra_fields = False
314 314 chained_validators = [v.ValidPerms(localizer, type_='user_group')]
315 315 return _UserPermsForm
316 316
317 317
318 318 def RepoFieldForm(localizer):
319 319 _ = localizer
320 320
321 321 class _RepoFieldForm(formencode.Schema):
322 322 filter_extra_fields = True
323 323 allow_extra_fields = True
324 324
325 325 new_field_key = All(v.FieldKey(localizer),
326 326 v.UnicodeString(strip=True, min=3, not_empty=True))
327 327 new_field_value = v.UnicodeString(not_empty=False, if_missing=u'')
328 328 new_field_type = v.OneOf(['str', 'unicode', 'list', 'tuple'],
329 329 if_missing='str')
330 330 new_field_label = v.UnicodeString(not_empty=False)
331 331 new_field_desc = v.UnicodeString(not_empty=False)
332 332 return _RepoFieldForm
333 333
334 334
335 335 def RepoForkForm(localizer, edit=False, old_data=None,
336 336 supported_backends=BACKENDS.keys(), repo_groups=None,
337 337 landing_revs=None):
338 338 _ = localizer
339 339 old_data = old_data or {}
340 340 repo_groups = repo_groups or []
341 341 landing_revs = landing_revs or []
342 342
343 343 class _RepoForkForm(formencode.Schema):
344 344 allow_extra_fields = True
345 345 filter_extra_fields = False
346 346 repo_name = All(v.UnicodeString(strip=True, min=1, not_empty=True),
347 347 v.SlugifyName(localizer))
348 348 repo_group = All(v.CanWriteGroup(localizer, ),
349 349 v.OneOf(repo_groups, hideList=True))
350 350 repo_type = All(v.ValidForkType(localizer, old_data), v.OneOf(supported_backends))
351 351 description = v.UnicodeString(strip=True, min=1, not_empty=True)
352 352 private = v.StringBoolean(if_missing=False)
353 353 copy_permissions = v.StringBoolean(if_missing=False)
354 354 fork_parent_id = v.UnicodeString()
355 355 chained_validators = [v.ValidForkName(localizer, edit, old_data)]
356 356 landing_rev = v.OneOf(landing_revs, hideList=True)
357 357 return _RepoForkForm
358 358
359 359
360 360 def ApplicationSettingsForm(localizer):
361 361 _ = localizer
362 362
363 363 class _ApplicationSettingsForm(formencode.Schema):
364 364 allow_extra_fields = True
365 365 filter_extra_fields = False
366 366 rhodecode_title = v.UnicodeString(strip=True, max=40, not_empty=False)
367 367 rhodecode_realm = v.UnicodeString(strip=True, min=1, not_empty=True)
368 368 rhodecode_pre_code = v.UnicodeString(strip=True, min=1, not_empty=False)
369 369 rhodecode_post_code = v.UnicodeString(strip=True, min=1, not_empty=False)
370 370 rhodecode_captcha_public_key = v.UnicodeString(strip=True, min=1, not_empty=False)
371 371 rhodecode_captcha_private_key = v.UnicodeString(strip=True, min=1, not_empty=False)
372 372 rhodecode_create_personal_repo_group = v.StringBoolean(if_missing=False)
373 373 rhodecode_personal_repo_group_pattern = v.UnicodeString(strip=True, min=1, not_empty=False)
374 374 return _ApplicationSettingsForm
375 375
376 376
377 377 def ApplicationVisualisationForm(localizer):
378 378 _ = localizer
379 379
380 380 class _ApplicationVisualisationForm(formencode.Schema):
381 381 allow_extra_fields = True
382 382 filter_extra_fields = False
383 383 rhodecode_show_public_icon = v.StringBoolean(if_missing=False)
384 384 rhodecode_show_private_icon = v.StringBoolean(if_missing=False)
385 385 rhodecode_stylify_metatags = v.StringBoolean(if_missing=False)
386 386
387 387 rhodecode_repository_fields = v.StringBoolean(if_missing=False)
388 388 rhodecode_lightweight_journal = v.StringBoolean(if_missing=False)
389 389 rhodecode_dashboard_items = v.Int(min=5, not_empty=True)
390 390 rhodecode_admin_grid_items = v.Int(min=5, not_empty=True)
391 391 rhodecode_show_version = v.StringBoolean(if_missing=False)
392 392 rhodecode_use_gravatar = v.StringBoolean(if_missing=False)
393 393 rhodecode_markup_renderer = v.OneOf(['markdown', 'rst'])
394 394 rhodecode_gravatar_url = v.UnicodeString(min=3)
395 395 rhodecode_clone_uri_tmpl = v.UnicodeString(min=3)
396 rhodecode_clone_uri_ssh_tmpl = v.UnicodeString(min=3)
396 397 rhodecode_support_url = v.UnicodeString()
397 398 rhodecode_show_revision_number = v.StringBoolean(if_missing=False)
398 399 rhodecode_show_sha_length = v.Int(min=4, not_empty=True)
399 400 return _ApplicationVisualisationForm
400 401
401 402
402 403 class _BaseVcsSettingsForm(formencode.Schema):
403 404
404 405 allow_extra_fields = True
405 406 filter_extra_fields = False
406 407 hooks_changegroup_repo_size = v.StringBoolean(if_missing=False)
407 408 hooks_changegroup_push_logger = v.StringBoolean(if_missing=False)
408 409 hooks_outgoing_pull_logger = v.StringBoolean(if_missing=False)
409 410
410 411 # PR/Code-review
411 412 rhodecode_pr_merge_enabled = v.StringBoolean(if_missing=False)
412 413 rhodecode_use_outdated_comments = v.StringBoolean(if_missing=False)
413 414
414 415 # hg
415 416 extensions_largefiles = v.StringBoolean(if_missing=False)
416 417 extensions_evolve = v.StringBoolean(if_missing=False)
417 418 phases_publish = v.StringBoolean(if_missing=False)
418 419
419 420 rhodecode_hg_use_rebase_for_merging = v.StringBoolean(if_missing=False)
420 421 rhodecode_hg_close_branch_before_merging = v.StringBoolean(if_missing=False)
421 422
422 423 # git
423 424 vcs_git_lfs_enabled = v.StringBoolean(if_missing=False)
424 425 rhodecode_git_use_rebase_for_merging = v.StringBoolean(if_missing=False)
425 426 rhodecode_git_close_branch_before_merging = v.StringBoolean(if_missing=False)
426 427
427 428 # svn
428 429 vcs_svn_proxy_http_requests_enabled = v.StringBoolean(if_missing=False)
429 430 vcs_svn_proxy_http_server_url = v.UnicodeString(strip=True, if_missing=None)
430 431
431 432
432 433 def ApplicationUiSettingsForm(localizer):
433 434 _ = localizer
434 435
435 436 class _ApplicationUiSettingsForm(_BaseVcsSettingsForm):
436 437 web_push_ssl = v.StringBoolean(if_missing=False)
437 438 paths_root_path = All(
438 439 v.ValidPath(localizer),
439 440 v.UnicodeString(strip=True, min=1, not_empty=True)
440 441 )
441 442 largefiles_usercache = All(
442 443 v.ValidPath(localizer),
443 444 v.UnicodeString(strip=True, min=2, not_empty=True))
444 445 vcs_git_lfs_store_location = All(
445 446 v.ValidPath(localizer),
446 447 v.UnicodeString(strip=True, min=2, not_empty=True))
447 448 extensions_hgsubversion = v.StringBoolean(if_missing=False)
448 449 extensions_hggit = v.StringBoolean(if_missing=False)
449 450 new_svn_branch = v.ValidSvnPattern(localizer, section='vcs_svn_branch')
450 451 new_svn_tag = v.ValidSvnPattern(localizer, section='vcs_svn_tag')
451 452 return _ApplicationUiSettingsForm
452 453
453 454
454 455 def RepoVcsSettingsForm(localizer, repo_name):
455 456 _ = localizer
456 457
457 458 class _RepoVcsSettingsForm(_BaseVcsSettingsForm):
458 459 inherit_global_settings = v.StringBoolean(if_missing=False)
459 460 new_svn_branch = v.ValidSvnPattern(localizer,
460 461 section='vcs_svn_branch', repo_name=repo_name)
461 462 new_svn_tag = v.ValidSvnPattern(localizer,
462 463 section='vcs_svn_tag', repo_name=repo_name)
463 464 return _RepoVcsSettingsForm
464 465
465 466
466 467 def LabsSettingsForm(localizer):
467 468 _ = localizer
468 469
469 470 class _LabSettingsForm(formencode.Schema):
470 471 allow_extra_fields = True
471 472 filter_extra_fields = False
472 473 return _LabSettingsForm
473 474
474 475
475 476 def ApplicationPermissionsForm(
476 477 localizer, register_choices, password_reset_choices,
477 478 extern_activate_choices):
478 479 _ = localizer
479 480
480 481 class _DefaultPermissionsForm(formencode.Schema):
481 482 allow_extra_fields = True
482 483 filter_extra_fields = True
483 484
484 485 anonymous = v.StringBoolean(if_missing=False)
485 486 default_register = v.OneOf(register_choices)
486 487 default_register_message = v.UnicodeString()
487 488 default_password_reset = v.OneOf(password_reset_choices)
488 489 default_extern_activate = v.OneOf(extern_activate_choices)
489 490 return _DefaultPermissionsForm
490 491
491 492
492 493 def ObjectPermissionsForm(localizer, repo_perms_choices, group_perms_choices,
493 494 user_group_perms_choices):
494 495 _ = localizer
495 496
496 497 class _ObjectPermissionsForm(formencode.Schema):
497 498 allow_extra_fields = True
498 499 filter_extra_fields = True
499 500 overwrite_default_repo = v.StringBoolean(if_missing=False)
500 501 overwrite_default_group = v.StringBoolean(if_missing=False)
501 502 overwrite_default_user_group = v.StringBoolean(if_missing=False)
502 503 default_repo_perm = v.OneOf(repo_perms_choices)
503 504 default_group_perm = v.OneOf(group_perms_choices)
504 505 default_user_group_perm = v.OneOf(user_group_perms_choices)
505 506 return _ObjectPermissionsForm
506 507
507 508
508 509 def UserPermissionsForm(localizer, create_choices, create_on_write_choices,
509 510 repo_group_create_choices, user_group_create_choices,
510 511 fork_choices, inherit_default_permissions_choices):
511 512 _ = localizer
512 513
513 514 class _DefaultPermissionsForm(formencode.Schema):
514 515 allow_extra_fields = True
515 516 filter_extra_fields = True
516 517
517 518 anonymous = v.StringBoolean(if_missing=False)
518 519
519 520 default_repo_create = v.OneOf(create_choices)
520 521 default_repo_create_on_write = v.OneOf(create_on_write_choices)
521 522 default_user_group_create = v.OneOf(user_group_create_choices)
522 523 default_repo_group_create = v.OneOf(repo_group_create_choices)
523 524 default_fork_create = v.OneOf(fork_choices)
524 525 default_inherit_default_permissions = v.OneOf(inherit_default_permissions_choices)
525 526 return _DefaultPermissionsForm
526 527
527 528
528 529 def UserIndividualPermissionsForm(localizer):
529 530 _ = localizer
530 531
531 532 class _DefaultPermissionsForm(formencode.Schema):
532 533 allow_extra_fields = True
533 534 filter_extra_fields = True
534 535
535 536 inherit_default_permissions = v.StringBoolean(if_missing=False)
536 537 return _DefaultPermissionsForm
537 538
538 539
539 540 def DefaultsForm(localizer, edit=False, old_data=None, supported_backends=BACKENDS.keys()):
540 541 _ = localizer
541 542 old_data = old_data or {}
542 543
543 544 class _DefaultsForm(formencode.Schema):
544 545 allow_extra_fields = True
545 546 filter_extra_fields = True
546 547 default_repo_type = v.OneOf(supported_backends)
547 548 default_repo_private = v.StringBoolean(if_missing=False)
548 549 default_repo_enable_statistics = v.StringBoolean(if_missing=False)
549 550 default_repo_enable_downloads = v.StringBoolean(if_missing=False)
550 551 default_repo_enable_locking = v.StringBoolean(if_missing=False)
551 552 return _DefaultsForm
552 553
553 554
554 555 def AuthSettingsForm(localizer):
555 556 _ = localizer
556 557
557 558 class _AuthSettingsForm(formencode.Schema):
558 559 allow_extra_fields = True
559 560 filter_extra_fields = True
560 561 auth_plugins = All(v.ValidAuthPlugins(localizer),
561 562 v.UniqueListFromString(localizer)(not_empty=True))
562 563 return _AuthSettingsForm
563 564
564 565
565 566 def UserExtraEmailForm(localizer):
566 567 _ = localizer
567 568
568 569 class _UserExtraEmailForm(formencode.Schema):
569 570 email = All(v.UniqSystemEmail(localizer), v.Email(not_empty=True))
570 571 return _UserExtraEmailForm
571 572
572 573
573 574 def UserExtraIpForm(localizer):
574 575 _ = localizer
575 576
576 577 class _UserExtraIpForm(formencode.Schema):
577 578 ip = v.ValidIp(localizer)(not_empty=True)
578 579 return _UserExtraIpForm
579 580
580 581
581 582 def PullRequestForm(localizer, repo_id):
582 583 _ = localizer
583 584
584 585 class ReviewerForm(formencode.Schema):
585 586 user_id = v.Int(not_empty=True)
586 587 reasons = All()
587 588 rules = All(v.UniqueList(localizer, convert=int)())
588 589 mandatory = v.StringBoolean()
589 590
590 591 class _PullRequestForm(formencode.Schema):
591 592 allow_extra_fields = True
592 593 filter_extra_fields = True
593 594
594 595 common_ancestor = v.UnicodeString(strip=True, required=True)
595 596 source_repo = v.UnicodeString(strip=True, required=True)
596 597 source_ref = v.UnicodeString(strip=True, required=True)
597 598 target_repo = v.UnicodeString(strip=True, required=True)
598 599 target_ref = v.UnicodeString(strip=True, required=True)
599 600 revisions = All(#v.NotReviewedRevisions(localizer, repo_id)(),
600 601 v.UniqueList(localizer)(not_empty=True))
601 602 review_members = formencode.ForEach(ReviewerForm())
602 603 pullrequest_title = v.UnicodeString(strip=True, required=True, min=3, max=255)
603 604 pullrequest_desc = v.UnicodeString(strip=True, required=False)
604 605
605 606 return _PullRequestForm
606 607
607 608
608 609 def IssueTrackerPatternsForm(localizer):
609 610 _ = localizer
610 611
611 612 class _IssueTrackerPatternsForm(formencode.Schema):
612 613 allow_extra_fields = True
613 614 filter_extra_fields = False
614 615 chained_validators = [v.ValidPattern(localizer)]
615 616 return _IssueTrackerPatternsForm
@@ -1,270 +1,278 b''
1 1 // summary.less
2 2 // For use in RhodeCode applications;
3 3 // Used for headers and file detail summary screens.
4 4
5 5 .summary {
6 6 float: left;
7 7 position: relative;
8 8 width: 100%;
9 9 margin: 0;
10 10 padding: 0;
11 11
12 12 .summary-detail-header {
13 13 float: left;
14 14 display: block;
15 15 width: 100%;
16 16 margin-bottom: @textmargin;
17 17 padding: 0 0 .5em 0;
18 18 border-bottom: @border-thickness solid @border-default-color;
19 19
20 20 .breadcrumbs {
21 21 float: left;
22 22 display: inline;
23 23 margin: 0;
24 24 padding: 0;
25 25 }
26 26 h4 {
27 27 float: left;
28 28 margin: 0 1em 0 0;
29 29 padding: 0;
30 30 line-height: 1.2em;
31 31 font-size: @basefontsize;
32 32 }
33 33
34 34 .action_link {
35 35 float: right;
36 36 }
37 37
38 38 .new-file {
39 39 float: right;
40 40 margin-top: -1.5em;
41 41 }
42 42 }
43 43
44 44 .summary-detail {
45 45 float: left;
46 46 position: relative;
47 47 width: 73%;
48 48 margin: 0 3% @space 0;
49 49 padding: 0;
50 50
51 51 .file_diff_buttons {
52 52 margin-top: @space;
53 53 }
54 54
55 55 // commit message
56 56 .commit {
57 57 white-space: pre-wrap;
58 58 }
59 59
60 #clone_url {
61 width: ~"calc(100% - 103px)";
62 padding: @padding/4;
60 .left-clone {
61 float: left;
62 height: 30px;
63 margin: 0;
64 padding: 0;
65 font-family: @text-semibold;
63 66 }
64 67
65 #clone_url_id {
66 width: ~"calc(100% - 125px)";
67 padding: @padding/4;
68 .right-clone {
69 float: right;
70 width: 83%;
71 }
72
73 .clone_url_input {
74 width: ~"calc(100% - 35px)";
75 padding: 5px;
68 76 }
69 77
70 78 &.directory {
71 79 margin-bottom: 0;
72 80 }
73 81
74 82 .desc {
75 83 white-space: pre-wrap;
76 84 }
77 85 .disabled {
78 86 opacity: .5;
79 87 cursor: inherit;
80 88 }
81 89 .help-block {
82 90 color: inherit;
83 91 margin: 0;
84 92 }
85 93 }
86 94
87 95 .sidebar-right {
88 96 float: left;
89 97 width: 24%;
90 98 margin: 0;
91 99 padding: 0;
92 100
93 101 ul {
94 102 margin-left: 0;
95 103 padding-left: 0;
96 104
97 105 li {
98 106
99 107 &:before {
100 108 content: none;
101 109 width: 0;
102 110 }
103 111 }
104 112 }
105 113 }
106 114
107 115 #clone_by_name, #clone_by_id{
108 116 display: inline-block;
109 117 margin-left: 0px;
110 118 }
111 119
112 120 .codeblock {
113 121 border: none;
114 122 background-color: transparent;
115 123 }
116 124
117 125 .code-body {
118 126 border: @border-thickness solid @border-default-color;
119 127 .border-radius(@border-radius);
120 128 }
121 129 }
122 130
123 131 // this is used outside of just the summary
124 132 .fieldset, // similar to form fieldset
125 133 .summary .sidebar-right-content { // these have to match
126 134 clear: both;
127 135 float: left;
128 136 position: relative;
129 137 display:block;
130 138 width: 100%;
131 139 min-height: 1em;
132 140 margin-bottom: @textmargin;
133 141 padding: 0;
134 142 line-height: 1.2em;
135 143
136 144 &:after { // clearfix
137 145 content: "";
138 146 clear: both;
139 147 width: 100%;
140 148 height: 1em;
141 149 }
142 150 }
143 151
144 152 .summary .sidebar-right-content {
145 153 margin-bottom: @space;
146 154
147 155 .rc-user {
148 156 min-width: 0;
149 157 }
150 158 }
151 159
152 160 .fieldset {
153 161
154 162 .left-label { // similar to form legend
155 163 float: left;
156 164 display: block;
157 165 width: 25%;
158 166 margin: 0;
159 167 padding: 0;
160 168 font-family: @text-semibold;
161 169 }
162 170
163 171 .right-content { // similar to form fields
164 172 float: left;
165 173 display: block;
166 174 width: 75%;
167 175 margin: 0 0 0 -15%;
168 176 padding: 0 0 0 15%;
169 177
170 178 .truncate-wrap,
171 179 .truncate {
172 180 max-width: 100%;
173 181 width: 100%;
174 182 }
175 183
176 184 .commit-long {
177 185 overflow-x: auto;
178 186 }
179 187 }
180 188 .commit.truncate-wrap {
181 189 overflow:hidden;
182 190 text-overflow: ellipsis;
183 191 }
184 192 }
185 193
186 194 // expand commit message
187 195 #message_expand {
188 196 clear: both;
189 197 display: block;
190 198 color: @rcblue;
191 199 cursor: pointer;
192 200 }
193 201
194 202 #trimmed_message_box {
195 203 max-height: floor(2 * @basefontsize * 1.2); // 2 lines * line-height
196 204 overflow: hidden;
197 205 }
198 206
199 207 // show/hide comments button
200 208 .show-inline-comments {
201 209 display: inline;
202 210 cursor: pointer;
203 211
204 212 .comments-show { display: inline; }
205 213 .comments-hide { display: none; }
206 214
207 215 &.comments-visible {
208 216 .comments-show { display: none; }
209 217 .comments-hide { display: inline; }
210 218 }
211 219 }
212 220
213 221 // Quick Start section
214 222 .quick_start {
215 223 float: left;
216 224 display: block;
217 225 position: relative;
218 226 width: 100%;
219 227
220 228 // adds some space to make copy and paste easier
221 229 .left-label,
222 230 .right-content {
223 231 line-height: 1.6em;
224 232 }
225 233 }
226 234
227 235 .submodule {
228 236 .summary-detail {
229 237 width: 100%;
230 238
231 239 .btn-collapse {
232 240 display: none;
233 241 }
234 242 }
235 243 }
236 244
237 245 .codeblock-header {
238 246 float: left;
239 247 display: block;
240 248 width: 100%;
241 249 margin: 0;
242 250 padding: @space 0 @padding 0;
243 251 border-top: @border-thickness solid @border-default-color;
244 252
245 253 .stats {
246 254 float: left;
247 255 width: 50%;
248 256 }
249 257
250 258 .buttons {
251 259 float: right;
252 260 width: 50%;
253 261 text-align: right;
254 262 color: @grey4;
255 263 }
256 264 }
257 265
258 266 #summary-menu-stats {
259 267
260 268 .stats-bullet {
261 269 color: @grey3;
262 270 min-width: 3em;
263 271 }
264 272
265 273 .repo-size {
266 274 margin-bottom: .5em;
267 275 }
268 276
269 277 }
270 278
@@ -1,226 +1,230 b''
1 1 ${h.secure_form(h.route_path('admin_settings_visual_update'), request=request)}
2 2
3 3 <div class="panel panel-default">
4 4 <div class="panel-heading" id="general">
5 5 <h3 class="panel-title">${_('General')}</h3>
6 6 </div>
7 7 <div class="panel-body">
8 8 <div class="checkbox">
9 9 ${h.checkbox('rhodecode_repository_fields','True')}
10 10 <label for="rhodecode_repository_fields">${_('Use repository extra fields')}</label>
11 11 </div>
12 12 <span class="help-block">${_('Allows storing additional customized fields per repository.')}</span>
13 13
14 14 <div></div>
15 15 <div class="checkbox">
16 16 ${h.checkbox('rhodecode_show_version','True')}
17 17 <label for="rhodecode_show_version">${_('Show RhodeCode version')}</label>
18 18 </div>
19 19 <span class="help-block">${_('Shows or hides a version number of RhodeCode displayed in the footer.')}</span>
20 20 </div>
21 21 </div>
22 22
23 23
24 24 <div class="panel panel-default">
25 25 <div class="panel-heading" id="gravatars">
26 26 <h3 class="panel-title">${_('Gravatars')}</h3>
27 27 </div>
28 28 <div class="panel-body">
29 29 <div class="checkbox">
30 30 ${h.checkbox('rhodecode_use_gravatar','True')}
31 31 <label for="rhodecode_use_gravatar">${_('Use Gravatars based avatars')}</label>
32 32 </div>
33 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 35 <div class="label">
36 36 <label for="rhodecode_gravatar_url">${_('Gravatar URL')}</label>
37 37 </div>
38 38 <div class="input">
39 39 <div class="field">
40 40 ${h.text('rhodecode_gravatar_url', size='100%')}
41 41 </div>
42 42
43 43 <div class="field">
44 44 <span class="help-block">${_('''Gravatar url allows you to use other avatar server application.
45 45 Following variables of the URL will be replaced accordingly.
46 46 {scheme} 'http' or 'https' sent from running RhodeCode server,
47 47 {email} user email,
48 48 {md5email} md5 hash of the user email (like at gravatar.com),
49 49 {size} size of the image that is expected from the server application,
50 50 {netloc} network location/server host of running RhodeCode server''')}</span>
51 51 </div>
52 52 </div>
53 53 </div>
54 54 </div>
55 55
56 56
57 57 <div class="panel panel-default">
58 58 <div class="panel-heading" id="meta-tagging">
59 59 <h3 class="panel-title">${_('Meta-Tagging')}</h3>
60 60 </div>
61 61 <div class="panel-body">
62 62 <div class="checkbox">
63 63 ${h.checkbox('rhodecode_stylify_metatags','True')}
64 64 <label for="rhodecode_stylify_metatags">${_('Stylify recognised meta tags')}</label>
65 65 </div>
66 66 <span class="help-block">${_('Parses meta tags from repository or repository group description fields and turns them into colored tags.')}</span>
67 67 <div>
68 68 <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
69 69 ${dt.metatags_help()}
70 70 </div>
71 71 </div>
72 72 </div>
73 73
74 74
75 75 <div class="panel panel-default">
76 76 <div class="panel-heading">
77 77 <h3 class="panel-title">${_('Dashboard Items')}</h3>
78 78 </div>
79 79 <div class="panel-body">
80 80 <div class="label">
81 81 <label for="rhodecode_dashboard_items">${_('Main page dashboard items')}</label>
82 82 </div>
83 83 <div class="field input">
84 84 ${h.text('rhodecode_dashboard_items',size=5)}
85 85 </div>
86 86 <div class="field">
87 87 <span class="help-block">${_('Number of items displayed in the main page dashboard before pagination is shown.')}</span>
88 88 </div>
89 89
90 90 <div class="label">
91 91 <label for="rhodecode_admin_grid_items">${_('Admin pages items')}</label>
92 92 </div>
93 93 <div class="field input">
94 94 ${h.text('rhodecode_admin_grid_items',size=5)}
95 95 </div>
96 96 <div class="field">
97 97 <span class="help-block">${_('Number of items displayed in the admin pages grids before pagination is shown.')}</span>
98 98 </div>
99 99 </div>
100 100 </div>
101 101
102 102
103 103
104 104 <div class="panel panel-default">
105 105 <div class="panel-heading" id="commit-id">
106 106 <h3 class="panel-title">${_('Commit ID Style')}</h3>
107 107 </div>
108 108 <div class="panel-body">
109 109 <div class="label">
110 110 <label for="rhodecode_show_sha_length">${_('Commit sha length')}</label>
111 111 </div>
112 112 <div class="input">
113 113 <div class="field">
114 114 ${h.text('rhodecode_show_sha_length',size=5)}
115 115 </div>
116 116 <div class="field">
117 117 <span class="help-block">${_('''Number of chars to show in commit sha displayed in web interface.
118 118 By default it's shown as r123:9043a6a4c226 this value defines the
119 119 length of the sha after the `r123:` part.''')}</span>
120 120 </div>
121 121 </div>
122 122
123 123 <div class="checkbox">
124 124 ${h.checkbox('rhodecode_show_revision_number','True')}
125 125 <label for="rhodecode_show_revision_number">${_('Show commit ID numeric reference')} / ${_('Commit show revision number')}</label>
126 126 </div>
127 127 <span class="help-block">${_('''Show revision number in commit sha displayed in web interface.
128 128 By default it's shown as r123:9043a6a4c226 this value defines the
129 129 if the `r123:` part is shown.''')}</span>
130 130 </div>
131 131 </div>
132 132
133 133
134 134 <div class="panel panel-default">
135 135 <div class="panel-heading" id="icons">
136 136 <h3 class="panel-title">${_('Icons')}</h3>
137 137 </div>
138 138 <div class="panel-body">
139 139 <div class="checkbox">
140 140 ${h.checkbox('rhodecode_show_public_icon','True')}
141 141 <label for="rhodecode_show_public_icon">${_('Show public repo icon on repositories')}</label>
142 142 </div>
143 143 <div></div>
144 144
145 145 <div class="checkbox">
146 146 ${h.checkbox('rhodecode_show_private_icon','True')}
147 147 <label for="rhodecode_show_private_icon">${_('Show private repo icon on repositories')}</label>
148 148 </div>
149 149 <span class="help-block">${_('Show public/private icons next to repositories names.')}</span>
150 150 </div>
151 151 </div>
152 152
153 153
154 154 <div class="panel panel-default">
155 155 <div class="panel-heading">
156 156 <h3 class="panel-title">${_('Markup Renderer')}</h3>
157 157 </div>
158 158 <div class="panel-body">
159 159 <div class="field select">
160 160 ${h.select('rhodecode_markup_renderer', '', ['rst', 'markdown'])}
161 161 </div>
162 162 <div class="field">
163 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 164 </div>
165 165 </div>
166 166 </div>
167 167
168 168 <div class="panel panel-default">
169 169 <div class="panel-heading">
170 <h3 class="panel-title">${_('Clone URL')}</h3>
170 <h3 class="panel-title">${_('Clone URL templates')}</h3>
171 171 </div>
172 172 <div class="panel-body">
173 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 175 </div>
176
176 <div class="field">
177 ${h.text('rhodecode_clone_uri_ssh_tmpl', size=60)} SSH
178 </div>
177 179 <div class="field">
178 180 <span class="help-block">
179 181 ${_('''Schema of clone url construction eg. '{scheme}://{user}@{netloc}/{repo}', available vars:
180 182 {scheme} 'http' or 'https' sent from running RhodeCode server,
181 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 186 {netloc} network location/server host of running RhodeCode server,
183 187 {repo} full repository name,
184 188 {repoid} ID of repository, can be used to contruct clone-by-id''')}
185 189 </span>
186 190 </div>
187 191 </div>
188 192 </div>
189 193
190 194 <div class="panel panel-default">
191 195 <div class="panel-heading">
192 196 <h3 class="panel-title">${_('Custom Support Link')}</h3>
193 197 </div>
194 198 <div class="panel-body">
195 199 <div class="field">
196 200 ${h.text('rhodecode_support_url', size=60)}
197 201 </div>
198 202 <div class="field">
199 203 <span class="help-block">
200 204 ${_('''Custom url for the support link located at the bottom.
201 205 The default is set to %(default_url)s. In case there's a need
202 206 to change the support link to internal issue tracker, it should be done here.
203 207 ''') % {'default_url': h.route_url('rhodecode_support')}}
204 208 </span>
205 209 </div>
206 210 </div>
207 211 </div>
208 212
209 213 <div class="buttons">
210 214 ${h.submit('save',_('Save settings'),class_="btn")}
211 215 ${h.reset('reset',_('Reset'),class_="btn")}
212 216 </div>
213 217
214 218
215 219 ${h.end_form()}
216 220
217 221 <script>
218 222 $(document).ready(function() {
219 223 $('#rhodecode_markup_renderer').select2({
220 224 containerCssClass: 'drop-menu',
221 225 dropdownCssClass: 'drop-menu-dropdown',
222 226 dropdownAutoWidth: true,
223 227 minimumResultsForSearch: -1
224 228 });
225 229 });
226 230 </script>
@@ -1,210 +1,214 b''
1 1 <%def name="refs_counters(branches, closed_branches, tags, bookmarks)">
2 2 <span class="branchtag tag">
3 3 <a href="${h.route_path('branches_home',repo_name=c.repo_name)}" class="childs">
4 4 <i class="icon-branch"></i>${_ungettext(
5 5 '%(num)s Branch','%(num)s Branches', len(branches)) % {'num': len(branches)}}</a>
6 6 </span>
7 7
8 8 %if closed_branches:
9 9 <span class="branchtag tag">
10 10 <a href="${h.route_path('branches_home',repo_name=c.repo_name)}" class="childs">
11 11 <i class="icon-branch"></i>${_ungettext(
12 12 '%(num)s Closed Branch', '%(num)s Closed Branches', len(closed_branches)) % {'num': len(closed_branches)}}</a>
13 13 </span>
14 14 %endif
15 15
16 16 <span class="tagtag tag">
17 17 <a href="${h.route_path('tags_home',repo_name=c.repo_name)}" class="childs">
18 18 <i class="icon-tag"></i>${_ungettext(
19 19 '%(num)s Tag', '%(num)s Tags', len(tags)) % {'num': len(tags)}}</a>
20 20 </span>
21 21
22 22 %if bookmarks:
23 23 <span class="booktag tag">
24 24 <a href="${h.route_path('bookmarks_home',repo_name=c.repo_name)}" class="childs">
25 25 <i class="icon-bookmark"></i>${_ungettext(
26 26 '%(num)s Bookmark', '%(num)s Bookmarks', len(bookmarks)) % {'num': len(bookmarks)}}</a>
27 27 </span>
28 28 %endif
29 29 </%def>
30 30
31 31 <%def name="summary_detail(breadcrumbs_links, show_downloads=True)">
32 32 <% summary = lambda n:{False:'summary-short'}.get(n) %>
33 33
34 34 <div id="summary-menu-stats" class="summary-detail">
35 35 <div class="summary-detail-header">
36 36 <div class="breadcrumbs files_location">
37 37 <h4>
38 38 ${breadcrumbs_links}
39 39 </h4>
40 40 </div>
41 41 <div id="summary_details_expand" class="btn-collapse" data-toggle="summary-details">
42 42 ${_('Show More')}
43 43 </div>
44 44 </div>
45 45
46 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;"/>
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>
57
58 <a id="clone_by_name" class="clone" style="display: none;">${_('Show by Name')}</a>
59 <a id="clone_by_id" class="clone">${_('Show by ID')}</a>
60
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>
48 <div class="left-clone">
49 <select id="clone_option" name="clone_option">
50 <option value="http" selected="selected">HTTP</option>
51 <option value="http_id">HTTP UID</option>
52 <option value="ssh">SSH</option>
53 </select>
62 54 </div>
63 %else:
64 <div class="left-label">
65 ${_('Clone url')}:
66 </div>
67 <div class="right-content">
68 <input type="text" class="input-monospace" id="clone_url" readonly="readonly" value="${c.clone_repo_url}"/>
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>
55 <div class="right-clone">
56 <%
57 maybe_disabled = ''
58 if h.is_svn_without_proxy(c.rhodecode_db_repo):
59 maybe_disabled = 'disabled'
60 %>
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;"/>
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>
67 <span style="display: none;" id="clone_option_http_id">
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>
75 <a id="clone_by_id" class="clone">${_('Show by ID')}</a>
72 <span style="display: none;" id="clone_option_ssh">
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 81 </div>
77 %endif
78 82 </div>
79 83
80 84 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
81 85 <div class="left-label">
82 86 ${_('Description')}:
83 87 </div>
84 88 <div class="right-content">
85 89 <div class="input ${summary(c.show_stats)}">
86 90 <%namespace name="dt" file="/data_table/_dt_elements.mako"/>
87 91 ${dt.repo_desc(c.rhodecode_db_repo.description_safe, c.visual.stylify_metatags)}
88 92 </div>
89 93 </div>
90 94 </div>
91 95
92 96 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
93 97 <div class="left-label">
94 98 ${_('Information')}:
95 99 </div>
96 100 <div class="right-content">
97 101
98 102 <div class="repo-size">
99 103 <% commit_rev = c.rhodecode_db_repo.changeset_cache.get('revision') %>
100 104
101 105 ## commits
102 106 % if commit_rev == -1:
103 107 ${_ungettext('%(num)s Commit', '%(num)s Commits', 0) % {'num': 0}},
104 108 % else:
105 109 <a href="${h.route_path('repo_changelog', repo_name=c.repo_name)}">
106 110 ${_ungettext('%(num)s Commit', '%(num)s Commits', commit_rev) % {'num': commit_rev}}</a>,
107 111 % endif
108 112
109 113 ## forks
110 114 <a title="${_('Number of Repository Forks')}" href="${h.route_path('repo_forks_show_all', repo_name=c.repo_name)}">
111 115 ${c.repository_forks} ${_ungettext('Fork', 'Forks', c.repository_forks)}</a>,
112 116
113 117 ## repo size
114 118 % if commit_rev == -1:
115 119 <span class="stats-bullet">0 B</span>
116 120 % else:
117 121 <span class="stats-bullet" id="repo_size_container">
118 122 ${_('Calculating Repository Size...')}
119 123 </span>
120 124 % endif
121 125 </div>
122 126
123 127 <div class="commit-info">
124 128 <div class="tags">
125 129 % if c.rhodecode_repo:
126 130 ${refs_counters(
127 131 c.rhodecode_repo.branches,
128 132 c.rhodecode_repo.branches_closed,
129 133 c.rhodecode_repo.tags,
130 134 c.rhodecode_repo.bookmarks)}
131 135 % else:
132 136 ## missing requirements can make c.rhodecode_repo None
133 137 ${refs_counters([], [], [], [])}
134 138 % endif
135 139 </div>
136 140 </div>
137 141
138 142 </div>
139 143 </div>
140 144
141 145 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
142 146 <div class="left-label">
143 147 ${_('Statistics')}:
144 148 </div>
145 149 <div class="right-content">
146 150 <div class="input ${summary(c.show_stats)} statistics">
147 151 % if c.show_stats:
148 152 <div id="lang_stats" class="enabled">
149 153 ${_('Calculating Code Statistics...')}
150 154 </div>
151 155 % else:
152 156 <span class="disabled">
153 157 ${_('Statistics are disabled for this repository')}
154 158 </span>
155 159 % if h.HasPermissionAll('hg.admin')('enable stats on from summary'):
156 160 , ${h.link_to(_('enable statistics'),h.route_path('edit_repo',repo_name=c.repo_name, _anchor='repo_enable_statistics'))}
157 161 % endif
158 162 % endif
159 163 </div>
160 164
161 165 </div>
162 166 </div>
163 167
164 168 % if show_downloads:
165 169 <div class="fieldset collapsable-content" data-toggle="summary-details" style="display: none;">
166 170 <div class="left-label">
167 171 ${_('Downloads')}:
168 172 </div>
169 173 <div class="right-content">
170 174 <div class="input ${summary(c.show_stats)} downloads">
171 175 % if c.rhodecode_repo and len(c.rhodecode_repo.revisions) == 0:
172 176 <span class="disabled">
173 177 ${_('There are no downloads yet')}
174 178 </span>
175 179 % elif not c.enable_downloads:
176 180 <span class="disabled">
177 181 ${_('Downloads are disabled for this repository')}
178 182 </span>
179 183 % if h.HasPermissionAll('hg.admin')('enable downloads on from summary'):
180 184 , ${h.link_to(_('enable downloads'),h.route_path('edit_repo',repo_name=c.repo_name, _anchor='repo_enable_downloads'))}
181 185 % endif
182 186 % else:
183 187 <span class="enabled">
184 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 189 <i class="icon-archive"></i> tip.zip
186 190 ## replaced by some JS on select
187 191 </a>
188 192 </span>
189 193 ${h.hidden('download_options')}
190 194 % endif
191 195 </div>
192 196 </div>
193 197 </div>
194 198 % endif
195 199
196 200 </div><!--end summary-detail-->
197 201 </%def>
198 202
199 203 <%def name="summary_stats(gravatar_function)">
200 204 <div class="sidebar-right">
201 205 <div class="summary-detail-header">
202 206 <h4 class="item">
203 207 ${_('Owner')}
204 208 </h4>
205 209 </div>
206 210 <div class="sidebar-right-content">
207 211 ${gravatar_function(c.rhodecode_db_repo.user.email, 16)}
208 212 </div>
209 213 </div><!--end sidebar-right-->
210 214 </%def>
@@ -1,137 +1,119 b''
1 1 <%inherit file="/summary/summary_base.mako"/>
2 2
3 3 <%namespace name="components" file="/summary/components.mako"/>
4 4
5 5
6 6 <%def name="menu_bar_subnav()">
7 7 ${self.repo_menu(active='summary')}
8 8 </%def>
9 9
10 10 <%def name="main()">
11 11
12 12 <div class="title">
13 13 ${self.repo_page_title(c.rhodecode_db_repo)}
14 14 <ul class="links icon-only-links block-right">
15 15 <li>
16 16 %if c.rhodecode_user.username != h.DEFAULT_USER:
17 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 18 %else:
19 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 20 %endif
21 21 </li>
22 22 </ul>
23 23 </div>
24 24
25 25 <div id="repo-summary" class="summary">
26 26 ${components.summary_detail(breadcrumbs_links=self.breadcrumbs_links(), show_downloads=True)}
27 27 ${components.summary_stats(gravatar_function=self.gravatar_with_user)}
28 28 </div><!--end repo-summary-->
29 29
30 30
31 31 <div class="box" >
32 32 %if not c.repo_commits:
33 33 <div class="title">
34 34 <h3>${_('Quick start')}</h3>
35 35 </div>
36 36 %endif
37 37 <div class="table">
38 38 <div id="shortlog_data">
39 39 <%include file='summary_commits.mako'/>
40 40 </div>
41 41 </div>
42 42 </div>
43 43
44 44 %if c.readme_data:
45 45 <div id="readme" class="anchor">
46 46 <div class="box" >
47 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 48 <h3 class="breadcrumbs">
49 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 50 </h3>
51 51 </div>
52 52 <div class="readme codeblock">
53 53 <div class="readme_box">
54 54 ${c.readme_data|n}
55 55 </div>
56 56 </div>
57 57 </div>
58 58 </div>
59 59 %endif
60 60
61 61 <script type="text/javascript">
62 62 $(document).ready(function(){
63 $('#clone_by_name').on('click',function(e){
64 // show url by name and hide name button
65 $('#clone_url').show();
66 $('#clone_by_name').hide();
67
68 // hide url by id and show name button
69 $('#clone_by_id').show();
70 $('#clone_url_id').hide();
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();
63 $('#clone_option').on('change', function(e) {
64 var selected = $(this).val();
65 $.each(['http', 'http_id', 'ssh'], function (idx, val) {
66 if(val === selected){
67 $('#clone_option_' + val).show();
68 } else {
69 $('#clone_option_' + val).hide();
70 }
71 });
90 72 });
91 73
92 74 var initialCommitData = {
93 75 id: null,
94 76 text: 'tip',
95 77 type: 'tag',
96 78 raw_id: null,
97 79 files_url: null
98 80 };
99 81
100 82 select2RefSwitcher('#download_options', initialCommitData);
101 83
102 84 // on change of download options
103 85 $('#download_options').on('change', function(e) {
104 86 // format of Object {text: "v0.0.3", type: "tag", id: "rev"}
105 87 var ext = '.zip';
106 88 var selected_cs = e.added;
107 89 var fname = e.added.raw_id + ext;
108 90 var href = pyroutes.url('repo_archivefile', {'repo_name': templateContext.repo_name, 'fname':fname});
109 91 // set new label
110 92 $('#archive_link').html('<i class="icon-archive"></i> {0}{1}'.format(escapeHtml(e.added.text), ext));
111 93
112 94 // set new url to button,
113 95 $('#archive_link').attr('href', href)
114 96 });
115 97
116 98
117 99 // load details on summary page expand
118 100 $('#summary_details_expand').on('click', function() {
119 101
120 102 var callback = function (data) {
121 103 % if c.show_stats:
122 104 showRepoStats('lang_stats', data);
123 105 % endif
124 106 };
125 107
126 108 showRepoSize(
127 109 'repo_size_container',
128 110 templateContext.repo_name,
129 111 templateContext.repo_landing_commit,
130 112 callback);
131 113
132 114 })
133 115
134 116 })
135 117 </script>
136 118
137 119 </%def>
General Comments 0
You need to be logged in to leave comments. Login now