##// END OF EJS Templates
goto-switcher: optimized performance and query capabilities....
marcink -
r2038:2bdf9d4d default
parent child Browse files
Show More
@@ -1,305 +1,321 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2016-2017 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 re
22 22 import logging
23 23
24 24 from pyramid.view import view_config
25 25
26 26 from rhodecode.apps._base import BaseAppView
27 27 from rhodecode.lib import helpers as h
28 28 from rhodecode.lib.auth import LoginRequired, NotAnonymous, \
29 29 HasRepoGroupPermissionAnyDecorator
30 30 from rhodecode.lib.index import searcher_from_config
31 31 from rhodecode.lib.utils2 import safe_unicode, str2bool
32 32 from rhodecode.lib.ext_json import json
33 from rhodecode.model.db import func, Repository, RepoGroup
33 from rhodecode.model.db import (
34 func, or_, in_filter_generator, Repository, RepoGroup)
34 35 from rhodecode.model.repo import RepoModel
35 36 from rhodecode.model.repo_group import RepoGroupModel
36 from rhodecode.model.scm import ScmModel, RepoGroupList, RepoList
37 from rhodecode.model.scm import RepoGroupList, RepoList
37 38 from rhodecode.model.user import UserModel
38 39 from rhodecode.model.user_group import UserGroupModel
39 40
40 41 log = logging.getLogger(__name__)
41 42
42 43
43 44 class HomeView(BaseAppView):
44 45
45 46 def load_default_context(self):
46 47 c = self._get_local_tmpl_context()
47 48 c.user = c.auth_user.get_instance()
48 49 self._register_global_c(c)
49 50 return c
50 51
51 52 @LoginRequired()
52 53 @view_config(
53 54 route_name='user_autocomplete_data', request_method='GET',
54 55 renderer='json_ext', xhr=True)
55 56 def user_autocomplete_data(self):
56 57 query = self.request.GET.get('query')
57 58 active = str2bool(self.request.GET.get('active') or True)
58 59 include_groups = str2bool(self.request.GET.get('user_groups'))
59 60 expand_groups = str2bool(self.request.GET.get('user_groups_expand'))
60 61 skip_default_user = str2bool(self.request.GET.get('skip_default_user'))
61 62
62 63 log.debug('generating user list, query:%s, active:%s, with_groups:%s',
63 64 query, active, include_groups)
64 65
65 66 _users = UserModel().get_users(
66 67 name_contains=query, only_active=active)
67 68
68 69 def maybe_skip_default_user(usr):
69 70 if skip_default_user and usr['username'] == UserModel.cls.DEFAULT_USER:
70 71 return False
71 72 return True
72 73 _users = filter(maybe_skip_default_user, _users)
73 74
74 75 if include_groups:
75 76 # extend with user groups
76 77 _user_groups = UserGroupModel().get_user_groups(
77 78 name_contains=query, only_active=active,
78 79 expand_groups=expand_groups)
79 80 _users = _users + _user_groups
80 81
81 82 return {'suggestions': _users}
82 83
83 84 @LoginRequired()
84 85 @NotAnonymous()
85 86 @view_config(
86 87 route_name='user_group_autocomplete_data', request_method='GET',
87 88 renderer='json_ext', xhr=True)
88 89 def user_group_autocomplete_data(self):
89 90 query = self.request.GET.get('query')
90 91 active = str2bool(self.request.GET.get('active') or True)
91 92 expand_groups = str2bool(self.request.GET.get('user_groups_expand'))
92 93
93 94 log.debug('generating user group list, query:%s, active:%s',
94 95 query, active)
95 96
96 97 _user_groups = UserGroupModel().get_user_groups(
97 98 name_contains=query, only_active=active,
98 99 expand_groups=expand_groups)
99 100 _user_groups = _user_groups
100 101
101 102 return {'suggestions': _user_groups}
102 103
103 104 def _get_repo_list(self, name_contains=None, repo_type=None, limit=20):
105 allowed_ids = self._rhodecode_user.repo_acl_ids(
106 ['repository.read', 'repository.write', 'repository.admin'],
107 cache=False, name_filter=name_contains)
108
104 109 query = Repository.query()\
105 110 .order_by(func.length(Repository.repo_name))\
106 .order_by(Repository.repo_name)
111 .order_by(Repository.repo_name)\
112 .filter(or_(
113 # generate multiple IN to fix limitation problems
114 *in_filter_generator(Repository.repo_id, allowed_ids)
115 ))
107 116
108 117 if repo_type:
109 118 query = query.filter(Repository.repo_type == repo_type)
110 119
111 120 if name_contains:
112 121 ilike_expression = u'%{}%'.format(safe_unicode(name_contains))
113 122 query = query.filter(
114 123 Repository.repo_name.ilike(ilike_expression))
115 124 query = query.limit(limit)
116 125
117 all_repos = query.all()
118 # permission checks are inside this function
119 repo_iter = ScmModel().get_repos(all_repos)
126 acl_repo_iter = query
127
120 128 return [
121 129 {
122 'id': obj['name'],
123 'text': obj['name'],
130 'id': obj.repo_name,
131 'text': obj.repo_name,
124 132 'type': 'repo',
125 'obj': obj['dbrepo'],
126 'url': h.route_path('repo_summary', repo_name=obj['name'])
133 'obj': {'repo_type': obj.repo_type, 'private': obj.private},
134 'url': h.route_path('repo_summary', repo_name=obj.repo_name)
127 135 }
128 for obj in repo_iter]
136 for obj in acl_repo_iter]
129 137
130 138 def _get_repo_group_list(self, name_contains=None, limit=20):
139 allowed_ids = self._rhodecode_user.repo_group_acl_ids(
140 ['group.read', 'group.write', 'group.admin'],
141 cache=False, name_filter=name_contains)
142
131 143 query = RepoGroup.query()\
132 144 .order_by(func.length(RepoGroup.group_name))\
133 .order_by(RepoGroup.group_name)
145 .order_by(RepoGroup.group_name) \
146 .filter(or_(
147 # generate multiple IN to fix limitation problems
148 *in_filter_generator(RepoGroup.group_id, allowed_ids)
149 ))
134 150
135 151 if name_contains:
136 152 ilike_expression = u'%{}%'.format(safe_unicode(name_contains))
137 153 query = query.filter(
138 154 RepoGroup.group_name.ilike(ilike_expression))
139 155 query = query.limit(limit)
140 156
141 all_groups = query.all()
142 repo_groups_iter = ScmModel().get_repo_groups(all_groups)
157 acl_repo_iter = query
158
143 159 return [
144 160 {
145 161 'id': obj.group_name,
146 162 'text': obj.group_name,
147 163 'type': 'group',
148 164 'obj': {},
149 165 'url': h.route_path(
150 166 'repo_group_home', repo_group_name=obj.group_name)
151 167 }
152 for obj in repo_groups_iter]
168 for obj in acl_repo_iter]
153 169
154 170 def _get_hash_commit_list(self, auth_user, query=None):
155 171 if not query or len(query) < 3:
156 172 return []
157 173
158 174 commit_hashes = re.compile('(?:commit:)([0-9a-f]{2,40})').findall(query)
159 175
160 176 if len(commit_hashes) != 1:
161 177 return []
162 178
163 179 commit_hash_prefix = commit_hashes[0]
164 180
165 181 searcher = searcher_from_config(self.request.registry.settings)
166 182 result = searcher.search(
167 183 'commit_id:%s*' % commit_hash_prefix, 'commit', auth_user,
168 184 raise_on_exc=False)
169 185
170 186 return [
171 187 {
172 188 'id': entry['commit_id'],
173 189 'text': entry['commit_id'],
174 190 'type': 'commit',
175 191 'obj': {'repo': entry['repository']},
176 192 'url': h.route_path(
177 193 'repo_commit',
178 194 repo_name=entry['repository'], commit_id=entry['commit_id'])
179 195 }
180 196 for entry in result['results']]
181 197
182 198 @LoginRequired()
183 199 @view_config(
184 200 route_name='repo_list_data', request_method='GET',
185 201 renderer='json_ext', xhr=True)
186 202 def repo_list_data(self):
187 203 _ = self.request.translate
188 204
189 205 query = self.request.GET.get('query')
190 206 repo_type = self.request.GET.get('repo_type')
191 207 log.debug('generating repo list, query:%s, repo_type:%s',
192 208 query, repo_type)
193 209
194 210 res = []
195 211 repos = self._get_repo_list(query, repo_type=repo_type)
196 212 if repos:
197 213 res.append({
198 214 'text': _('Repositories'),
199 215 'children': repos
200 216 })
201 217
202 218 data = {
203 219 'more': False,
204 220 'results': res
205 221 }
206 222 return data
207 223
208 224 @LoginRequired()
209 225 @view_config(
210 226 route_name='goto_switcher_data', request_method='GET',
211 227 renderer='json_ext', xhr=True)
212 228 def goto_switcher_data(self):
213 229 c = self.load_default_context()
214 230
215 231 _ = self.request.translate
216 232
217 233 query = self.request.GET.get('query')
218 234 log.debug('generating goto switcher list, query %s', query)
219 235
220 236 res = []
221 237 repo_groups = self._get_repo_group_list(query)
222 238 if repo_groups:
223 239 res.append({
224 240 'text': _('Groups'),
225 241 'children': repo_groups
226 242 })
227 243
228 244 repos = self._get_repo_list(query)
229 245 if repos:
230 246 res.append({
231 247 'text': _('Repositories'),
232 248 'children': repos
233 249 })
234 250
235 251 commits = self._get_hash_commit_list(c.auth_user, query)
236 252 if commits:
237 253 unique_repos = {}
238 254 for commit in commits:
239 255 unique_repos.setdefault(commit['obj']['repo'], []
240 256 ).append(commit)
241 257
242 258 for repo in unique_repos:
243 259 res.append({
244 260 'text': _('Commits in %(repo)s') % {'repo': repo},
245 261 'children': unique_repos[repo]
246 262 })
247 263
248 264 data = {
249 265 'more': False,
250 266 'results': res
251 267 }
252 268 return data
253 269
254 270 def _get_groups_and_repos(self, repo_group_id=None):
255 271 # repo groups groups
256 272 repo_group_list = RepoGroup.get_all_repo_groups(group_id=repo_group_id)
257 273 _perms = ['group.read', 'group.write', 'group.admin']
258 274 repo_group_list_acl = RepoGroupList(repo_group_list, perm_set=_perms)
259 275 repo_group_data = RepoGroupModel().get_repo_groups_as_dict(
260 276 repo_group_list=repo_group_list_acl, admin=False)
261 277
262 278 # repositories
263 279 repo_list = Repository.get_all_repos(group_id=repo_group_id)
264 280 _perms = ['repository.read', 'repository.write', 'repository.admin']
265 281 repo_list_acl = RepoList(repo_list, perm_set=_perms)
266 282 repo_data = RepoModel().get_repos_as_dict(
267 283 repo_list=repo_list_acl, admin=False)
268 284
269 285 return repo_data, repo_group_data
270 286
271 287 @LoginRequired()
272 288 @view_config(
273 289 route_name='home', request_method='GET',
274 290 renderer='rhodecode:templates/index.mako')
275 291 def main_page(self):
276 292 c = self.load_default_context()
277 293 c.repo_group = None
278 294
279 295 repo_data, repo_group_data = self._get_groups_and_repos()
280 296 # json used to render the grids
281 297 c.repos_data = json.dumps(repo_data)
282 298 c.repo_groups_data = json.dumps(repo_group_data)
283 299
284 300 return self._get_template_context(c)
285 301
286 302 @LoginRequired()
287 303 @HasRepoGroupPermissionAnyDecorator(
288 304 'group.read', 'group.write', 'group.admin')
289 305 @view_config(
290 306 route_name='repo_group_home', request_method='GET',
291 307 renderer='rhodecode:templates/index_repo_group.mako')
292 308 @view_config(
293 309 route_name='repo_group_home_slash', request_method='GET',
294 310 renderer='rhodecode:templates/index_repo_group.mako')
295 311 def repo_group_main_page(self):
296 312 c = self.load_default_context()
297 313 c.repo_group = self.request.db_repo_group
298 314 repo_data, repo_group_data = self._get_groups_and_repos(
299 315 c.repo_group.group_id)
300 316
301 317 # json used to render the grids
302 318 c.repos_data = json.dumps(repo_data)
303 319 c.repo_groups_data = json.dumps(repo_group_data)
304 320
305 321 return self._get_template_context(c)
@@ -1,4172 +1,4190 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 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
38 38 from sqlalchemy import *
39 39 from sqlalchemy.ext.declarative import declared_attr
40 40 from sqlalchemy.ext.hybrid import hybrid_property
41 41 from sqlalchemy.orm import (
42 42 relationship, joinedload, class_mapper, validates, aliased)
43 43 from sqlalchemy.sql.expression import true
44 44 from sqlalchemy.sql.functions import coalesce, count # noqa
45 45 from beaker.cache import cache_region
46 46 from zope.cachedescriptors.property import Lazy as LazyProperty
47 47
48 48 from pyramid.threadlocal import get_current_request
49 49
50 50 from rhodecode.translation import _
51 51 from rhodecode.lib.vcs import get_vcs_instance
52 52 from rhodecode.lib.vcs.backends.base import EmptyCommit, Reference
53 53 from rhodecode.lib.utils2 import (
54 54 str2bool, safe_str, get_commit_safe, safe_unicode, md5_safe,
55 55 time_to_datetime, aslist, Optional, safe_int, get_clone_url, AttributeDict,
56 56 glob2re, StrictAttributeDict, cleaned_uri)
57 57 from rhodecode.lib.jsonalchemy import MutationObj, MutationList, JsonType
58 58 from rhodecode.lib.ext_json import json
59 59 from rhodecode.lib.caching_query import FromCache
60 60 from rhodecode.lib.encrypt import AESCipher
61 61
62 62 from rhodecode.model.meta import Base, Session
63 63
64 64 URL_SEP = '/'
65 65 log = logging.getLogger(__name__)
66 66
67 67 # =============================================================================
68 68 # BASE CLASSES
69 69 # =============================================================================
70 70
71 71 # this is propagated from .ini file rhodecode.encrypted_values.secret or
72 72 # beaker.session.secret if first is not set.
73 73 # and initialized at environment.py
74 74 ENCRYPTION_KEY = None
75 75
76 76 # used to sort permissions by types, '#' used here is not allowed to be in
77 77 # usernames, and it's very early in sorted string.printable table.
78 78 PERMISSION_TYPE_SORT = {
79 79 'admin': '####',
80 80 'write': '###',
81 81 'read': '##',
82 82 'none': '#',
83 83 }
84 84
85 85
86 86 def display_sort(obj):
87 87 """
88 88 Sort function used to sort permissions in .permissions() function of
89 89 Repository, RepoGroup, UserGroup. Also it put the default user in front
90 90 of all other resources
91 91 """
92 92
93 93 if obj.username == User.DEFAULT_USER:
94 94 return '#####'
95 95 prefix = PERMISSION_TYPE_SORT.get(obj.permission.split('.')[-1], '')
96 96 return prefix + obj.username
97 97
98 98
99 99 def _hash_key(k):
100 100 return md5_safe(k)
101 101
102 102
103 def in_filter_generator(qry, items, limit=500):
104 """
105 Splits IN() into multiple with OR
106 e.g.::
107 cnt = Repository.query().filter(
108 or_(
109 *in_filter_generator(Repository.repo_id, range(100000))
110 )).count()
111 """
112 parts = []
113 for chunk in xrange(0, len(items), limit):
114 parts.append(
115 qry.in_(items[chunk: chunk + limit])
116 )
117
118 return parts
119
120
103 121 class EncryptedTextValue(TypeDecorator):
104 122 """
105 123 Special column for encrypted long text data, use like::
106 124
107 125 value = Column("encrypted_value", EncryptedValue(), nullable=False)
108 126
109 127 This column is intelligent so if value is in unencrypted form it return
110 128 unencrypted form, but on save it always encrypts
111 129 """
112 130 impl = Text
113 131
114 132 def process_bind_param(self, value, dialect):
115 133 if not value:
116 134 return value
117 135 if value.startswith('enc$aes$') or value.startswith('enc$aes_hmac$'):
118 136 # protect against double encrypting if someone manually starts
119 137 # doing
120 138 raise ValueError('value needs to be in unencrypted format, ie. '
121 139 'not starting with enc$aes')
122 140 return 'enc$aes_hmac$%s' % AESCipher(
123 141 ENCRYPTION_KEY, hmac=True).encrypt(value)
124 142
125 143 def process_result_value(self, value, dialect):
126 144 import rhodecode
127 145
128 146 if not value:
129 147 return value
130 148
131 149 parts = value.split('$', 3)
132 150 if not len(parts) == 3:
133 151 # probably not encrypted values
134 152 return value
135 153 else:
136 154 if parts[0] != 'enc':
137 155 # parts ok but without our header ?
138 156 return value
139 157 enc_strict_mode = str2bool(rhodecode.CONFIG.get(
140 158 'rhodecode.encrypted_values.strict') or True)
141 159 # at that stage we know it's our encryption
142 160 if parts[1] == 'aes':
143 161 decrypted_data = AESCipher(ENCRYPTION_KEY).decrypt(parts[2])
144 162 elif parts[1] == 'aes_hmac':
145 163 decrypted_data = AESCipher(
146 164 ENCRYPTION_KEY, hmac=True,
147 165 strict_verification=enc_strict_mode).decrypt(parts[2])
148 166 else:
149 167 raise ValueError(
150 168 'Encryption type part is wrong, must be `aes` '
151 169 'or `aes_hmac`, got `%s` instead' % (parts[1]))
152 170 return decrypted_data
153 171
154 172
155 173 class BaseModel(object):
156 174 """
157 175 Base Model for all classes
158 176 """
159 177
160 178 @classmethod
161 179 def _get_keys(cls):
162 180 """return column names for this model """
163 181 return class_mapper(cls).c.keys()
164 182
165 183 def get_dict(self):
166 184 """
167 185 return dict with keys and values corresponding
168 186 to this model data """
169 187
170 188 d = {}
171 189 for k in self._get_keys():
172 190 d[k] = getattr(self, k)
173 191
174 192 # also use __json__() if present to get additional fields
175 193 _json_attr = getattr(self, '__json__', None)
176 194 if _json_attr:
177 195 # update with attributes from __json__
178 196 if callable(_json_attr):
179 197 _json_attr = _json_attr()
180 198 for k, val in _json_attr.iteritems():
181 199 d[k] = val
182 200 return d
183 201
184 202 def get_appstruct(self):
185 203 """return list with keys and values tuples corresponding
186 204 to this model data """
187 205
188 206 l = []
189 207 for k in self._get_keys():
190 208 l.append((k, getattr(self, k),))
191 209 return l
192 210
193 211 def populate_obj(self, populate_dict):
194 212 """populate model with data from given populate_dict"""
195 213
196 214 for k in self._get_keys():
197 215 if k in populate_dict:
198 216 setattr(self, k, populate_dict[k])
199 217
200 218 @classmethod
201 219 def query(cls):
202 220 return Session().query(cls)
203 221
204 222 @classmethod
205 223 def get(cls, id_):
206 224 if id_:
207 225 return cls.query().get(id_)
208 226
209 227 @classmethod
210 228 def get_or_404(cls, id_):
211 229 from pyramid.httpexceptions import HTTPNotFound
212 230
213 231 try:
214 232 id_ = int(id_)
215 233 except (TypeError, ValueError):
216 234 raise HTTPNotFound()
217 235
218 236 res = cls.query().get(id_)
219 237 if not res:
220 238 raise HTTPNotFound()
221 239 return res
222 240
223 241 @classmethod
224 242 def getAll(cls):
225 243 # deprecated and left for backward compatibility
226 244 return cls.get_all()
227 245
228 246 @classmethod
229 247 def get_all(cls):
230 248 return cls.query().all()
231 249
232 250 @classmethod
233 251 def delete(cls, id_):
234 252 obj = cls.query().get(id_)
235 253 Session().delete(obj)
236 254
237 255 @classmethod
238 256 def identity_cache(cls, session, attr_name, value):
239 257 exist_in_session = []
240 258 for (item_cls, pkey), instance in session.identity_map.items():
241 259 if cls == item_cls and getattr(instance, attr_name) == value:
242 260 exist_in_session.append(instance)
243 261 if exist_in_session:
244 262 if len(exist_in_session) == 1:
245 263 return exist_in_session[0]
246 264 log.exception(
247 265 'multiple objects with attr %s and '
248 266 'value %s found with same name: %r',
249 267 attr_name, value, exist_in_session)
250 268
251 269 def __repr__(self):
252 270 if hasattr(self, '__unicode__'):
253 271 # python repr needs to return str
254 272 try:
255 273 return safe_str(self.__unicode__())
256 274 except UnicodeDecodeError:
257 275 pass
258 276 return '<DB:%s>' % (self.__class__.__name__)
259 277
260 278
261 279 class RhodeCodeSetting(Base, BaseModel):
262 280 __tablename__ = 'rhodecode_settings'
263 281 __table_args__ = (
264 282 UniqueConstraint('app_settings_name'),
265 283 {'extend_existing': True, 'mysql_engine': 'InnoDB',
266 284 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
267 285 )
268 286
269 287 SETTINGS_TYPES = {
270 288 'str': safe_str,
271 289 'int': safe_int,
272 290 'unicode': safe_unicode,
273 291 'bool': str2bool,
274 292 'list': functools.partial(aslist, sep=',')
275 293 }
276 294 DEFAULT_UPDATE_URL = 'https://rhodecode.com/api/v1/info/versions'
277 295 GLOBAL_CONF_KEY = 'app_settings'
278 296
279 297 app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
280 298 app_settings_name = Column("app_settings_name", String(255), nullable=True, unique=None, default=None)
281 299 _app_settings_value = Column("app_settings_value", String(4096), nullable=True, unique=None, default=None)
282 300 _app_settings_type = Column("app_settings_type", String(255), nullable=True, unique=None, default=None)
283 301
284 302 def __init__(self, key='', val='', type='unicode'):
285 303 self.app_settings_name = key
286 304 self.app_settings_type = type
287 305 self.app_settings_value = val
288 306
289 307 @validates('_app_settings_value')
290 308 def validate_settings_value(self, key, val):
291 309 assert type(val) == unicode
292 310 return val
293 311
294 312 @hybrid_property
295 313 def app_settings_value(self):
296 314 v = self._app_settings_value
297 315 _type = self.app_settings_type
298 316 if _type:
299 317 _type = self.app_settings_type.split('.')[0]
300 318 # decode the encrypted value
301 319 if 'encrypted' in self.app_settings_type:
302 320 cipher = EncryptedTextValue()
303 321 v = safe_unicode(cipher.process_result_value(v, None))
304 322
305 323 converter = self.SETTINGS_TYPES.get(_type) or \
306 324 self.SETTINGS_TYPES['unicode']
307 325 return converter(v)
308 326
309 327 @app_settings_value.setter
310 328 def app_settings_value(self, val):
311 329 """
312 330 Setter that will always make sure we use unicode in app_settings_value
313 331
314 332 :param val:
315 333 """
316 334 val = safe_unicode(val)
317 335 # encode the encrypted value
318 336 if 'encrypted' in self.app_settings_type:
319 337 cipher = EncryptedTextValue()
320 338 val = safe_unicode(cipher.process_bind_param(val, None))
321 339 self._app_settings_value = val
322 340
323 341 @hybrid_property
324 342 def app_settings_type(self):
325 343 return self._app_settings_type
326 344
327 345 @app_settings_type.setter
328 346 def app_settings_type(self, val):
329 347 if val.split('.')[0] not in self.SETTINGS_TYPES:
330 348 raise Exception('type must be one of %s got %s'
331 349 % (self.SETTINGS_TYPES.keys(), val))
332 350 self._app_settings_type = val
333 351
334 352 def __unicode__(self):
335 353 return u"<%s('%s:%s[%s]')>" % (
336 354 self.__class__.__name__,
337 355 self.app_settings_name, self.app_settings_value,
338 356 self.app_settings_type
339 357 )
340 358
341 359
342 360 class RhodeCodeUi(Base, BaseModel):
343 361 __tablename__ = 'rhodecode_ui'
344 362 __table_args__ = (
345 363 UniqueConstraint('ui_key'),
346 364 {'extend_existing': True, 'mysql_engine': 'InnoDB',
347 365 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
348 366 )
349 367
350 368 HOOK_REPO_SIZE = 'changegroup.repo_size'
351 369 # HG
352 370 HOOK_PRE_PULL = 'preoutgoing.pre_pull'
353 371 HOOK_PULL = 'outgoing.pull_logger'
354 372 HOOK_PRE_PUSH = 'prechangegroup.pre_push'
355 373 HOOK_PRETX_PUSH = 'pretxnchangegroup.pre_push'
356 374 HOOK_PUSH = 'changegroup.push_logger'
357 375 HOOK_PUSH_KEY = 'pushkey.key_push'
358 376
359 377 # TODO: johbo: Unify way how hooks are configured for git and hg,
360 378 # git part is currently hardcoded.
361 379
362 380 # SVN PATTERNS
363 381 SVN_BRANCH_ID = 'vcs_svn_branch'
364 382 SVN_TAG_ID = 'vcs_svn_tag'
365 383
366 384 ui_id = Column(
367 385 "ui_id", Integer(), nullable=False, unique=True, default=None,
368 386 primary_key=True)
369 387 ui_section = Column(
370 388 "ui_section", String(255), nullable=True, unique=None, default=None)
371 389 ui_key = Column(
372 390 "ui_key", String(255), nullable=True, unique=None, default=None)
373 391 ui_value = Column(
374 392 "ui_value", String(255), nullable=True, unique=None, default=None)
375 393 ui_active = Column(
376 394 "ui_active", Boolean(), nullable=True, unique=None, default=True)
377 395
378 396 def __repr__(self):
379 397 return '<%s[%s]%s=>%s]>' % (self.__class__.__name__, self.ui_section,
380 398 self.ui_key, self.ui_value)
381 399
382 400
383 401 class RepoRhodeCodeSetting(Base, BaseModel):
384 402 __tablename__ = 'repo_rhodecode_settings'
385 403 __table_args__ = (
386 404 UniqueConstraint(
387 405 'app_settings_name', 'repository_id',
388 406 name='uq_repo_rhodecode_setting_name_repo_id'),
389 407 {'extend_existing': True, 'mysql_engine': 'InnoDB',
390 408 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
391 409 )
392 410
393 411 repository_id = Column(
394 412 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
395 413 nullable=False)
396 414 app_settings_id = Column(
397 415 "app_settings_id", Integer(), nullable=False, unique=True,
398 416 default=None, primary_key=True)
399 417 app_settings_name = Column(
400 418 "app_settings_name", String(255), nullable=True, unique=None,
401 419 default=None)
402 420 _app_settings_value = Column(
403 421 "app_settings_value", String(4096), nullable=True, unique=None,
404 422 default=None)
405 423 _app_settings_type = Column(
406 424 "app_settings_type", String(255), nullable=True, unique=None,
407 425 default=None)
408 426
409 427 repository = relationship('Repository')
410 428
411 429 def __init__(self, repository_id, key='', val='', type='unicode'):
412 430 self.repository_id = repository_id
413 431 self.app_settings_name = key
414 432 self.app_settings_type = type
415 433 self.app_settings_value = val
416 434
417 435 @validates('_app_settings_value')
418 436 def validate_settings_value(self, key, val):
419 437 assert type(val) == unicode
420 438 return val
421 439
422 440 @hybrid_property
423 441 def app_settings_value(self):
424 442 v = self._app_settings_value
425 443 type_ = self.app_settings_type
426 444 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
427 445 converter = SETTINGS_TYPES.get(type_) or SETTINGS_TYPES['unicode']
428 446 return converter(v)
429 447
430 448 @app_settings_value.setter
431 449 def app_settings_value(self, val):
432 450 """
433 451 Setter that will always make sure we use unicode in app_settings_value
434 452
435 453 :param val:
436 454 """
437 455 self._app_settings_value = safe_unicode(val)
438 456
439 457 @hybrid_property
440 458 def app_settings_type(self):
441 459 return self._app_settings_type
442 460
443 461 @app_settings_type.setter
444 462 def app_settings_type(self, val):
445 463 SETTINGS_TYPES = RhodeCodeSetting.SETTINGS_TYPES
446 464 if val not in SETTINGS_TYPES:
447 465 raise Exception('type must be one of %s got %s'
448 466 % (SETTINGS_TYPES.keys(), val))
449 467 self._app_settings_type = val
450 468
451 469 def __unicode__(self):
452 470 return u"<%s('%s:%s:%s[%s]')>" % (
453 471 self.__class__.__name__, self.repository.repo_name,
454 472 self.app_settings_name, self.app_settings_value,
455 473 self.app_settings_type
456 474 )
457 475
458 476
459 477 class RepoRhodeCodeUi(Base, BaseModel):
460 478 __tablename__ = 'repo_rhodecode_ui'
461 479 __table_args__ = (
462 480 UniqueConstraint(
463 481 'repository_id', 'ui_section', 'ui_key',
464 482 name='uq_repo_rhodecode_ui_repository_id_section_key'),
465 483 {'extend_existing': True, 'mysql_engine': 'InnoDB',
466 484 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
467 485 )
468 486
469 487 repository_id = Column(
470 488 "repository_id", Integer(), ForeignKey('repositories.repo_id'),
471 489 nullable=False)
472 490 ui_id = Column(
473 491 "ui_id", Integer(), nullable=False, unique=True, default=None,
474 492 primary_key=True)
475 493 ui_section = Column(
476 494 "ui_section", String(255), nullable=True, unique=None, default=None)
477 495 ui_key = Column(
478 496 "ui_key", String(255), nullable=True, unique=None, default=None)
479 497 ui_value = Column(
480 498 "ui_value", String(255), nullable=True, unique=None, default=None)
481 499 ui_active = Column(
482 500 "ui_active", Boolean(), nullable=True, unique=None, default=True)
483 501
484 502 repository = relationship('Repository')
485 503
486 504 def __repr__(self):
487 505 return '<%s[%s:%s]%s=>%s]>' % (
488 506 self.__class__.__name__, self.repository.repo_name,
489 507 self.ui_section, self.ui_key, self.ui_value)
490 508
491 509
492 510 class User(Base, BaseModel):
493 511 __tablename__ = 'users'
494 512 __table_args__ = (
495 513 UniqueConstraint('username'), UniqueConstraint('email'),
496 514 Index('u_username_idx', 'username'),
497 515 Index('u_email_idx', 'email'),
498 516 {'extend_existing': True, 'mysql_engine': 'InnoDB',
499 517 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
500 518 )
501 519 DEFAULT_USER = 'default'
502 520 DEFAULT_USER_EMAIL = 'anonymous@rhodecode.org'
503 521 DEFAULT_GRAVATAR_URL = 'https://secure.gravatar.com/avatar/{md5email}?d=identicon&s={size}'
504 522
505 523 user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
506 524 username = Column("username", String(255), nullable=True, unique=None, default=None)
507 525 password = Column("password", String(255), nullable=True, unique=None, default=None)
508 526 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
509 527 admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
510 528 name = Column("firstname", String(255), nullable=True, unique=None, default=None)
511 529 lastname = Column("lastname", String(255), nullable=True, unique=None, default=None)
512 530 _email = Column("email", String(255), nullable=True, unique=None, default=None)
513 531 last_login = Column("last_login", DateTime(timezone=False), nullable=True, unique=None, default=None)
514 532 last_activity = Column('last_activity', DateTime(timezone=False), nullable=True, unique=None, default=None)
515 533
516 534 extern_type = Column("extern_type", String(255), nullable=True, unique=None, default=None)
517 535 extern_name = Column("extern_name", String(255), nullable=True, unique=None, default=None)
518 536 _api_key = Column("api_key", String(255), nullable=True, unique=None, default=None)
519 537 inherit_default_permissions = Column("inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
520 538 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
521 539 _user_data = Column("user_data", LargeBinary(), nullable=True) # JSON data
522 540
523 541 user_log = relationship('UserLog')
524 542 user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
525 543
526 544 repositories = relationship('Repository')
527 545 repository_groups = relationship('RepoGroup')
528 546 user_groups = relationship('UserGroup')
529 547
530 548 user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
531 549 followings = relationship('UserFollowing', primaryjoin='UserFollowing.user_id==User.user_id', cascade='all')
532 550
533 551 repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
534 552 repo_group_to_perm = relationship('UserRepoGroupToPerm', primaryjoin='UserRepoGroupToPerm.user_id==User.user_id', cascade='all')
535 553 user_group_to_perm = relationship('UserUserGroupToPerm', primaryjoin='UserUserGroupToPerm.user_id==User.user_id', cascade='all')
536 554
537 555 group_member = relationship('UserGroupMember', cascade='all')
538 556
539 557 notifications = relationship('UserNotification', cascade='all')
540 558 # notifications assigned to this user
541 559 user_created_notifications = relationship('Notification', cascade='all')
542 560 # comments created by this user
543 561 user_comments = relationship('ChangesetComment', cascade='all')
544 562 # user profile extra info
545 563 user_emails = relationship('UserEmailMap', cascade='all')
546 564 user_ip_map = relationship('UserIpMap', cascade='all')
547 565 user_auth_tokens = relationship('UserApiKeys', cascade='all')
548 566 user_ssh_keys = relationship('UserSshKeys', cascade='all')
549 567
550 568 # gists
551 569 user_gists = relationship('Gist', cascade='all')
552 570 # user pull requests
553 571 user_pull_requests = relationship('PullRequest', cascade='all')
554 572 # external identities
555 573 extenal_identities = relationship(
556 574 'ExternalIdentity',
557 575 primaryjoin="User.user_id==ExternalIdentity.local_user_id",
558 576 cascade='all')
559 577
560 578 def __unicode__(self):
561 579 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
562 580 self.user_id, self.username)
563 581
564 582 @hybrid_property
565 583 def email(self):
566 584 return self._email
567 585
568 586 @email.setter
569 587 def email(self, val):
570 588 self._email = val.lower() if val else None
571 589
572 590 @hybrid_property
573 591 def first_name(self):
574 592 from rhodecode.lib import helpers as h
575 593 if self.name:
576 594 return h.escape(self.name)
577 595 return self.name
578 596
579 597 @hybrid_property
580 598 def last_name(self):
581 599 from rhodecode.lib import helpers as h
582 600 if self.lastname:
583 601 return h.escape(self.lastname)
584 602 return self.lastname
585 603
586 604 @hybrid_property
587 605 def api_key(self):
588 606 """
589 607 Fetch if exist an auth-token with role ALL connected to this user
590 608 """
591 609 user_auth_token = UserApiKeys.query()\
592 610 .filter(UserApiKeys.user_id == self.user_id)\
593 611 .filter(or_(UserApiKeys.expires == -1,
594 612 UserApiKeys.expires >= time.time()))\
595 613 .filter(UserApiKeys.role == UserApiKeys.ROLE_ALL).first()
596 614 if user_auth_token:
597 615 user_auth_token = user_auth_token.api_key
598 616
599 617 return user_auth_token
600 618
601 619 @api_key.setter
602 620 def api_key(self, val):
603 621 # don't allow to set API key this is deprecated for now
604 622 self._api_key = None
605 623
606 624 @property
607 625 def reviewer_pull_requests(self):
608 626 return PullRequestReviewers.query() \
609 627 .options(joinedload(PullRequestReviewers.pull_request)) \
610 628 .filter(PullRequestReviewers.user_id == self.user_id) \
611 629 .all()
612 630
613 631 @property
614 632 def firstname(self):
615 633 # alias for future
616 634 return self.name
617 635
618 636 @property
619 637 def emails(self):
620 638 other = UserEmailMap.query()\
621 639 .filter(UserEmailMap.user == self) \
622 640 .order_by(UserEmailMap.email_id.asc()) \
623 641 .all()
624 642 return [self.email] + [x.email for x in other]
625 643
626 644 @property
627 645 def auth_tokens(self):
628 646 auth_tokens = self.get_auth_tokens()
629 647 return [x.api_key for x in auth_tokens]
630 648
631 649 def get_auth_tokens(self):
632 650 return UserApiKeys.query()\
633 651 .filter(UserApiKeys.user == self)\
634 652 .order_by(UserApiKeys.user_api_key_id.asc())\
635 653 .all()
636 654
637 655 @property
638 656 def feed_token(self):
639 657 return self.get_feed_token()
640 658
641 659 def get_feed_token(self):
642 660 feed_tokens = UserApiKeys.query()\
643 661 .filter(UserApiKeys.user == self)\
644 662 .filter(UserApiKeys.role == UserApiKeys.ROLE_FEED)\
645 663 .all()
646 664 if feed_tokens:
647 665 return feed_tokens[0].api_key
648 666 return 'NO_FEED_TOKEN_AVAILABLE'
649 667
650 668 @classmethod
651 669 def extra_valid_auth_tokens(cls, user, role=None):
652 670 tokens = UserApiKeys.query().filter(UserApiKeys.user == user)\
653 671 .filter(or_(UserApiKeys.expires == -1,
654 672 UserApiKeys.expires >= time.time()))
655 673 if role:
656 674 tokens = tokens.filter(or_(UserApiKeys.role == role,
657 675 UserApiKeys.role == UserApiKeys.ROLE_ALL))
658 676 return tokens.all()
659 677
660 678 def authenticate_by_token(self, auth_token, roles=None, scope_repo_id=None):
661 679 from rhodecode.lib import auth
662 680
663 681 log.debug('Trying to authenticate user: %s via auth-token, '
664 682 'and roles: %s', self, roles)
665 683
666 684 if not auth_token:
667 685 return False
668 686
669 687 crypto_backend = auth.crypto_backend()
670 688
671 689 roles = (roles or []) + [UserApiKeys.ROLE_ALL]
672 690 tokens_q = UserApiKeys.query()\
673 691 .filter(UserApiKeys.user_id == self.user_id)\
674 692 .filter(or_(UserApiKeys.expires == -1,
675 693 UserApiKeys.expires >= time.time()))
676 694
677 695 tokens_q = tokens_q.filter(UserApiKeys.role.in_(roles))
678 696
679 697 plain_tokens = []
680 698 hash_tokens = []
681 699
682 700 for token in tokens_q.all():
683 701 # verify scope first
684 702 if token.repo_id:
685 703 # token has a scope, we need to verify it
686 704 if scope_repo_id != token.repo_id:
687 705 log.debug(
688 706 'Scope mismatch: token has a set repo scope: %s, '
689 707 'and calling scope is:%s, skipping further checks',
690 708 token.repo, scope_repo_id)
691 709 # token has a scope, and it doesn't match, skip token
692 710 continue
693 711
694 712 if token.api_key.startswith(crypto_backend.ENC_PREF):
695 713 hash_tokens.append(token.api_key)
696 714 else:
697 715 plain_tokens.append(token.api_key)
698 716
699 717 is_plain_match = auth_token in plain_tokens
700 718 if is_plain_match:
701 719 return True
702 720
703 721 for hashed in hash_tokens:
704 722 # TODO(marcink): this is expensive to calculate, but most secure
705 723 match = crypto_backend.hash_check(auth_token, hashed)
706 724 if match:
707 725 return True
708 726
709 727 return False
710 728
711 729 @property
712 730 def ip_addresses(self):
713 731 ret = UserIpMap.query().filter(UserIpMap.user == self).all()
714 732 return [x.ip_addr for x in ret]
715 733
716 734 @property
717 735 def username_and_name(self):
718 736 return '%s (%s %s)' % (self.username, self.first_name, self.last_name)
719 737
720 738 @property
721 739 def username_or_name_or_email(self):
722 740 full_name = self.full_name if self.full_name is not ' ' else None
723 741 return self.username or full_name or self.email
724 742
725 743 @property
726 744 def full_name(self):
727 745 return '%s %s' % (self.first_name, self.last_name)
728 746
729 747 @property
730 748 def full_name_or_username(self):
731 749 return ('%s %s' % (self.first_name, self.last_name)
732 750 if (self.first_name and self.last_name) else self.username)
733 751
734 752 @property
735 753 def full_contact(self):
736 754 return '%s %s <%s>' % (self.first_name, self.last_name, self.email)
737 755
738 756 @property
739 757 def short_contact(self):
740 758 return '%s %s' % (self.first_name, self.last_name)
741 759
742 760 @property
743 761 def is_admin(self):
744 762 return self.admin
745 763
746 764 def AuthUser(self, **kwargs):
747 765 """
748 766 Returns instance of AuthUser for this user
749 767 """
750 768 from rhodecode.lib.auth import AuthUser
751 769 return AuthUser(user_id=self.user_id, username=self.username, **kwargs)
752 770
753 771 @hybrid_property
754 772 def user_data(self):
755 773 if not self._user_data:
756 774 return {}
757 775
758 776 try:
759 777 return json.loads(self._user_data)
760 778 except TypeError:
761 779 return {}
762 780
763 781 @user_data.setter
764 782 def user_data(self, val):
765 783 if not isinstance(val, dict):
766 784 raise Exception('user_data must be dict, got %s' % type(val))
767 785 try:
768 786 self._user_data = json.dumps(val)
769 787 except Exception:
770 788 log.error(traceback.format_exc())
771 789
772 790 @classmethod
773 791 def get_by_username(cls, username, case_insensitive=False,
774 792 cache=False, identity_cache=False):
775 793 session = Session()
776 794
777 795 if case_insensitive:
778 796 q = cls.query().filter(
779 797 func.lower(cls.username) == func.lower(username))
780 798 else:
781 799 q = cls.query().filter(cls.username == username)
782 800
783 801 if cache:
784 802 if identity_cache:
785 803 val = cls.identity_cache(session, 'username', username)
786 804 if val:
787 805 return val
788 806 else:
789 807 cache_key = "get_user_by_name_%s" % _hash_key(username)
790 808 q = q.options(
791 809 FromCache("sql_cache_short", cache_key))
792 810
793 811 return q.scalar()
794 812
795 813 @classmethod
796 814 def get_by_auth_token(cls, auth_token, cache=False):
797 815 q = UserApiKeys.query()\
798 816 .filter(UserApiKeys.api_key == auth_token)\
799 817 .filter(or_(UserApiKeys.expires == -1,
800 818 UserApiKeys.expires >= time.time()))
801 819 if cache:
802 820 q = q.options(
803 821 FromCache("sql_cache_short", "get_auth_token_%s" % auth_token))
804 822
805 823 match = q.first()
806 824 if match:
807 825 return match.user
808 826
809 827 @classmethod
810 828 def get_by_email(cls, email, case_insensitive=False, cache=False):
811 829
812 830 if case_insensitive:
813 831 q = cls.query().filter(func.lower(cls.email) == func.lower(email))
814 832
815 833 else:
816 834 q = cls.query().filter(cls.email == email)
817 835
818 836 email_key = _hash_key(email)
819 837 if cache:
820 838 q = q.options(
821 839 FromCache("sql_cache_short", "get_email_key_%s" % email_key))
822 840
823 841 ret = q.scalar()
824 842 if ret is None:
825 843 q = UserEmailMap.query()
826 844 # try fetching in alternate email map
827 845 if case_insensitive:
828 846 q = q.filter(func.lower(UserEmailMap.email) == func.lower(email))
829 847 else:
830 848 q = q.filter(UserEmailMap.email == email)
831 849 q = q.options(joinedload(UserEmailMap.user))
832 850 if cache:
833 851 q = q.options(
834 852 FromCache("sql_cache_short", "get_email_map_key_%s" % email_key))
835 853 ret = getattr(q.scalar(), 'user', None)
836 854
837 855 return ret
838 856
839 857 @classmethod
840 858 def get_from_cs_author(cls, author):
841 859 """
842 860 Tries to get User objects out of commit author string
843 861
844 862 :param author:
845 863 """
846 864 from rhodecode.lib.helpers import email, author_name
847 865 # Valid email in the attribute passed, see if they're in the system
848 866 _email = email(author)
849 867 if _email:
850 868 user = cls.get_by_email(_email, case_insensitive=True)
851 869 if user:
852 870 return user
853 871 # Maybe we can match by username?
854 872 _author = author_name(author)
855 873 user = cls.get_by_username(_author, case_insensitive=True)
856 874 if user:
857 875 return user
858 876
859 877 def update_userdata(self, **kwargs):
860 878 usr = self
861 879 old = usr.user_data
862 880 old.update(**kwargs)
863 881 usr.user_data = old
864 882 Session().add(usr)
865 883 log.debug('updated userdata with ', kwargs)
866 884
867 885 def update_lastlogin(self):
868 886 """Update user lastlogin"""
869 887 self.last_login = datetime.datetime.now()
870 888 Session().add(self)
871 889 log.debug('updated user %s lastlogin', self.username)
872 890
873 891 def update_lastactivity(self):
874 892 """Update user lastactivity"""
875 893 self.last_activity = datetime.datetime.now()
876 894 Session().add(self)
877 895 log.debug('updated user %s lastactivity', self.username)
878 896
879 897 def update_password(self, new_password):
880 898 from rhodecode.lib.auth import get_crypt_password
881 899
882 900 self.password = get_crypt_password(new_password)
883 901 Session().add(self)
884 902
885 903 @classmethod
886 904 def get_first_super_admin(cls):
887 905 user = User.query().filter(User.admin == true()).first()
888 906 if user is None:
889 907 raise Exception('FATAL: Missing administrative account!')
890 908 return user
891 909
892 910 @classmethod
893 911 def get_all_super_admins(cls):
894 912 """
895 913 Returns all admin accounts sorted by username
896 914 """
897 915 return User.query().filter(User.admin == true())\
898 916 .order_by(User.username.asc()).all()
899 917
900 918 @classmethod
901 919 def get_default_user(cls, cache=False, refresh=False):
902 920 user = User.get_by_username(User.DEFAULT_USER, cache=cache)
903 921 if user is None:
904 922 raise Exception('FATAL: Missing default account!')
905 923 if refresh:
906 924 # The default user might be based on outdated state which
907 925 # has been loaded from the cache.
908 926 # A call to refresh() ensures that the
909 927 # latest state from the database is used.
910 928 Session().refresh(user)
911 929 return user
912 930
913 931 def _get_default_perms(self, user, suffix=''):
914 932 from rhodecode.model.permission import PermissionModel
915 933 return PermissionModel().get_default_perms(user.user_perms, suffix)
916 934
917 935 def get_default_perms(self, suffix=''):
918 936 return self._get_default_perms(self, suffix)
919 937
920 938 def get_api_data(self, include_secrets=False, details='full'):
921 939 """
922 940 Common function for generating user related data for API
923 941
924 942 :param include_secrets: By default secrets in the API data will be replaced
925 943 by a placeholder value to prevent exposing this data by accident. In case
926 944 this data shall be exposed, set this flag to ``True``.
927 945
928 946 :param details: details can be 'basic|full' basic gives only a subset of
929 947 the available user information that includes user_id, name and emails.
930 948 """
931 949 user = self
932 950 user_data = self.user_data
933 951 data = {
934 952 'user_id': user.user_id,
935 953 'username': user.username,
936 954 'firstname': user.name,
937 955 'lastname': user.lastname,
938 956 'email': user.email,
939 957 'emails': user.emails,
940 958 }
941 959 if details == 'basic':
942 960 return data
943 961
944 962 auth_token_length = 40
945 963 auth_token_replacement = '*' * auth_token_length
946 964
947 965 extras = {
948 966 'auth_tokens': [auth_token_replacement],
949 967 'active': user.active,
950 968 'admin': user.admin,
951 969 'extern_type': user.extern_type,
952 970 'extern_name': user.extern_name,
953 971 'last_login': user.last_login,
954 972 'last_activity': user.last_activity,
955 973 'ip_addresses': user.ip_addresses,
956 974 'language': user_data.get('language')
957 975 }
958 976 data.update(extras)
959 977
960 978 if include_secrets:
961 979 data['auth_tokens'] = user.auth_tokens
962 980 return data
963 981
964 982 def __json__(self):
965 983 data = {
966 984 'full_name': self.full_name,
967 985 'full_name_or_username': self.full_name_or_username,
968 986 'short_contact': self.short_contact,
969 987 'full_contact': self.full_contact,
970 988 }
971 989 data.update(self.get_api_data())
972 990 return data
973 991
974 992
975 993 class UserApiKeys(Base, BaseModel):
976 994 __tablename__ = 'user_api_keys'
977 995 __table_args__ = (
978 996 Index('uak_api_key_idx', 'api_key', unique=True),
979 997 Index('uak_api_key_expires_idx', 'api_key', 'expires'),
980 998 {'extend_existing': True, 'mysql_engine': 'InnoDB',
981 999 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
982 1000 )
983 1001 __mapper_args__ = {}
984 1002
985 1003 # ApiKey role
986 1004 ROLE_ALL = 'token_role_all'
987 1005 ROLE_HTTP = 'token_role_http'
988 1006 ROLE_VCS = 'token_role_vcs'
989 1007 ROLE_API = 'token_role_api'
990 1008 ROLE_FEED = 'token_role_feed'
991 1009 ROLE_PASSWORD_RESET = 'token_password_reset'
992 1010
993 1011 ROLES = [ROLE_ALL, ROLE_HTTP, ROLE_VCS, ROLE_API, ROLE_FEED]
994 1012
995 1013 user_api_key_id = Column("user_api_key_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
996 1014 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
997 1015 api_key = Column("api_key", String(255), nullable=False, unique=True)
998 1016 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
999 1017 expires = Column('expires', Float(53), nullable=False)
1000 1018 role = Column('role', String(255), nullable=True)
1001 1019 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1002 1020
1003 1021 # scope columns
1004 1022 repo_id = Column(
1005 1023 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
1006 1024 nullable=True, unique=None, default=None)
1007 1025 repo = relationship('Repository', lazy='joined')
1008 1026
1009 1027 repo_group_id = Column(
1010 1028 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
1011 1029 nullable=True, unique=None, default=None)
1012 1030 repo_group = relationship('RepoGroup', lazy='joined')
1013 1031
1014 1032 user = relationship('User', lazy='joined')
1015 1033
1016 1034 def __unicode__(self):
1017 1035 return u"<%s('%s')>" % (self.__class__.__name__, self.role)
1018 1036
1019 1037 def __json__(self):
1020 1038 data = {
1021 1039 'auth_token': self.api_key,
1022 1040 'role': self.role,
1023 1041 'scope': self.scope_humanized,
1024 1042 'expired': self.expired
1025 1043 }
1026 1044 return data
1027 1045
1028 1046 def get_api_data(self, include_secrets=False):
1029 1047 data = self.__json__()
1030 1048 if include_secrets:
1031 1049 return data
1032 1050 else:
1033 1051 data['auth_token'] = self.token_obfuscated
1034 1052 return data
1035 1053
1036 1054 @hybrid_property
1037 1055 def description_safe(self):
1038 1056 from rhodecode.lib import helpers as h
1039 1057 return h.escape(self.description)
1040 1058
1041 1059 @property
1042 1060 def expired(self):
1043 1061 if self.expires == -1:
1044 1062 return False
1045 1063 return time.time() > self.expires
1046 1064
1047 1065 @classmethod
1048 1066 def _get_role_name(cls, role):
1049 1067 return {
1050 1068 cls.ROLE_ALL: _('all'),
1051 1069 cls.ROLE_HTTP: _('http/web interface'),
1052 1070 cls.ROLE_VCS: _('vcs (git/hg/svn protocol)'),
1053 1071 cls.ROLE_API: _('api calls'),
1054 1072 cls.ROLE_FEED: _('feed access'),
1055 1073 }.get(role, role)
1056 1074
1057 1075 @property
1058 1076 def role_humanized(self):
1059 1077 return self._get_role_name(self.role)
1060 1078
1061 1079 def _get_scope(self):
1062 1080 if self.repo:
1063 1081 return repr(self.repo)
1064 1082 if self.repo_group:
1065 1083 return repr(self.repo_group) + ' (recursive)'
1066 1084 return 'global'
1067 1085
1068 1086 @property
1069 1087 def scope_humanized(self):
1070 1088 return self._get_scope()
1071 1089
1072 1090 @property
1073 1091 def token_obfuscated(self):
1074 1092 if self.api_key:
1075 1093 return self.api_key[:4] + "****"
1076 1094
1077 1095
1078 1096 class UserEmailMap(Base, BaseModel):
1079 1097 __tablename__ = 'user_email_map'
1080 1098 __table_args__ = (
1081 1099 Index('uem_email_idx', 'email'),
1082 1100 UniqueConstraint('email'),
1083 1101 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1084 1102 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1085 1103 )
1086 1104 __mapper_args__ = {}
1087 1105
1088 1106 email_id = Column("email_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1089 1107 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1090 1108 _email = Column("email", String(255), nullable=True, unique=False, default=None)
1091 1109 user = relationship('User', lazy='joined')
1092 1110
1093 1111 @validates('_email')
1094 1112 def validate_email(self, key, email):
1095 1113 # check if this email is not main one
1096 1114 main_email = Session().query(User).filter(User.email == email).scalar()
1097 1115 if main_email is not None:
1098 1116 raise AttributeError('email %s is present is user table' % email)
1099 1117 return email
1100 1118
1101 1119 @hybrid_property
1102 1120 def email(self):
1103 1121 return self._email
1104 1122
1105 1123 @email.setter
1106 1124 def email(self, val):
1107 1125 self._email = val.lower() if val else None
1108 1126
1109 1127
1110 1128 class UserIpMap(Base, BaseModel):
1111 1129 __tablename__ = 'user_ip_map'
1112 1130 __table_args__ = (
1113 1131 UniqueConstraint('user_id', 'ip_addr'),
1114 1132 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1115 1133 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1116 1134 )
1117 1135 __mapper_args__ = {}
1118 1136
1119 1137 ip_id = Column("ip_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1120 1138 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1121 1139 ip_addr = Column("ip_addr", String(255), nullable=True, unique=False, default=None)
1122 1140 active = Column("active", Boolean(), nullable=True, unique=None, default=True)
1123 1141 description = Column("description", String(10000), nullable=True, unique=None, default=None)
1124 1142 user = relationship('User', lazy='joined')
1125 1143
1126 1144 @hybrid_property
1127 1145 def description_safe(self):
1128 1146 from rhodecode.lib import helpers as h
1129 1147 return h.escape(self.description)
1130 1148
1131 1149 @classmethod
1132 1150 def _get_ip_range(cls, ip_addr):
1133 1151 net = ipaddress.ip_network(safe_unicode(ip_addr), strict=False)
1134 1152 return [str(net.network_address), str(net.broadcast_address)]
1135 1153
1136 1154 def __json__(self):
1137 1155 return {
1138 1156 'ip_addr': self.ip_addr,
1139 1157 'ip_range': self._get_ip_range(self.ip_addr),
1140 1158 }
1141 1159
1142 1160 def __unicode__(self):
1143 1161 return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
1144 1162 self.user_id, self.ip_addr)
1145 1163
1146 1164
1147 1165 class UserSshKeys(Base, BaseModel):
1148 1166 __tablename__ = 'user_ssh_keys'
1149 1167 __table_args__ = (
1150 1168 Index('usk_ssh_key_fingerprint_idx', 'ssh_key_fingerprint'),
1151 1169
1152 1170 UniqueConstraint('ssh_key_fingerprint'),
1153 1171
1154 1172 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1155 1173 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
1156 1174 )
1157 1175 __mapper_args__ = {}
1158 1176
1159 1177 ssh_key_id = Column('ssh_key_id', Integer(), nullable=False, unique=True, default=None, primary_key=True)
1160 1178 ssh_key_data = Column('ssh_key_data', String(10240), nullable=False, unique=None, default=None)
1161 1179 ssh_key_fingerprint = Column('ssh_key_fingerprint', String(1024), nullable=False, unique=None, default=None)
1162 1180
1163 1181 description = Column('description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
1164 1182
1165 1183 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1166 1184 accessed_on = Column('accessed_on', DateTime(timezone=False), nullable=True, default=None)
1167 1185 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1168 1186
1169 1187 user = relationship('User', lazy='joined')
1170 1188
1171 1189 def __json__(self):
1172 1190 data = {
1173 1191 'ssh_fingerprint': self.ssh_key_fingerprint,
1174 1192 'description': self.description,
1175 1193 'created_on': self.created_on
1176 1194 }
1177 1195 return data
1178 1196
1179 1197 def get_api_data(self):
1180 1198 data = self.__json__()
1181 1199 return data
1182 1200
1183 1201
1184 1202 class UserLog(Base, BaseModel):
1185 1203 __tablename__ = 'user_logs'
1186 1204 __table_args__ = (
1187 1205 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1188 1206 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1189 1207 )
1190 1208 VERSION_1 = 'v1'
1191 1209 VERSION_2 = 'v2'
1192 1210 VERSIONS = [VERSION_1, VERSION_2]
1193 1211
1194 1212 user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1195 1213 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
1196 1214 username = Column("username", String(255), nullable=True, unique=None, default=None)
1197 1215 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True)
1198 1216 repository_name = Column("repository_name", String(255), nullable=True, unique=None, default=None)
1199 1217 user_ip = Column("user_ip", String(255), nullable=True, unique=None, default=None)
1200 1218 action = Column("action", Text().with_variant(Text(1200000), 'mysql'), nullable=True, unique=None, default=None)
1201 1219 action_date = Column("action_date", DateTime(timezone=False), nullable=True, unique=None, default=None)
1202 1220
1203 1221 version = Column("version", String(255), nullable=True, default=VERSION_1)
1204 1222 user_data = Column('user_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
1205 1223 action_data = Column('action_data_json', MutationObj.as_mutable(JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
1206 1224
1207 1225 def __unicode__(self):
1208 1226 return u"<%s('id:%s:%s')>" % (
1209 1227 self.__class__.__name__, self.repository_name, self.action)
1210 1228
1211 1229 def __json__(self):
1212 1230 return {
1213 1231 'user_id': self.user_id,
1214 1232 'username': self.username,
1215 1233 'repository_id': self.repository_id,
1216 1234 'repository_name': self.repository_name,
1217 1235 'user_ip': self.user_ip,
1218 1236 'action_date': self.action_date,
1219 1237 'action': self.action,
1220 1238 }
1221 1239
1222 1240 @property
1223 1241 def action_as_day(self):
1224 1242 return datetime.date(*self.action_date.timetuple()[:3])
1225 1243
1226 1244 user = relationship('User')
1227 1245 repository = relationship('Repository', cascade='')
1228 1246
1229 1247
1230 1248 class UserGroup(Base, BaseModel):
1231 1249 __tablename__ = 'users_groups'
1232 1250 __table_args__ = (
1233 1251 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1234 1252 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1235 1253 )
1236 1254
1237 1255 users_group_id = Column("users_group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1238 1256 users_group_name = Column("users_group_name", String(255), nullable=False, unique=True, default=None)
1239 1257 user_group_description = Column("user_group_description", String(10000), nullable=True, unique=None, default=None)
1240 1258 users_group_active = Column("users_group_active", Boolean(), nullable=True, unique=None, default=None)
1241 1259 inherit_default_permissions = Column("users_group_inherit_default_permissions", Boolean(), nullable=False, unique=None, default=True)
1242 1260 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
1243 1261 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1244 1262 _group_data = Column("group_data", LargeBinary(), nullable=True) # JSON data
1245 1263
1246 1264 members = relationship('UserGroupMember', cascade="all, delete, delete-orphan", lazy="joined")
1247 1265 users_group_to_perm = relationship('UserGroupToPerm', cascade='all')
1248 1266 users_group_repo_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1249 1267 users_group_repo_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
1250 1268 user_user_group_to_perm = relationship('UserUserGroupToPerm', cascade='all')
1251 1269 user_group_user_group_to_perm = relationship('UserGroupUserGroupToPerm ', primaryjoin="UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id", cascade='all')
1252 1270
1253 1271 user = relationship('User', primaryjoin="User.user_id==UserGroup.user_id")
1254 1272
1255 1273 @classmethod
1256 1274 def _load_group_data(cls, column):
1257 1275 if not column:
1258 1276 return {}
1259 1277
1260 1278 try:
1261 1279 return json.loads(column) or {}
1262 1280 except TypeError:
1263 1281 return {}
1264 1282
1265 1283 @hybrid_property
1266 1284 def description_safe(self):
1267 1285 from rhodecode.lib import helpers as h
1268 1286 return h.escape(self.description)
1269 1287
1270 1288 @hybrid_property
1271 1289 def group_data(self):
1272 1290 return self._load_group_data(self._group_data)
1273 1291
1274 1292 @group_data.expression
1275 1293 def group_data(self, **kwargs):
1276 1294 return self._group_data
1277 1295
1278 1296 @group_data.setter
1279 1297 def group_data(self, val):
1280 1298 try:
1281 1299 self._group_data = json.dumps(val)
1282 1300 except Exception:
1283 1301 log.error(traceback.format_exc())
1284 1302
1285 1303 def __unicode__(self):
1286 1304 return u"<%s('id:%s:%s')>" % (self.__class__.__name__,
1287 1305 self.users_group_id,
1288 1306 self.users_group_name)
1289 1307
1290 1308 @classmethod
1291 1309 def get_by_group_name(cls, group_name, cache=False,
1292 1310 case_insensitive=False):
1293 1311 if case_insensitive:
1294 1312 q = cls.query().filter(func.lower(cls.users_group_name) ==
1295 1313 func.lower(group_name))
1296 1314
1297 1315 else:
1298 1316 q = cls.query().filter(cls.users_group_name == group_name)
1299 1317 if cache:
1300 1318 q = q.options(
1301 1319 FromCache("sql_cache_short", "get_group_%s" % _hash_key(group_name)))
1302 1320 return q.scalar()
1303 1321
1304 1322 @classmethod
1305 1323 def get(cls, user_group_id, cache=False):
1306 1324 user_group = cls.query()
1307 1325 if cache:
1308 1326 user_group = user_group.options(
1309 1327 FromCache("sql_cache_short", "get_users_group_%s" % user_group_id))
1310 1328 return user_group.get(user_group_id)
1311 1329
1312 1330 def permissions(self, with_admins=True, with_owner=True):
1313 1331 q = UserUserGroupToPerm.query().filter(UserUserGroupToPerm.user_group == self)
1314 1332 q = q.options(joinedload(UserUserGroupToPerm.user_group),
1315 1333 joinedload(UserUserGroupToPerm.user),
1316 1334 joinedload(UserUserGroupToPerm.permission),)
1317 1335
1318 1336 # get owners and admins and permissions. We do a trick of re-writing
1319 1337 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1320 1338 # has a global reference and changing one object propagates to all
1321 1339 # others. This means if admin is also an owner admin_row that change
1322 1340 # would propagate to both objects
1323 1341 perm_rows = []
1324 1342 for _usr in q.all():
1325 1343 usr = AttributeDict(_usr.user.get_dict())
1326 1344 usr.permission = _usr.permission.permission_name
1327 1345 perm_rows.append(usr)
1328 1346
1329 1347 # filter the perm rows by 'default' first and then sort them by
1330 1348 # admin,write,read,none permissions sorted again alphabetically in
1331 1349 # each group
1332 1350 perm_rows = sorted(perm_rows, key=display_sort)
1333 1351
1334 1352 _admin_perm = 'usergroup.admin'
1335 1353 owner_row = []
1336 1354 if with_owner:
1337 1355 usr = AttributeDict(self.user.get_dict())
1338 1356 usr.owner_row = True
1339 1357 usr.permission = _admin_perm
1340 1358 owner_row.append(usr)
1341 1359
1342 1360 super_admin_rows = []
1343 1361 if with_admins:
1344 1362 for usr in User.get_all_super_admins():
1345 1363 # if this admin is also owner, don't double the record
1346 1364 if usr.user_id == owner_row[0].user_id:
1347 1365 owner_row[0].admin_row = True
1348 1366 else:
1349 1367 usr = AttributeDict(usr.get_dict())
1350 1368 usr.admin_row = True
1351 1369 usr.permission = _admin_perm
1352 1370 super_admin_rows.append(usr)
1353 1371
1354 1372 return super_admin_rows + owner_row + perm_rows
1355 1373
1356 1374 def permission_user_groups(self):
1357 1375 q = UserGroupUserGroupToPerm.query().filter(UserGroupUserGroupToPerm.target_user_group == self)
1358 1376 q = q.options(joinedload(UserGroupUserGroupToPerm.user_group),
1359 1377 joinedload(UserGroupUserGroupToPerm.target_user_group),
1360 1378 joinedload(UserGroupUserGroupToPerm.permission),)
1361 1379
1362 1380 perm_rows = []
1363 1381 for _user_group in q.all():
1364 1382 usr = AttributeDict(_user_group.user_group.get_dict())
1365 1383 usr.permission = _user_group.permission.permission_name
1366 1384 perm_rows.append(usr)
1367 1385
1368 1386 return perm_rows
1369 1387
1370 1388 def _get_default_perms(self, user_group, suffix=''):
1371 1389 from rhodecode.model.permission import PermissionModel
1372 1390 return PermissionModel().get_default_perms(user_group.users_group_to_perm, suffix)
1373 1391
1374 1392 def get_default_perms(self, suffix=''):
1375 1393 return self._get_default_perms(self, suffix)
1376 1394
1377 1395 def get_api_data(self, with_group_members=True, include_secrets=False):
1378 1396 """
1379 1397 :param include_secrets: See :meth:`User.get_api_data`, this parameter is
1380 1398 basically forwarded.
1381 1399
1382 1400 """
1383 1401 user_group = self
1384 1402 data = {
1385 1403 'users_group_id': user_group.users_group_id,
1386 1404 'group_name': user_group.users_group_name,
1387 1405 'group_description': user_group.user_group_description,
1388 1406 'active': user_group.users_group_active,
1389 1407 'owner': user_group.user.username,
1390 1408 'owner_email': user_group.user.email,
1391 1409 }
1392 1410
1393 1411 if with_group_members:
1394 1412 users = []
1395 1413 for user in user_group.members:
1396 1414 user = user.user
1397 1415 users.append(user.get_api_data(include_secrets=include_secrets))
1398 1416 data['users'] = users
1399 1417
1400 1418 return data
1401 1419
1402 1420
1403 1421 class UserGroupMember(Base, BaseModel):
1404 1422 __tablename__ = 'users_groups_members'
1405 1423 __table_args__ = (
1406 1424 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1407 1425 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1408 1426 )
1409 1427
1410 1428 users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1411 1429 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
1412 1430 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
1413 1431
1414 1432 user = relationship('User', lazy='joined')
1415 1433 users_group = relationship('UserGroup')
1416 1434
1417 1435 def __init__(self, gr_id='', u_id=''):
1418 1436 self.users_group_id = gr_id
1419 1437 self.user_id = u_id
1420 1438
1421 1439
1422 1440 class RepositoryField(Base, BaseModel):
1423 1441 __tablename__ = 'repositories_fields'
1424 1442 __table_args__ = (
1425 1443 UniqueConstraint('repository_id', 'field_key'), # no-multi field
1426 1444 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1427 1445 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1428 1446 )
1429 1447 PREFIX = 'ex_' # prefix used in form to not conflict with already existing fields
1430 1448
1431 1449 repo_field_id = Column("repo_field_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
1432 1450 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
1433 1451 field_key = Column("field_key", String(250))
1434 1452 field_label = Column("field_label", String(1024), nullable=False)
1435 1453 field_value = Column("field_value", String(10000), nullable=False)
1436 1454 field_desc = Column("field_desc", String(1024), nullable=False)
1437 1455 field_type = Column("field_type", String(255), nullable=False, unique=None)
1438 1456 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
1439 1457
1440 1458 repository = relationship('Repository')
1441 1459
1442 1460 @property
1443 1461 def field_key_prefixed(self):
1444 1462 return 'ex_%s' % self.field_key
1445 1463
1446 1464 @classmethod
1447 1465 def un_prefix_key(cls, key):
1448 1466 if key.startswith(cls.PREFIX):
1449 1467 return key[len(cls.PREFIX):]
1450 1468 return key
1451 1469
1452 1470 @classmethod
1453 1471 def get_by_key_name(cls, key, repo):
1454 1472 row = cls.query()\
1455 1473 .filter(cls.repository == repo)\
1456 1474 .filter(cls.field_key == key).scalar()
1457 1475 return row
1458 1476
1459 1477
1460 1478 class Repository(Base, BaseModel):
1461 1479 __tablename__ = 'repositories'
1462 1480 __table_args__ = (
1463 1481 Index('r_repo_name_idx', 'repo_name', mysql_length=255),
1464 1482 {'extend_existing': True, 'mysql_engine': 'InnoDB',
1465 1483 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
1466 1484 )
1467 1485 DEFAULT_CLONE_URI = '{scheme}://{user}@{netloc}/{repo}'
1468 1486 DEFAULT_CLONE_URI_ID = '{scheme}://{user}@{netloc}/_{repoid}'
1469 1487
1470 1488 STATE_CREATED = 'repo_state_created'
1471 1489 STATE_PENDING = 'repo_state_pending'
1472 1490 STATE_ERROR = 'repo_state_error'
1473 1491
1474 1492 LOCK_AUTOMATIC = 'lock_auto'
1475 1493 LOCK_API = 'lock_api'
1476 1494 LOCK_WEB = 'lock_web'
1477 1495 LOCK_PULL = 'lock_pull'
1478 1496
1479 1497 NAME_SEP = URL_SEP
1480 1498
1481 1499 repo_id = Column(
1482 1500 "repo_id", Integer(), nullable=False, unique=True, default=None,
1483 1501 primary_key=True)
1484 1502 _repo_name = Column(
1485 1503 "repo_name", Text(), nullable=False, default=None)
1486 1504 _repo_name_hash = Column(
1487 1505 "repo_name_hash", String(255), nullable=False, unique=True)
1488 1506 repo_state = Column("repo_state", String(255), nullable=True)
1489 1507
1490 1508 clone_uri = Column(
1491 1509 "clone_uri", EncryptedTextValue(), nullable=True, unique=False,
1492 1510 default=None)
1493 1511 repo_type = Column(
1494 1512 "repo_type", String(255), nullable=False, unique=False, default=None)
1495 1513 user_id = Column(
1496 1514 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
1497 1515 unique=False, default=None)
1498 1516 private = Column(
1499 1517 "private", Boolean(), nullable=True, unique=None, default=None)
1500 1518 enable_statistics = Column(
1501 1519 "statistics", Boolean(), nullable=True, unique=None, default=True)
1502 1520 enable_downloads = Column(
1503 1521 "downloads", Boolean(), nullable=True, unique=None, default=True)
1504 1522 description = Column(
1505 1523 "description", String(10000), nullable=True, unique=None, default=None)
1506 1524 created_on = Column(
1507 1525 'created_on', DateTime(timezone=False), nullable=True, unique=None,
1508 1526 default=datetime.datetime.now)
1509 1527 updated_on = Column(
1510 1528 'updated_on', DateTime(timezone=False), nullable=True, unique=None,
1511 1529 default=datetime.datetime.now)
1512 1530 _landing_revision = Column(
1513 1531 "landing_revision", String(255), nullable=False, unique=False,
1514 1532 default=None)
1515 1533 enable_locking = Column(
1516 1534 "enable_locking", Boolean(), nullable=False, unique=None,
1517 1535 default=False)
1518 1536 _locked = Column(
1519 1537 "locked", String(255), nullable=True, unique=False, default=None)
1520 1538 _changeset_cache = Column(
1521 1539 "changeset_cache", LargeBinary(), nullable=True) # JSON data
1522 1540
1523 1541 fork_id = Column(
1524 1542 "fork_id", Integer(), ForeignKey('repositories.repo_id'),
1525 1543 nullable=True, unique=False, default=None)
1526 1544 group_id = Column(
1527 1545 "group_id", Integer(), ForeignKey('groups.group_id'), nullable=True,
1528 1546 unique=False, default=None)
1529 1547
1530 1548 user = relationship('User', lazy='joined')
1531 1549 fork = relationship('Repository', remote_side=repo_id, lazy='joined')
1532 1550 group = relationship('RepoGroup', lazy='joined')
1533 1551 repo_to_perm = relationship(
1534 1552 'UserRepoToPerm', cascade='all',
1535 1553 order_by='UserRepoToPerm.repo_to_perm_id')
1536 1554 users_group_to_perm = relationship('UserGroupRepoToPerm', cascade='all')
1537 1555 stats = relationship('Statistics', cascade='all', uselist=False)
1538 1556
1539 1557 followers = relationship(
1540 1558 'UserFollowing',
1541 1559 primaryjoin='UserFollowing.follows_repo_id==Repository.repo_id',
1542 1560 cascade='all')
1543 1561 extra_fields = relationship(
1544 1562 'RepositoryField', cascade="all, delete, delete-orphan")
1545 1563 logs = relationship('UserLog')
1546 1564 comments = relationship(
1547 1565 'ChangesetComment', cascade="all, delete, delete-orphan")
1548 1566 pull_requests_source = relationship(
1549 1567 'PullRequest',
1550 1568 primaryjoin='PullRequest.source_repo_id==Repository.repo_id',
1551 1569 cascade="all, delete, delete-orphan")
1552 1570 pull_requests_target = relationship(
1553 1571 'PullRequest',
1554 1572 primaryjoin='PullRequest.target_repo_id==Repository.repo_id',
1555 1573 cascade="all, delete, delete-orphan")
1556 1574 ui = relationship('RepoRhodeCodeUi', cascade="all")
1557 1575 settings = relationship('RepoRhodeCodeSetting', cascade="all")
1558 1576 integrations = relationship('Integration',
1559 1577 cascade="all, delete, delete-orphan")
1560 1578
1561 1579 def __unicode__(self):
1562 1580 return u"<%s('%s:%s')>" % (self.__class__.__name__, self.repo_id,
1563 1581 safe_unicode(self.repo_name))
1564 1582
1565 1583 @hybrid_property
1566 1584 def description_safe(self):
1567 1585 from rhodecode.lib import helpers as h
1568 1586 return h.escape(self.description)
1569 1587
1570 1588 @hybrid_property
1571 1589 def landing_rev(self):
1572 1590 # always should return [rev_type, rev]
1573 1591 if self._landing_revision:
1574 1592 _rev_info = self._landing_revision.split(':')
1575 1593 if len(_rev_info) < 2:
1576 1594 _rev_info.insert(0, 'rev')
1577 1595 return [_rev_info[0], _rev_info[1]]
1578 1596 return [None, None]
1579 1597
1580 1598 @landing_rev.setter
1581 1599 def landing_rev(self, val):
1582 1600 if ':' not in val:
1583 1601 raise ValueError('value must be delimited with `:` and consist '
1584 1602 'of <rev_type>:<rev>, got %s instead' % val)
1585 1603 self._landing_revision = val
1586 1604
1587 1605 @hybrid_property
1588 1606 def locked(self):
1589 1607 if self._locked:
1590 1608 user_id, timelocked, reason = self._locked.split(':')
1591 1609 lock_values = int(user_id), timelocked, reason
1592 1610 else:
1593 1611 lock_values = [None, None, None]
1594 1612 return lock_values
1595 1613
1596 1614 @locked.setter
1597 1615 def locked(self, val):
1598 1616 if val and isinstance(val, (list, tuple)):
1599 1617 self._locked = ':'.join(map(str, val))
1600 1618 else:
1601 1619 self._locked = None
1602 1620
1603 1621 @hybrid_property
1604 1622 def changeset_cache(self):
1605 1623 from rhodecode.lib.vcs.backends.base import EmptyCommit
1606 1624 dummy = EmptyCommit().__json__()
1607 1625 if not self._changeset_cache:
1608 1626 return dummy
1609 1627 try:
1610 1628 return json.loads(self._changeset_cache)
1611 1629 except TypeError:
1612 1630 return dummy
1613 1631 except Exception:
1614 1632 log.error(traceback.format_exc())
1615 1633 return dummy
1616 1634
1617 1635 @changeset_cache.setter
1618 1636 def changeset_cache(self, val):
1619 1637 try:
1620 1638 self._changeset_cache = json.dumps(val)
1621 1639 except Exception:
1622 1640 log.error(traceback.format_exc())
1623 1641
1624 1642 @hybrid_property
1625 1643 def repo_name(self):
1626 1644 return self._repo_name
1627 1645
1628 1646 @repo_name.setter
1629 1647 def repo_name(self, value):
1630 1648 self._repo_name = value
1631 1649 self._repo_name_hash = hashlib.sha1(safe_str(value)).hexdigest()
1632 1650
1633 1651 @classmethod
1634 1652 def normalize_repo_name(cls, repo_name):
1635 1653 """
1636 1654 Normalizes os specific repo_name to the format internally stored inside
1637 1655 database using URL_SEP
1638 1656
1639 1657 :param cls:
1640 1658 :param repo_name:
1641 1659 """
1642 1660 return cls.NAME_SEP.join(repo_name.split(os.sep))
1643 1661
1644 1662 @classmethod
1645 1663 def get_by_repo_name(cls, repo_name, cache=False, identity_cache=False):
1646 1664 session = Session()
1647 1665 q = session.query(cls).filter(cls.repo_name == repo_name)
1648 1666
1649 1667 if cache:
1650 1668 if identity_cache:
1651 1669 val = cls.identity_cache(session, 'repo_name', repo_name)
1652 1670 if val:
1653 1671 return val
1654 1672 else:
1655 1673 cache_key = "get_repo_by_name_%s" % _hash_key(repo_name)
1656 1674 q = q.options(
1657 1675 FromCache("sql_cache_short", cache_key))
1658 1676
1659 1677 return q.scalar()
1660 1678
1661 1679 @classmethod
1662 1680 def get_by_full_path(cls, repo_full_path):
1663 1681 repo_name = repo_full_path.split(cls.base_path(), 1)[-1]
1664 1682 repo_name = cls.normalize_repo_name(repo_name)
1665 1683 return cls.get_by_repo_name(repo_name.strip(URL_SEP))
1666 1684
1667 1685 @classmethod
1668 1686 def get_repo_forks(cls, repo_id):
1669 1687 return cls.query().filter(Repository.fork_id == repo_id)
1670 1688
1671 1689 @classmethod
1672 1690 def base_path(cls):
1673 1691 """
1674 1692 Returns base path when all repos are stored
1675 1693
1676 1694 :param cls:
1677 1695 """
1678 1696 q = Session().query(RhodeCodeUi)\
1679 1697 .filter(RhodeCodeUi.ui_key == cls.NAME_SEP)
1680 1698 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1681 1699 return q.one().ui_value
1682 1700
1683 1701 @classmethod
1684 1702 def is_valid(cls, repo_name):
1685 1703 """
1686 1704 returns True if given repo name is a valid filesystem repository
1687 1705
1688 1706 :param cls:
1689 1707 :param repo_name:
1690 1708 """
1691 1709 from rhodecode.lib.utils import is_valid_repo
1692 1710
1693 1711 return is_valid_repo(repo_name, cls.base_path())
1694 1712
1695 1713 @classmethod
1696 1714 def get_all_repos(cls, user_id=Optional(None), group_id=Optional(None),
1697 1715 case_insensitive=True):
1698 1716 q = Repository.query()
1699 1717
1700 1718 if not isinstance(user_id, Optional):
1701 1719 q = q.filter(Repository.user_id == user_id)
1702 1720
1703 1721 if not isinstance(group_id, Optional):
1704 1722 q = q.filter(Repository.group_id == group_id)
1705 1723
1706 1724 if case_insensitive:
1707 1725 q = q.order_by(func.lower(Repository.repo_name))
1708 1726 else:
1709 1727 q = q.order_by(Repository.repo_name)
1710 1728 return q.all()
1711 1729
1712 1730 @property
1713 1731 def forks(self):
1714 1732 """
1715 1733 Return forks of this repo
1716 1734 """
1717 1735 return Repository.get_repo_forks(self.repo_id)
1718 1736
1719 1737 @property
1720 1738 def parent(self):
1721 1739 """
1722 1740 Returns fork parent
1723 1741 """
1724 1742 return self.fork
1725 1743
1726 1744 @property
1727 1745 def just_name(self):
1728 1746 return self.repo_name.split(self.NAME_SEP)[-1]
1729 1747
1730 1748 @property
1731 1749 def groups_with_parents(self):
1732 1750 groups = []
1733 1751 if self.group is None:
1734 1752 return groups
1735 1753
1736 1754 cur_gr = self.group
1737 1755 groups.insert(0, cur_gr)
1738 1756 while 1:
1739 1757 gr = getattr(cur_gr, 'parent_group', None)
1740 1758 cur_gr = cur_gr.parent_group
1741 1759 if gr is None:
1742 1760 break
1743 1761 groups.insert(0, gr)
1744 1762
1745 1763 return groups
1746 1764
1747 1765 @property
1748 1766 def groups_and_repo(self):
1749 1767 return self.groups_with_parents, self
1750 1768
1751 1769 @LazyProperty
1752 1770 def repo_path(self):
1753 1771 """
1754 1772 Returns base full path for that repository means where it actually
1755 1773 exists on a filesystem
1756 1774 """
1757 1775 q = Session().query(RhodeCodeUi).filter(
1758 1776 RhodeCodeUi.ui_key == self.NAME_SEP)
1759 1777 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
1760 1778 return q.one().ui_value
1761 1779
1762 1780 @property
1763 1781 def repo_full_path(self):
1764 1782 p = [self.repo_path]
1765 1783 # we need to split the name by / since this is how we store the
1766 1784 # names in the database, but that eventually needs to be converted
1767 1785 # into a valid system path
1768 1786 p += self.repo_name.split(self.NAME_SEP)
1769 1787 return os.path.join(*map(safe_unicode, p))
1770 1788
1771 1789 @property
1772 1790 def cache_keys(self):
1773 1791 """
1774 1792 Returns associated cache keys for that repo
1775 1793 """
1776 1794 return CacheKey.query()\
1777 1795 .filter(CacheKey.cache_args == self.repo_name)\
1778 1796 .order_by(CacheKey.cache_key)\
1779 1797 .all()
1780 1798
1781 1799 def get_new_name(self, repo_name):
1782 1800 """
1783 1801 returns new full repository name based on assigned group and new new
1784 1802
1785 1803 :param group_name:
1786 1804 """
1787 1805 path_prefix = self.group.full_path_splitted if self.group else []
1788 1806 return self.NAME_SEP.join(path_prefix + [repo_name])
1789 1807
1790 1808 @property
1791 1809 def _config(self):
1792 1810 """
1793 1811 Returns db based config object.
1794 1812 """
1795 1813 from rhodecode.lib.utils import make_db_config
1796 1814 return make_db_config(clear_session=False, repo=self)
1797 1815
1798 1816 def permissions(self, with_admins=True, with_owner=True):
1799 1817 q = UserRepoToPerm.query().filter(UserRepoToPerm.repository == self)
1800 1818 q = q.options(joinedload(UserRepoToPerm.repository),
1801 1819 joinedload(UserRepoToPerm.user),
1802 1820 joinedload(UserRepoToPerm.permission),)
1803 1821
1804 1822 # get owners and admins and permissions. We do a trick of re-writing
1805 1823 # objects from sqlalchemy to named-tuples due to sqlalchemy session
1806 1824 # has a global reference and changing one object propagates to all
1807 1825 # others. This means if admin is also an owner admin_row that change
1808 1826 # would propagate to both objects
1809 1827 perm_rows = []
1810 1828 for _usr in q.all():
1811 1829 usr = AttributeDict(_usr.user.get_dict())
1812 1830 usr.permission = _usr.permission.permission_name
1813 1831 perm_rows.append(usr)
1814 1832
1815 1833 # filter the perm rows by 'default' first and then sort them by
1816 1834 # admin,write,read,none permissions sorted again alphabetically in
1817 1835 # each group
1818 1836 perm_rows = sorted(perm_rows, key=display_sort)
1819 1837
1820 1838 _admin_perm = 'repository.admin'
1821 1839 owner_row = []
1822 1840 if with_owner:
1823 1841 usr = AttributeDict(self.user.get_dict())
1824 1842 usr.owner_row = True
1825 1843 usr.permission = _admin_perm
1826 1844 owner_row.append(usr)
1827 1845
1828 1846 super_admin_rows = []
1829 1847 if with_admins:
1830 1848 for usr in User.get_all_super_admins():
1831 1849 # if this admin is also owner, don't double the record
1832 1850 if usr.user_id == owner_row[0].user_id:
1833 1851 owner_row[0].admin_row = True
1834 1852 else:
1835 1853 usr = AttributeDict(usr.get_dict())
1836 1854 usr.admin_row = True
1837 1855 usr.permission = _admin_perm
1838 1856 super_admin_rows.append(usr)
1839 1857
1840 1858 return super_admin_rows + owner_row + perm_rows
1841 1859
1842 1860 def permission_user_groups(self):
1843 1861 q = UserGroupRepoToPerm.query().filter(
1844 1862 UserGroupRepoToPerm.repository == self)
1845 1863 q = q.options(joinedload(UserGroupRepoToPerm.repository),
1846 1864 joinedload(UserGroupRepoToPerm.users_group),
1847 1865 joinedload(UserGroupRepoToPerm.permission),)
1848 1866
1849 1867 perm_rows = []
1850 1868 for _user_group in q.all():
1851 1869 usr = AttributeDict(_user_group.users_group.get_dict())
1852 1870 usr.permission = _user_group.permission.permission_name
1853 1871 perm_rows.append(usr)
1854 1872
1855 1873 return perm_rows
1856 1874
1857 1875 def get_api_data(self, include_secrets=False):
1858 1876 """
1859 1877 Common function for generating repo api data
1860 1878
1861 1879 :param include_secrets: See :meth:`User.get_api_data`.
1862 1880
1863 1881 """
1864 1882 # TODO: mikhail: Here there is an anti-pattern, we probably need to
1865 1883 # move this methods on models level.
1866 1884 from rhodecode.model.settings import SettingsModel
1867 1885 from rhodecode.model.repo import RepoModel
1868 1886
1869 1887 repo = self
1870 1888 _user_id, _time, _reason = self.locked
1871 1889
1872 1890 data = {
1873 1891 'repo_id': repo.repo_id,
1874 1892 'repo_name': repo.repo_name,
1875 1893 'repo_type': repo.repo_type,
1876 1894 'clone_uri': repo.clone_uri or '',
1877 1895 'url': RepoModel().get_url(self),
1878 1896 'private': repo.private,
1879 1897 'created_on': repo.created_on,
1880 1898 'description': repo.description_safe,
1881 1899 'landing_rev': repo.landing_rev,
1882 1900 'owner': repo.user.username,
1883 1901 'fork_of': repo.fork.repo_name if repo.fork else None,
1884 1902 'fork_of_id': repo.fork.repo_id if repo.fork else None,
1885 1903 'enable_statistics': repo.enable_statistics,
1886 1904 'enable_locking': repo.enable_locking,
1887 1905 'enable_downloads': repo.enable_downloads,
1888 1906 'last_changeset': repo.changeset_cache,
1889 1907 'locked_by': User.get(_user_id).get_api_data(
1890 1908 include_secrets=include_secrets) if _user_id else None,
1891 1909 'locked_date': time_to_datetime(_time) if _time else None,
1892 1910 'lock_reason': _reason if _reason else None,
1893 1911 }
1894 1912
1895 1913 # TODO: mikhail: should be per-repo settings here
1896 1914 rc_config = SettingsModel().get_all_settings()
1897 1915 repository_fields = str2bool(
1898 1916 rc_config.get('rhodecode_repository_fields'))
1899 1917 if repository_fields:
1900 1918 for f in self.extra_fields:
1901 1919 data[f.field_key_prefixed] = f.field_value
1902 1920
1903 1921 return data
1904 1922
1905 1923 @classmethod
1906 1924 def lock(cls, repo, user_id, lock_time=None, lock_reason=None):
1907 1925 if not lock_time:
1908 1926 lock_time = time.time()
1909 1927 if not lock_reason:
1910 1928 lock_reason = cls.LOCK_AUTOMATIC
1911 1929 repo.locked = [user_id, lock_time, lock_reason]
1912 1930 Session().add(repo)
1913 1931 Session().commit()
1914 1932
1915 1933 @classmethod
1916 1934 def unlock(cls, repo):
1917 1935 repo.locked = None
1918 1936 Session().add(repo)
1919 1937 Session().commit()
1920 1938
1921 1939 @classmethod
1922 1940 def getlock(cls, repo):
1923 1941 return repo.locked
1924 1942
1925 1943 def is_user_lock(self, user_id):
1926 1944 if self.lock[0]:
1927 1945 lock_user_id = safe_int(self.lock[0])
1928 1946 user_id = safe_int(user_id)
1929 1947 # both are ints, and they are equal
1930 1948 return all([lock_user_id, user_id]) and lock_user_id == user_id
1931 1949
1932 1950 return False
1933 1951
1934 1952 def get_locking_state(self, action, user_id, only_when_enabled=True):
1935 1953 """
1936 1954 Checks locking on this repository, if locking is enabled and lock is
1937 1955 present returns a tuple of make_lock, locked, locked_by.
1938 1956 make_lock can have 3 states None (do nothing) True, make lock
1939 1957 False release lock, This value is later propagated to hooks, which
1940 1958 do the locking. Think about this as signals passed to hooks what to do.
1941 1959
1942 1960 """
1943 1961 # TODO: johbo: This is part of the business logic and should be moved
1944 1962 # into the RepositoryModel.
1945 1963
1946 1964 if action not in ('push', 'pull'):
1947 1965 raise ValueError("Invalid action value: %s" % repr(action))
1948 1966
1949 1967 # defines if locked error should be thrown to user
1950 1968 currently_locked = False
1951 1969 # defines if new lock should be made, tri-state
1952 1970 make_lock = None
1953 1971 repo = self
1954 1972 user = User.get(user_id)
1955 1973
1956 1974 lock_info = repo.locked
1957 1975
1958 1976 if repo and (repo.enable_locking or not only_when_enabled):
1959 1977 if action == 'push':
1960 1978 # check if it's already locked !, if it is compare users
1961 1979 locked_by_user_id = lock_info[0]
1962 1980 if user.user_id == locked_by_user_id:
1963 1981 log.debug(
1964 1982 'Got `push` action from user %s, now unlocking', user)
1965 1983 # unlock if we have push from user who locked
1966 1984 make_lock = False
1967 1985 else:
1968 1986 # we're not the same user who locked, ban with
1969 1987 # code defined in settings (default is 423 HTTP Locked) !
1970 1988 log.debug('Repo %s is currently locked by %s', repo, user)
1971 1989 currently_locked = True
1972 1990 elif action == 'pull':
1973 1991 # [0] user [1] date
1974 1992 if lock_info[0] and lock_info[1]:
1975 1993 log.debug('Repo %s is currently locked by %s', repo, user)
1976 1994 currently_locked = True
1977 1995 else:
1978 1996 log.debug('Setting lock on repo %s by %s', repo, user)
1979 1997 make_lock = True
1980 1998
1981 1999 else:
1982 2000 log.debug('Repository %s do not have locking enabled', repo)
1983 2001
1984 2002 log.debug('FINAL locking values make_lock:%s,locked:%s,locked_by:%s',
1985 2003 make_lock, currently_locked, lock_info)
1986 2004
1987 2005 from rhodecode.lib.auth import HasRepoPermissionAny
1988 2006 perm_check = HasRepoPermissionAny('repository.write', 'repository.admin')
1989 2007 if make_lock and not perm_check(repo_name=repo.repo_name, user=user):
1990 2008 # if we don't have at least write permission we cannot make a lock
1991 2009 log.debug('lock state reset back to FALSE due to lack '
1992 2010 'of at least read permission')
1993 2011 make_lock = False
1994 2012
1995 2013 return make_lock, currently_locked, lock_info
1996 2014
1997 2015 @property
1998 2016 def last_db_change(self):
1999 2017 return self.updated_on
2000 2018
2001 2019 @property
2002 2020 def clone_uri_hidden(self):
2003 2021 clone_uri = self.clone_uri
2004 2022 if clone_uri:
2005 2023 import urlobject
2006 2024 url_obj = urlobject.URLObject(cleaned_uri(clone_uri))
2007 2025 if url_obj.password:
2008 2026 clone_uri = url_obj.with_password('*****')
2009 2027 return clone_uri
2010 2028
2011 2029 def clone_url(self, **override):
2012 2030 from rhodecode.model.settings import SettingsModel
2013 2031
2014 2032 uri_tmpl = None
2015 2033 if 'with_id' in override:
2016 2034 uri_tmpl = self.DEFAULT_CLONE_URI_ID
2017 2035 del override['with_id']
2018 2036
2019 2037 if 'uri_tmpl' in override:
2020 2038 uri_tmpl = override['uri_tmpl']
2021 2039 del override['uri_tmpl']
2022 2040
2023 2041 # we didn't override our tmpl from **overrides
2024 2042 if not uri_tmpl:
2025 2043 rc_config = SettingsModel().get_all_settings(cache=True)
2026 2044 uri_tmpl = rc_config.get(
2027 2045 'rhodecode_clone_uri_tmpl') or self.DEFAULT_CLONE_URI
2028 2046
2029 2047 request = get_current_request()
2030 2048 return get_clone_url(request=request,
2031 2049 uri_tmpl=uri_tmpl,
2032 2050 repo_name=self.repo_name,
2033 2051 repo_id=self.repo_id, **override)
2034 2052
2035 2053 def set_state(self, state):
2036 2054 self.repo_state = state
2037 2055 Session().add(self)
2038 2056 #==========================================================================
2039 2057 # SCM PROPERTIES
2040 2058 #==========================================================================
2041 2059
2042 2060 def get_commit(self, commit_id=None, commit_idx=None, pre_load=None):
2043 2061 return get_commit_safe(
2044 2062 self.scm_instance(), commit_id, commit_idx, pre_load=pre_load)
2045 2063
2046 2064 def get_changeset(self, rev=None, pre_load=None):
2047 2065 warnings.warn("Use get_commit", DeprecationWarning)
2048 2066 commit_id = None
2049 2067 commit_idx = None
2050 2068 if isinstance(rev, basestring):
2051 2069 commit_id = rev
2052 2070 else:
2053 2071 commit_idx = rev
2054 2072 return self.get_commit(commit_id=commit_id, commit_idx=commit_idx,
2055 2073 pre_load=pre_load)
2056 2074
2057 2075 def get_landing_commit(self):
2058 2076 """
2059 2077 Returns landing commit, or if that doesn't exist returns the tip
2060 2078 """
2061 2079 _rev_type, _rev = self.landing_rev
2062 2080 commit = self.get_commit(_rev)
2063 2081 if isinstance(commit, EmptyCommit):
2064 2082 return self.get_commit()
2065 2083 return commit
2066 2084
2067 2085 def update_commit_cache(self, cs_cache=None, config=None):
2068 2086 """
2069 2087 Update cache of last changeset for repository, keys should be::
2070 2088
2071 2089 short_id
2072 2090 raw_id
2073 2091 revision
2074 2092 parents
2075 2093 message
2076 2094 date
2077 2095 author
2078 2096
2079 2097 :param cs_cache:
2080 2098 """
2081 2099 from rhodecode.lib.vcs.backends.base import BaseChangeset
2082 2100 if cs_cache is None:
2083 2101 # use no-cache version here
2084 2102 scm_repo = self.scm_instance(cache=False, config=config)
2085 2103 if scm_repo:
2086 2104 cs_cache = scm_repo.get_commit(
2087 2105 pre_load=["author", "date", "message", "parents"])
2088 2106 else:
2089 2107 cs_cache = EmptyCommit()
2090 2108
2091 2109 if isinstance(cs_cache, BaseChangeset):
2092 2110 cs_cache = cs_cache.__json__()
2093 2111
2094 2112 def is_outdated(new_cs_cache):
2095 2113 if (new_cs_cache['raw_id'] != self.changeset_cache['raw_id'] or
2096 2114 new_cs_cache['revision'] != self.changeset_cache['revision']):
2097 2115 return True
2098 2116 return False
2099 2117
2100 2118 # check if we have maybe already latest cached revision
2101 2119 if is_outdated(cs_cache) or not self.changeset_cache:
2102 2120 _default = datetime.datetime.fromtimestamp(0)
2103 2121 last_change = cs_cache.get('date') or _default
2104 2122 log.debug('updated repo %s with new cs cache %s',
2105 2123 self.repo_name, cs_cache)
2106 2124 self.updated_on = last_change
2107 2125 self.changeset_cache = cs_cache
2108 2126 Session().add(self)
2109 2127 Session().commit()
2110 2128 else:
2111 2129 log.debug('Skipping update_commit_cache for repo:`%s` '
2112 2130 'commit already with latest changes', self.repo_name)
2113 2131
2114 2132 @property
2115 2133 def tip(self):
2116 2134 return self.get_commit('tip')
2117 2135
2118 2136 @property
2119 2137 def author(self):
2120 2138 return self.tip.author
2121 2139
2122 2140 @property
2123 2141 def last_change(self):
2124 2142 return self.scm_instance().last_change
2125 2143
2126 2144 def get_comments(self, revisions=None):
2127 2145 """
2128 2146 Returns comments for this repository grouped by revisions
2129 2147
2130 2148 :param revisions: filter query by revisions only
2131 2149 """
2132 2150 cmts = ChangesetComment.query()\
2133 2151 .filter(ChangesetComment.repo == self)
2134 2152 if revisions:
2135 2153 cmts = cmts.filter(ChangesetComment.revision.in_(revisions))
2136 2154 grouped = collections.defaultdict(list)
2137 2155 for cmt in cmts.all():
2138 2156 grouped[cmt.revision].append(cmt)
2139 2157 return grouped
2140 2158
2141 2159 def statuses(self, revisions=None):
2142 2160 """
2143 2161 Returns statuses for this repository
2144 2162
2145 2163 :param revisions: list of revisions to get statuses for
2146 2164 """
2147 2165 statuses = ChangesetStatus.query()\
2148 2166 .filter(ChangesetStatus.repo == self)\
2149 2167 .filter(ChangesetStatus.version == 0)
2150 2168
2151 2169 if revisions:
2152 2170 # Try doing the filtering in chunks to avoid hitting limits
2153 2171 size = 500
2154 2172 status_results = []
2155 2173 for chunk in xrange(0, len(revisions), size):
2156 2174 status_results += statuses.filter(
2157 2175 ChangesetStatus.revision.in_(
2158 2176 revisions[chunk: chunk+size])
2159 2177 ).all()
2160 2178 else:
2161 2179 status_results = statuses.all()
2162 2180
2163 2181 grouped = {}
2164 2182
2165 2183 # maybe we have open new pullrequest without a status?
2166 2184 stat = ChangesetStatus.STATUS_UNDER_REVIEW
2167 2185 status_lbl = ChangesetStatus.get_status_lbl(stat)
2168 2186 for pr in PullRequest.query().filter(PullRequest.source_repo == self).all():
2169 2187 for rev in pr.revisions:
2170 2188 pr_id = pr.pull_request_id
2171 2189 pr_repo = pr.target_repo.repo_name
2172 2190 grouped[rev] = [stat, status_lbl, pr_id, pr_repo]
2173 2191
2174 2192 for stat in status_results:
2175 2193 pr_id = pr_repo = None
2176 2194 if stat.pull_request:
2177 2195 pr_id = stat.pull_request.pull_request_id
2178 2196 pr_repo = stat.pull_request.target_repo.repo_name
2179 2197 grouped[stat.revision] = [str(stat.status), stat.status_lbl,
2180 2198 pr_id, pr_repo]
2181 2199 return grouped
2182 2200
2183 2201 # ==========================================================================
2184 2202 # SCM CACHE INSTANCE
2185 2203 # ==========================================================================
2186 2204
2187 2205 def scm_instance(self, **kwargs):
2188 2206 import rhodecode
2189 2207
2190 2208 # Passing a config will not hit the cache currently only used
2191 2209 # for repo2dbmapper
2192 2210 config = kwargs.pop('config', None)
2193 2211 cache = kwargs.pop('cache', None)
2194 2212 full_cache = str2bool(rhodecode.CONFIG.get('vcs_full_cache'))
2195 2213 # if cache is NOT defined use default global, else we have a full
2196 2214 # control over cache behaviour
2197 2215 if cache is None and full_cache and not config:
2198 2216 return self._get_instance_cached()
2199 2217 return self._get_instance(cache=bool(cache), config=config)
2200 2218
2201 2219 def _get_instance_cached(self):
2202 2220 @cache_region('long_term')
2203 2221 def _get_repo(cache_key):
2204 2222 return self._get_instance()
2205 2223
2206 2224 invalidator_context = CacheKey.repo_context_cache(
2207 2225 _get_repo, self.repo_name, None, thread_scoped=True)
2208 2226
2209 2227 with invalidator_context as context:
2210 2228 context.invalidate()
2211 2229 repo = context.compute()
2212 2230
2213 2231 return repo
2214 2232
2215 2233 def _get_instance(self, cache=True, config=None):
2216 2234 config = config or self._config
2217 2235 custom_wire = {
2218 2236 'cache': cache # controls the vcs.remote cache
2219 2237 }
2220 2238 repo = get_vcs_instance(
2221 2239 repo_path=safe_str(self.repo_full_path),
2222 2240 config=config,
2223 2241 with_wire=custom_wire,
2224 2242 create=False,
2225 2243 _vcs_alias=self.repo_type)
2226 2244
2227 2245 return repo
2228 2246
2229 2247 def __json__(self):
2230 2248 return {'landing_rev': self.landing_rev}
2231 2249
2232 2250 def get_dict(self):
2233 2251
2234 2252 # Since we transformed `repo_name` to a hybrid property, we need to
2235 2253 # keep compatibility with the code which uses `repo_name` field.
2236 2254
2237 2255 result = super(Repository, self).get_dict()
2238 2256 result['repo_name'] = result.pop('_repo_name', None)
2239 2257 return result
2240 2258
2241 2259
2242 2260 class RepoGroup(Base, BaseModel):
2243 2261 __tablename__ = 'groups'
2244 2262 __table_args__ = (
2245 2263 UniqueConstraint('group_name', 'group_parent_id'),
2246 2264 CheckConstraint('group_id != group_parent_id'),
2247 2265 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2248 2266 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2249 2267 )
2250 2268 __mapper_args__ = {'order_by': 'group_name'}
2251 2269
2252 2270 CHOICES_SEPARATOR = '/' # used to generate select2 choices for nested groups
2253 2271
2254 2272 group_id = Column("group_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2255 2273 group_name = Column("group_name", String(255), nullable=False, unique=True, default=None)
2256 2274 group_parent_id = Column("group_parent_id", Integer(), ForeignKey('groups.group_id'), nullable=True, unique=None, default=None)
2257 2275 group_description = Column("group_description", String(10000), nullable=True, unique=None, default=None)
2258 2276 enable_locking = Column("enable_locking", Boolean(), nullable=False, unique=None, default=False)
2259 2277 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
2260 2278 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
2261 2279 updated_on = Column('updated_on', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2262 2280 personal = Column('personal', Boolean(), nullable=True, unique=None, default=None)
2263 2281
2264 2282 repo_group_to_perm = relationship('UserRepoGroupToPerm', cascade='all', order_by='UserRepoGroupToPerm.group_to_perm_id')
2265 2283 users_group_to_perm = relationship('UserGroupRepoGroupToPerm', cascade='all')
2266 2284 parent_group = relationship('RepoGroup', remote_side=group_id)
2267 2285 user = relationship('User')
2268 2286 integrations = relationship('Integration',
2269 2287 cascade="all, delete, delete-orphan")
2270 2288
2271 2289 def __init__(self, group_name='', parent_group=None):
2272 2290 self.group_name = group_name
2273 2291 self.parent_group = parent_group
2274 2292
2275 2293 def __unicode__(self):
2276 2294 return u"<%s('id:%s:%s')>" % (
2277 2295 self.__class__.__name__, self.group_id, self.group_name)
2278 2296
2279 2297 @hybrid_property
2280 2298 def description_safe(self):
2281 2299 from rhodecode.lib import helpers as h
2282 2300 return h.escape(self.group_description)
2283 2301
2284 2302 @classmethod
2285 2303 def _generate_choice(cls, repo_group):
2286 2304 from webhelpers.html import literal as _literal
2287 2305 _name = lambda k: _literal(cls.CHOICES_SEPARATOR.join(k))
2288 2306 return repo_group.group_id, _name(repo_group.full_path_splitted)
2289 2307
2290 2308 @classmethod
2291 2309 def groups_choices(cls, groups=None, show_empty_group=True):
2292 2310 if not groups:
2293 2311 groups = cls.query().all()
2294 2312
2295 2313 repo_groups = []
2296 2314 if show_empty_group:
2297 2315 repo_groups = [(-1, u'-- %s --' % _('No parent'))]
2298 2316
2299 2317 repo_groups.extend([cls._generate_choice(x) for x in groups])
2300 2318
2301 2319 repo_groups = sorted(
2302 2320 repo_groups, key=lambda t: t[1].split(cls.CHOICES_SEPARATOR)[0])
2303 2321 return repo_groups
2304 2322
2305 2323 @classmethod
2306 2324 def url_sep(cls):
2307 2325 return URL_SEP
2308 2326
2309 2327 @classmethod
2310 2328 def get_by_group_name(cls, group_name, cache=False, case_insensitive=False):
2311 2329 if case_insensitive:
2312 2330 gr = cls.query().filter(func.lower(cls.group_name)
2313 2331 == func.lower(group_name))
2314 2332 else:
2315 2333 gr = cls.query().filter(cls.group_name == group_name)
2316 2334 if cache:
2317 2335 name_key = _hash_key(group_name)
2318 2336 gr = gr.options(
2319 2337 FromCache("sql_cache_short", "get_group_%s" % name_key))
2320 2338 return gr.scalar()
2321 2339
2322 2340 @classmethod
2323 2341 def get_user_personal_repo_group(cls, user_id):
2324 2342 user = User.get(user_id)
2325 2343 if user.username == User.DEFAULT_USER:
2326 2344 return None
2327 2345
2328 2346 return cls.query()\
2329 2347 .filter(cls.personal == true()) \
2330 2348 .filter(cls.user == user).scalar()
2331 2349
2332 2350 @classmethod
2333 2351 def get_all_repo_groups(cls, user_id=Optional(None), group_id=Optional(None),
2334 2352 case_insensitive=True):
2335 2353 q = RepoGroup.query()
2336 2354
2337 2355 if not isinstance(user_id, Optional):
2338 2356 q = q.filter(RepoGroup.user_id == user_id)
2339 2357
2340 2358 if not isinstance(group_id, Optional):
2341 2359 q = q.filter(RepoGroup.group_parent_id == group_id)
2342 2360
2343 2361 if case_insensitive:
2344 2362 q = q.order_by(func.lower(RepoGroup.group_name))
2345 2363 else:
2346 2364 q = q.order_by(RepoGroup.group_name)
2347 2365 return q.all()
2348 2366
2349 2367 @property
2350 2368 def parents(self):
2351 2369 parents_recursion_limit = 10
2352 2370 groups = []
2353 2371 if self.parent_group is None:
2354 2372 return groups
2355 2373 cur_gr = self.parent_group
2356 2374 groups.insert(0, cur_gr)
2357 2375 cnt = 0
2358 2376 while 1:
2359 2377 cnt += 1
2360 2378 gr = getattr(cur_gr, 'parent_group', None)
2361 2379 cur_gr = cur_gr.parent_group
2362 2380 if gr is None:
2363 2381 break
2364 2382 if cnt == parents_recursion_limit:
2365 2383 # this will prevent accidental infinit loops
2366 2384 log.error(('more than %s parents found for group %s, stopping '
2367 2385 'recursive parent fetching' % (parents_recursion_limit, self)))
2368 2386 break
2369 2387
2370 2388 groups.insert(0, gr)
2371 2389 return groups
2372 2390
2373 2391 @property
2374 2392 def last_db_change(self):
2375 2393 return self.updated_on
2376 2394
2377 2395 @property
2378 2396 def children(self):
2379 2397 return RepoGroup.query().filter(RepoGroup.parent_group == self)
2380 2398
2381 2399 @property
2382 2400 def name(self):
2383 2401 return self.group_name.split(RepoGroup.url_sep())[-1]
2384 2402
2385 2403 @property
2386 2404 def full_path(self):
2387 2405 return self.group_name
2388 2406
2389 2407 @property
2390 2408 def full_path_splitted(self):
2391 2409 return self.group_name.split(RepoGroup.url_sep())
2392 2410
2393 2411 @property
2394 2412 def repositories(self):
2395 2413 return Repository.query()\
2396 2414 .filter(Repository.group == self)\
2397 2415 .order_by(Repository.repo_name)
2398 2416
2399 2417 @property
2400 2418 def repositories_recursive_count(self):
2401 2419 cnt = self.repositories.count()
2402 2420
2403 2421 def children_count(group):
2404 2422 cnt = 0
2405 2423 for child in group.children:
2406 2424 cnt += child.repositories.count()
2407 2425 cnt += children_count(child)
2408 2426 return cnt
2409 2427
2410 2428 return cnt + children_count(self)
2411 2429
2412 2430 def _recursive_objects(self, include_repos=True):
2413 2431 all_ = []
2414 2432
2415 2433 def _get_members(root_gr):
2416 2434 if include_repos:
2417 2435 for r in root_gr.repositories:
2418 2436 all_.append(r)
2419 2437 childs = root_gr.children.all()
2420 2438 if childs:
2421 2439 for gr in childs:
2422 2440 all_.append(gr)
2423 2441 _get_members(gr)
2424 2442
2425 2443 _get_members(self)
2426 2444 return [self] + all_
2427 2445
2428 2446 def recursive_groups_and_repos(self):
2429 2447 """
2430 2448 Recursive return all groups, with repositories in those groups
2431 2449 """
2432 2450 return self._recursive_objects()
2433 2451
2434 2452 def recursive_groups(self):
2435 2453 """
2436 2454 Returns all children groups for this group including children of children
2437 2455 """
2438 2456 return self._recursive_objects(include_repos=False)
2439 2457
2440 2458 def get_new_name(self, group_name):
2441 2459 """
2442 2460 returns new full group name based on parent and new name
2443 2461
2444 2462 :param group_name:
2445 2463 """
2446 2464 path_prefix = (self.parent_group.full_path_splitted if
2447 2465 self.parent_group else [])
2448 2466 return RepoGroup.url_sep().join(path_prefix + [group_name])
2449 2467
2450 2468 def permissions(self, with_admins=True, with_owner=True):
2451 2469 q = UserRepoGroupToPerm.query().filter(UserRepoGroupToPerm.group == self)
2452 2470 q = q.options(joinedload(UserRepoGroupToPerm.group),
2453 2471 joinedload(UserRepoGroupToPerm.user),
2454 2472 joinedload(UserRepoGroupToPerm.permission),)
2455 2473
2456 2474 # get owners and admins and permissions. We do a trick of re-writing
2457 2475 # objects from sqlalchemy to named-tuples due to sqlalchemy session
2458 2476 # has a global reference and changing one object propagates to all
2459 2477 # others. This means if admin is also an owner admin_row that change
2460 2478 # would propagate to both objects
2461 2479 perm_rows = []
2462 2480 for _usr in q.all():
2463 2481 usr = AttributeDict(_usr.user.get_dict())
2464 2482 usr.permission = _usr.permission.permission_name
2465 2483 perm_rows.append(usr)
2466 2484
2467 2485 # filter the perm rows by 'default' first and then sort them by
2468 2486 # admin,write,read,none permissions sorted again alphabetically in
2469 2487 # each group
2470 2488 perm_rows = sorted(perm_rows, key=display_sort)
2471 2489
2472 2490 _admin_perm = 'group.admin'
2473 2491 owner_row = []
2474 2492 if with_owner:
2475 2493 usr = AttributeDict(self.user.get_dict())
2476 2494 usr.owner_row = True
2477 2495 usr.permission = _admin_perm
2478 2496 owner_row.append(usr)
2479 2497
2480 2498 super_admin_rows = []
2481 2499 if with_admins:
2482 2500 for usr in User.get_all_super_admins():
2483 2501 # if this admin is also owner, don't double the record
2484 2502 if usr.user_id == owner_row[0].user_id:
2485 2503 owner_row[0].admin_row = True
2486 2504 else:
2487 2505 usr = AttributeDict(usr.get_dict())
2488 2506 usr.admin_row = True
2489 2507 usr.permission = _admin_perm
2490 2508 super_admin_rows.append(usr)
2491 2509
2492 2510 return super_admin_rows + owner_row + perm_rows
2493 2511
2494 2512 def permission_user_groups(self):
2495 2513 q = UserGroupRepoGroupToPerm.query().filter(UserGroupRepoGroupToPerm.group == self)
2496 2514 q = q.options(joinedload(UserGroupRepoGroupToPerm.group),
2497 2515 joinedload(UserGroupRepoGroupToPerm.users_group),
2498 2516 joinedload(UserGroupRepoGroupToPerm.permission),)
2499 2517
2500 2518 perm_rows = []
2501 2519 for _user_group in q.all():
2502 2520 usr = AttributeDict(_user_group.users_group.get_dict())
2503 2521 usr.permission = _user_group.permission.permission_name
2504 2522 perm_rows.append(usr)
2505 2523
2506 2524 return perm_rows
2507 2525
2508 2526 def get_api_data(self):
2509 2527 """
2510 2528 Common function for generating api data
2511 2529
2512 2530 """
2513 2531 group = self
2514 2532 data = {
2515 2533 'group_id': group.group_id,
2516 2534 'group_name': group.group_name,
2517 2535 'group_description': group.description_safe,
2518 2536 'parent_group': group.parent_group.group_name if group.parent_group else None,
2519 2537 'repositories': [x.repo_name for x in group.repositories],
2520 2538 'owner': group.user.username,
2521 2539 }
2522 2540 return data
2523 2541
2524 2542
2525 2543 class Permission(Base, BaseModel):
2526 2544 __tablename__ = 'permissions'
2527 2545 __table_args__ = (
2528 2546 Index('p_perm_name_idx', 'permission_name'),
2529 2547 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2530 2548 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
2531 2549 )
2532 2550 PERMS = [
2533 2551 ('hg.admin', _('RhodeCode Super Administrator')),
2534 2552
2535 2553 ('repository.none', _('Repository no access')),
2536 2554 ('repository.read', _('Repository read access')),
2537 2555 ('repository.write', _('Repository write access')),
2538 2556 ('repository.admin', _('Repository admin access')),
2539 2557
2540 2558 ('group.none', _('Repository group no access')),
2541 2559 ('group.read', _('Repository group read access')),
2542 2560 ('group.write', _('Repository group write access')),
2543 2561 ('group.admin', _('Repository group admin access')),
2544 2562
2545 2563 ('usergroup.none', _('User group no access')),
2546 2564 ('usergroup.read', _('User group read access')),
2547 2565 ('usergroup.write', _('User group write access')),
2548 2566 ('usergroup.admin', _('User group admin access')),
2549 2567
2550 2568 ('hg.repogroup.create.false', _('Repository Group creation disabled')),
2551 2569 ('hg.repogroup.create.true', _('Repository Group creation enabled')),
2552 2570
2553 2571 ('hg.usergroup.create.false', _('User Group creation disabled')),
2554 2572 ('hg.usergroup.create.true', _('User Group creation enabled')),
2555 2573
2556 2574 ('hg.create.none', _('Repository creation disabled')),
2557 2575 ('hg.create.repository', _('Repository creation enabled')),
2558 2576 ('hg.create.write_on_repogroup.true', _('Repository creation enabled with write permission to a repository group')),
2559 2577 ('hg.create.write_on_repogroup.false', _('Repository creation disabled with write permission to a repository group')),
2560 2578
2561 2579 ('hg.fork.none', _('Repository forking disabled')),
2562 2580 ('hg.fork.repository', _('Repository forking enabled')),
2563 2581
2564 2582 ('hg.register.none', _('Registration disabled')),
2565 2583 ('hg.register.manual_activate', _('User Registration with manual account activation')),
2566 2584 ('hg.register.auto_activate', _('User Registration with automatic account activation')),
2567 2585
2568 2586 ('hg.password_reset.enabled', _('Password reset enabled')),
2569 2587 ('hg.password_reset.hidden', _('Password reset hidden')),
2570 2588 ('hg.password_reset.disabled', _('Password reset disabled')),
2571 2589
2572 2590 ('hg.extern_activate.manual', _('Manual activation of external account')),
2573 2591 ('hg.extern_activate.auto', _('Automatic activation of external account')),
2574 2592
2575 2593 ('hg.inherit_default_perms.false', _('Inherit object permissions from default user disabled')),
2576 2594 ('hg.inherit_default_perms.true', _('Inherit object permissions from default user enabled')),
2577 2595 ]
2578 2596
2579 2597 # definition of system default permissions for DEFAULT user
2580 2598 DEFAULT_USER_PERMISSIONS = [
2581 2599 'repository.read',
2582 2600 'group.read',
2583 2601 'usergroup.read',
2584 2602 'hg.create.repository',
2585 2603 'hg.repogroup.create.false',
2586 2604 'hg.usergroup.create.false',
2587 2605 'hg.create.write_on_repogroup.true',
2588 2606 'hg.fork.repository',
2589 2607 'hg.register.manual_activate',
2590 2608 'hg.password_reset.enabled',
2591 2609 'hg.extern_activate.auto',
2592 2610 'hg.inherit_default_perms.true',
2593 2611 ]
2594 2612
2595 2613 # defines which permissions are more important higher the more important
2596 2614 # Weight defines which permissions are more important.
2597 2615 # The higher number the more important.
2598 2616 PERM_WEIGHTS = {
2599 2617 'repository.none': 0,
2600 2618 'repository.read': 1,
2601 2619 'repository.write': 3,
2602 2620 'repository.admin': 4,
2603 2621
2604 2622 'group.none': 0,
2605 2623 'group.read': 1,
2606 2624 'group.write': 3,
2607 2625 'group.admin': 4,
2608 2626
2609 2627 'usergroup.none': 0,
2610 2628 'usergroup.read': 1,
2611 2629 'usergroup.write': 3,
2612 2630 'usergroup.admin': 4,
2613 2631
2614 2632 'hg.repogroup.create.false': 0,
2615 2633 'hg.repogroup.create.true': 1,
2616 2634
2617 2635 'hg.usergroup.create.false': 0,
2618 2636 'hg.usergroup.create.true': 1,
2619 2637
2620 2638 'hg.fork.none': 0,
2621 2639 'hg.fork.repository': 1,
2622 2640 'hg.create.none': 0,
2623 2641 'hg.create.repository': 1
2624 2642 }
2625 2643
2626 2644 permission_id = Column("permission_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2627 2645 permission_name = Column("permission_name", String(255), nullable=True, unique=None, default=None)
2628 2646 permission_longname = Column("permission_longname", String(255), nullable=True, unique=None, default=None)
2629 2647
2630 2648 def __unicode__(self):
2631 2649 return u"<%s('%s:%s')>" % (
2632 2650 self.__class__.__name__, self.permission_id, self.permission_name
2633 2651 )
2634 2652
2635 2653 @classmethod
2636 2654 def get_by_key(cls, key):
2637 2655 return cls.query().filter(cls.permission_name == key).scalar()
2638 2656
2639 2657 @classmethod
2640 2658 def get_default_repo_perms(cls, user_id, repo_id=None):
2641 2659 q = Session().query(UserRepoToPerm, Repository, Permission)\
2642 2660 .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\
2643 2661 .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\
2644 2662 .filter(UserRepoToPerm.user_id == user_id)
2645 2663 if repo_id:
2646 2664 q = q.filter(UserRepoToPerm.repository_id == repo_id)
2647 2665 return q.all()
2648 2666
2649 2667 @classmethod
2650 2668 def get_default_repo_perms_from_user_group(cls, user_id, repo_id=None):
2651 2669 q = Session().query(UserGroupRepoToPerm, Repository, Permission)\
2652 2670 .join(
2653 2671 Permission,
2654 2672 UserGroupRepoToPerm.permission_id == Permission.permission_id)\
2655 2673 .join(
2656 2674 Repository,
2657 2675 UserGroupRepoToPerm.repository_id == Repository.repo_id)\
2658 2676 .join(
2659 2677 UserGroup,
2660 2678 UserGroupRepoToPerm.users_group_id ==
2661 2679 UserGroup.users_group_id)\
2662 2680 .join(
2663 2681 UserGroupMember,
2664 2682 UserGroupRepoToPerm.users_group_id ==
2665 2683 UserGroupMember.users_group_id)\
2666 2684 .filter(
2667 2685 UserGroupMember.user_id == user_id,
2668 2686 UserGroup.users_group_active == true())
2669 2687 if repo_id:
2670 2688 q = q.filter(UserGroupRepoToPerm.repository_id == repo_id)
2671 2689 return q.all()
2672 2690
2673 2691 @classmethod
2674 2692 def get_default_group_perms(cls, user_id, repo_group_id=None):
2675 2693 q = Session().query(UserRepoGroupToPerm, RepoGroup, Permission)\
2676 2694 .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\
2677 2695 .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\
2678 2696 .filter(UserRepoGroupToPerm.user_id == user_id)
2679 2697 if repo_group_id:
2680 2698 q = q.filter(UserRepoGroupToPerm.group_id == repo_group_id)
2681 2699 return q.all()
2682 2700
2683 2701 @classmethod
2684 2702 def get_default_group_perms_from_user_group(
2685 2703 cls, user_id, repo_group_id=None):
2686 2704 q = Session().query(UserGroupRepoGroupToPerm, RepoGroup, Permission)\
2687 2705 .join(
2688 2706 Permission,
2689 2707 UserGroupRepoGroupToPerm.permission_id ==
2690 2708 Permission.permission_id)\
2691 2709 .join(
2692 2710 RepoGroup,
2693 2711 UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)\
2694 2712 .join(
2695 2713 UserGroup,
2696 2714 UserGroupRepoGroupToPerm.users_group_id ==
2697 2715 UserGroup.users_group_id)\
2698 2716 .join(
2699 2717 UserGroupMember,
2700 2718 UserGroupRepoGroupToPerm.users_group_id ==
2701 2719 UserGroupMember.users_group_id)\
2702 2720 .filter(
2703 2721 UserGroupMember.user_id == user_id,
2704 2722 UserGroup.users_group_active == true())
2705 2723 if repo_group_id:
2706 2724 q = q.filter(UserGroupRepoGroupToPerm.group_id == repo_group_id)
2707 2725 return q.all()
2708 2726
2709 2727 @classmethod
2710 2728 def get_default_user_group_perms(cls, user_id, user_group_id=None):
2711 2729 q = Session().query(UserUserGroupToPerm, UserGroup, Permission)\
2712 2730 .join((Permission, UserUserGroupToPerm.permission_id == Permission.permission_id))\
2713 2731 .join((UserGroup, UserUserGroupToPerm.user_group_id == UserGroup.users_group_id))\
2714 2732 .filter(UserUserGroupToPerm.user_id == user_id)
2715 2733 if user_group_id:
2716 2734 q = q.filter(UserUserGroupToPerm.user_group_id == user_group_id)
2717 2735 return q.all()
2718 2736
2719 2737 @classmethod
2720 2738 def get_default_user_group_perms_from_user_group(
2721 2739 cls, user_id, user_group_id=None):
2722 2740 TargetUserGroup = aliased(UserGroup, name='target_user_group')
2723 2741 q = Session().query(UserGroupUserGroupToPerm, UserGroup, Permission)\
2724 2742 .join(
2725 2743 Permission,
2726 2744 UserGroupUserGroupToPerm.permission_id ==
2727 2745 Permission.permission_id)\
2728 2746 .join(
2729 2747 TargetUserGroup,
2730 2748 UserGroupUserGroupToPerm.target_user_group_id ==
2731 2749 TargetUserGroup.users_group_id)\
2732 2750 .join(
2733 2751 UserGroup,
2734 2752 UserGroupUserGroupToPerm.user_group_id ==
2735 2753 UserGroup.users_group_id)\
2736 2754 .join(
2737 2755 UserGroupMember,
2738 2756 UserGroupUserGroupToPerm.user_group_id ==
2739 2757 UserGroupMember.users_group_id)\
2740 2758 .filter(
2741 2759 UserGroupMember.user_id == user_id,
2742 2760 UserGroup.users_group_active == true())
2743 2761 if user_group_id:
2744 2762 q = q.filter(
2745 2763 UserGroupUserGroupToPerm.user_group_id == user_group_id)
2746 2764
2747 2765 return q.all()
2748 2766
2749 2767
2750 2768 class UserRepoToPerm(Base, BaseModel):
2751 2769 __tablename__ = 'repo_to_perm'
2752 2770 __table_args__ = (
2753 2771 UniqueConstraint('user_id', 'repository_id', 'permission_id'),
2754 2772 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2755 2773 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2756 2774 )
2757 2775 repo_to_perm_id = Column("repo_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2758 2776 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2759 2777 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2760 2778 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2761 2779
2762 2780 user = relationship('User')
2763 2781 repository = relationship('Repository')
2764 2782 permission = relationship('Permission')
2765 2783
2766 2784 @classmethod
2767 2785 def create(cls, user, repository, permission):
2768 2786 n = cls()
2769 2787 n.user = user
2770 2788 n.repository = repository
2771 2789 n.permission = permission
2772 2790 Session().add(n)
2773 2791 return n
2774 2792
2775 2793 def __unicode__(self):
2776 2794 return u'<%s => %s >' % (self.user, self.repository)
2777 2795
2778 2796
2779 2797 class UserUserGroupToPerm(Base, BaseModel):
2780 2798 __tablename__ = 'user_user_group_to_perm'
2781 2799 __table_args__ = (
2782 2800 UniqueConstraint('user_id', 'user_group_id', 'permission_id'),
2783 2801 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2784 2802 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2785 2803 )
2786 2804 user_user_group_to_perm_id = Column("user_user_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2787 2805 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2788 2806 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2789 2807 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2790 2808
2791 2809 user = relationship('User')
2792 2810 user_group = relationship('UserGroup')
2793 2811 permission = relationship('Permission')
2794 2812
2795 2813 @classmethod
2796 2814 def create(cls, user, user_group, permission):
2797 2815 n = cls()
2798 2816 n.user = user
2799 2817 n.user_group = user_group
2800 2818 n.permission = permission
2801 2819 Session().add(n)
2802 2820 return n
2803 2821
2804 2822 def __unicode__(self):
2805 2823 return u'<%s => %s >' % (self.user, self.user_group)
2806 2824
2807 2825
2808 2826 class UserToPerm(Base, BaseModel):
2809 2827 __tablename__ = 'user_to_perm'
2810 2828 __table_args__ = (
2811 2829 UniqueConstraint('user_id', 'permission_id'),
2812 2830 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2813 2831 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2814 2832 )
2815 2833 user_to_perm_id = Column("user_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2816 2834 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2817 2835 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2818 2836
2819 2837 user = relationship('User')
2820 2838 permission = relationship('Permission', lazy='joined')
2821 2839
2822 2840 def __unicode__(self):
2823 2841 return u'<%s => %s >' % (self.user, self.permission)
2824 2842
2825 2843
2826 2844 class UserGroupRepoToPerm(Base, BaseModel):
2827 2845 __tablename__ = 'users_group_repo_to_perm'
2828 2846 __table_args__ = (
2829 2847 UniqueConstraint('repository_id', 'users_group_id', 'permission_id'),
2830 2848 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2831 2849 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2832 2850 )
2833 2851 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2834 2852 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2835 2853 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2836 2854 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
2837 2855
2838 2856 users_group = relationship('UserGroup')
2839 2857 permission = relationship('Permission')
2840 2858 repository = relationship('Repository')
2841 2859
2842 2860 @classmethod
2843 2861 def create(cls, users_group, repository, permission):
2844 2862 n = cls()
2845 2863 n.users_group = users_group
2846 2864 n.repository = repository
2847 2865 n.permission = permission
2848 2866 Session().add(n)
2849 2867 return n
2850 2868
2851 2869 def __unicode__(self):
2852 2870 return u'<UserGroupRepoToPerm:%s => %s >' % (self.users_group, self.repository)
2853 2871
2854 2872
2855 2873 class UserGroupUserGroupToPerm(Base, BaseModel):
2856 2874 __tablename__ = 'user_group_user_group_to_perm'
2857 2875 __table_args__ = (
2858 2876 UniqueConstraint('target_user_group_id', 'user_group_id', 'permission_id'),
2859 2877 CheckConstraint('target_user_group_id != user_group_id'),
2860 2878 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2861 2879 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2862 2880 )
2863 2881 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)
2864 2882 target_user_group_id = Column("target_user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2865 2883 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2866 2884 user_group_id = Column("user_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2867 2885
2868 2886 target_user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.target_user_group_id==UserGroup.users_group_id')
2869 2887 user_group = relationship('UserGroup', primaryjoin='UserGroupUserGroupToPerm.user_group_id==UserGroup.users_group_id')
2870 2888 permission = relationship('Permission')
2871 2889
2872 2890 @classmethod
2873 2891 def create(cls, target_user_group, user_group, permission):
2874 2892 n = cls()
2875 2893 n.target_user_group = target_user_group
2876 2894 n.user_group = user_group
2877 2895 n.permission = permission
2878 2896 Session().add(n)
2879 2897 return n
2880 2898
2881 2899 def __unicode__(self):
2882 2900 return u'<UserGroupUserGroup:%s => %s >' % (self.target_user_group, self.user_group)
2883 2901
2884 2902
2885 2903 class UserGroupToPerm(Base, BaseModel):
2886 2904 __tablename__ = 'users_group_to_perm'
2887 2905 __table_args__ = (
2888 2906 UniqueConstraint('users_group_id', 'permission_id',),
2889 2907 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2890 2908 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2891 2909 )
2892 2910 users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2893 2911 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2894 2912 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2895 2913
2896 2914 users_group = relationship('UserGroup')
2897 2915 permission = relationship('Permission')
2898 2916
2899 2917
2900 2918 class UserRepoGroupToPerm(Base, BaseModel):
2901 2919 __tablename__ = 'user_repo_group_to_perm'
2902 2920 __table_args__ = (
2903 2921 UniqueConstraint('user_id', 'group_id', 'permission_id'),
2904 2922 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2905 2923 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2906 2924 )
2907 2925
2908 2926 group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2909 2927 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2910 2928 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2911 2929 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2912 2930
2913 2931 user = relationship('User')
2914 2932 group = relationship('RepoGroup')
2915 2933 permission = relationship('Permission')
2916 2934
2917 2935 @classmethod
2918 2936 def create(cls, user, repository_group, permission):
2919 2937 n = cls()
2920 2938 n.user = user
2921 2939 n.group = repository_group
2922 2940 n.permission = permission
2923 2941 Session().add(n)
2924 2942 return n
2925 2943
2926 2944
2927 2945 class UserGroupRepoGroupToPerm(Base, BaseModel):
2928 2946 __tablename__ = 'users_group_repo_group_to_perm'
2929 2947 __table_args__ = (
2930 2948 UniqueConstraint('users_group_id', 'group_id'),
2931 2949 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2932 2950 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2933 2951 )
2934 2952
2935 2953 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)
2936 2954 users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
2937 2955 group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
2938 2956 permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
2939 2957
2940 2958 users_group = relationship('UserGroup')
2941 2959 permission = relationship('Permission')
2942 2960 group = relationship('RepoGroup')
2943 2961
2944 2962 @classmethod
2945 2963 def create(cls, user_group, repository_group, permission):
2946 2964 n = cls()
2947 2965 n.users_group = user_group
2948 2966 n.group = repository_group
2949 2967 n.permission = permission
2950 2968 Session().add(n)
2951 2969 return n
2952 2970
2953 2971 def __unicode__(self):
2954 2972 return u'<UserGroupRepoGroupToPerm:%s => %s >' % (self.users_group, self.group)
2955 2973
2956 2974
2957 2975 class Statistics(Base, BaseModel):
2958 2976 __tablename__ = 'statistics'
2959 2977 __table_args__ = (
2960 2978 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2961 2979 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2962 2980 )
2963 2981 stat_id = Column("stat_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2964 2982 repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True, default=None)
2965 2983 stat_on_revision = Column("stat_on_revision", Integer(), nullable=False)
2966 2984 commit_activity = Column("commit_activity", LargeBinary(1000000), nullable=False)#JSON data
2967 2985 commit_activity_combined = Column("commit_activity_combined", LargeBinary(), nullable=False)#JSON data
2968 2986 languages = Column("languages", LargeBinary(1000000), nullable=False)#JSON data
2969 2987
2970 2988 repository = relationship('Repository', single_parent=True)
2971 2989
2972 2990
2973 2991 class UserFollowing(Base, BaseModel):
2974 2992 __tablename__ = 'user_followings'
2975 2993 __table_args__ = (
2976 2994 UniqueConstraint('user_id', 'follows_repository_id'),
2977 2995 UniqueConstraint('user_id', 'follows_user_id'),
2978 2996 {'extend_existing': True, 'mysql_engine': 'InnoDB',
2979 2997 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
2980 2998 )
2981 2999
2982 3000 user_following_id = Column("user_following_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
2983 3001 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
2984 3002 follows_repo_id = Column("follows_repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=True, unique=None, default=None)
2985 3003 follows_user_id = Column("follows_user_id", Integer(), ForeignKey('users.user_id'), nullable=True, unique=None, default=None)
2986 3004 follows_from = Column('follows_from', DateTime(timezone=False), nullable=True, unique=None, default=datetime.datetime.now)
2987 3005
2988 3006 user = relationship('User', primaryjoin='User.user_id==UserFollowing.user_id')
2989 3007
2990 3008 follows_user = relationship('User', primaryjoin='User.user_id==UserFollowing.follows_user_id')
2991 3009 follows_repository = relationship('Repository', order_by='Repository.repo_name')
2992 3010
2993 3011 @classmethod
2994 3012 def get_repo_followers(cls, repo_id):
2995 3013 return cls.query().filter(cls.follows_repo_id == repo_id)
2996 3014
2997 3015
2998 3016 class CacheKey(Base, BaseModel):
2999 3017 __tablename__ = 'cache_invalidation'
3000 3018 __table_args__ = (
3001 3019 UniqueConstraint('cache_key'),
3002 3020 Index('key_idx', 'cache_key'),
3003 3021 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3004 3022 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3005 3023 )
3006 3024 CACHE_TYPE_ATOM = 'ATOM'
3007 3025 CACHE_TYPE_RSS = 'RSS'
3008 3026 CACHE_TYPE_README = 'README'
3009 3027
3010 3028 cache_id = Column("cache_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
3011 3029 cache_key = Column("cache_key", String(255), nullable=True, unique=None, default=None)
3012 3030 cache_args = Column("cache_args", String(255), nullable=True, unique=None, default=None)
3013 3031 cache_active = Column("cache_active", Boolean(), nullable=True, unique=None, default=False)
3014 3032
3015 3033 def __init__(self, cache_key, cache_args=''):
3016 3034 self.cache_key = cache_key
3017 3035 self.cache_args = cache_args
3018 3036 self.cache_active = False
3019 3037
3020 3038 def __unicode__(self):
3021 3039 return u"<%s('%s:%s[%s]')>" % (
3022 3040 self.__class__.__name__,
3023 3041 self.cache_id, self.cache_key, self.cache_active)
3024 3042
3025 3043 def _cache_key_partition(self):
3026 3044 prefix, repo_name, suffix = self.cache_key.partition(self.cache_args)
3027 3045 return prefix, repo_name, suffix
3028 3046
3029 3047 def get_prefix(self):
3030 3048 """
3031 3049 Try to extract prefix from existing cache key. The key could consist
3032 3050 of prefix, repo_name, suffix
3033 3051 """
3034 3052 # this returns prefix, repo_name, suffix
3035 3053 return self._cache_key_partition()[0]
3036 3054
3037 3055 def get_suffix(self):
3038 3056 """
3039 3057 get suffix that might have been used in _get_cache_key to
3040 3058 generate self.cache_key. Only used for informational purposes
3041 3059 in repo_edit.mako.
3042 3060 """
3043 3061 # prefix, repo_name, suffix
3044 3062 return self._cache_key_partition()[2]
3045 3063
3046 3064 @classmethod
3047 3065 def delete_all_cache(cls):
3048 3066 """
3049 3067 Delete all cache keys from database.
3050 3068 Should only be run when all instances are down and all entries
3051 3069 thus stale.
3052 3070 """
3053 3071 cls.query().delete()
3054 3072 Session().commit()
3055 3073
3056 3074 @classmethod
3057 3075 def get_cache_key(cls, repo_name, cache_type):
3058 3076 """
3059 3077
3060 3078 Generate a cache key for this process of RhodeCode instance.
3061 3079 Prefix most likely will be process id or maybe explicitly set
3062 3080 instance_id from .ini file.
3063 3081 """
3064 3082 import rhodecode
3065 3083 prefix = safe_unicode(rhodecode.CONFIG.get('instance_id') or '')
3066 3084
3067 3085 repo_as_unicode = safe_unicode(repo_name)
3068 3086 key = u'{}_{}'.format(repo_as_unicode, cache_type) \
3069 3087 if cache_type else repo_as_unicode
3070 3088
3071 3089 return u'{}{}'.format(prefix, key)
3072 3090
3073 3091 @classmethod
3074 3092 def set_invalidate(cls, repo_name, delete=False):
3075 3093 """
3076 3094 Mark all caches of a repo as invalid in the database.
3077 3095 """
3078 3096
3079 3097 try:
3080 3098 qry = Session().query(cls).filter(cls.cache_args == repo_name)
3081 3099 if delete:
3082 3100 log.debug('cache objects deleted for repo %s',
3083 3101 safe_str(repo_name))
3084 3102 qry.delete()
3085 3103 else:
3086 3104 log.debug('cache objects marked as invalid for repo %s',
3087 3105 safe_str(repo_name))
3088 3106 qry.update({"cache_active": False})
3089 3107
3090 3108 Session().commit()
3091 3109 except Exception:
3092 3110 log.exception(
3093 3111 'Cache key invalidation failed for repository %s',
3094 3112 safe_str(repo_name))
3095 3113 Session().rollback()
3096 3114
3097 3115 @classmethod
3098 3116 def get_active_cache(cls, cache_key):
3099 3117 inv_obj = cls.query().filter(cls.cache_key == cache_key).scalar()
3100 3118 if inv_obj:
3101 3119 return inv_obj
3102 3120 return None
3103 3121
3104 3122 @classmethod
3105 3123 def repo_context_cache(cls, compute_func, repo_name, cache_type,
3106 3124 thread_scoped=False):
3107 3125 """
3108 3126 @cache_region('long_term')
3109 3127 def _heavy_calculation(cache_key):
3110 3128 return 'result'
3111 3129
3112 3130 cache_context = CacheKey.repo_context_cache(
3113 3131 _heavy_calculation, repo_name, cache_type)
3114 3132
3115 3133 with cache_context as context:
3116 3134 context.invalidate()
3117 3135 computed = context.compute()
3118 3136
3119 3137 assert computed == 'result'
3120 3138 """
3121 3139 from rhodecode.lib import caches
3122 3140 return caches.InvalidationContext(
3123 3141 compute_func, repo_name, cache_type, thread_scoped=thread_scoped)
3124 3142
3125 3143
3126 3144 class ChangesetComment(Base, BaseModel):
3127 3145 __tablename__ = 'changeset_comments'
3128 3146 __table_args__ = (
3129 3147 Index('cc_revision_idx', 'revision'),
3130 3148 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3131 3149 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3132 3150 )
3133 3151
3134 3152 COMMENT_OUTDATED = u'comment_outdated'
3135 3153 COMMENT_TYPE_NOTE = u'note'
3136 3154 COMMENT_TYPE_TODO = u'todo'
3137 3155 COMMENT_TYPES = [COMMENT_TYPE_NOTE, COMMENT_TYPE_TODO]
3138 3156
3139 3157 comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
3140 3158 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3141 3159 revision = Column('revision', String(40), nullable=True)
3142 3160 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3143 3161 pull_request_version_id = Column("pull_request_version_id", Integer(), ForeignKey('pull_request_versions.pull_request_version_id'), nullable=True)
3144 3162 line_no = Column('line_no', Unicode(10), nullable=True)
3145 3163 hl_lines = Column('hl_lines', Unicode(512), nullable=True)
3146 3164 f_path = Column('f_path', Unicode(1000), nullable=True)
3147 3165 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
3148 3166 text = Column('text', UnicodeText().with_variant(UnicodeText(25000), 'mysql'), nullable=False)
3149 3167 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3150 3168 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3151 3169 renderer = Column('renderer', Unicode(64), nullable=True)
3152 3170 display_state = Column('display_state', Unicode(128), nullable=True)
3153 3171
3154 3172 comment_type = Column('comment_type', Unicode(128), nullable=True, default=COMMENT_TYPE_NOTE)
3155 3173 resolved_comment_id = Column('resolved_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'), nullable=True)
3156 3174 resolved_comment = relationship('ChangesetComment', remote_side=comment_id, backref='resolved_by')
3157 3175 author = relationship('User', lazy='joined')
3158 3176 repo = relationship('Repository')
3159 3177 status_change = relationship('ChangesetStatus', cascade="all, delete, delete-orphan", lazy='joined')
3160 3178 pull_request = relationship('PullRequest', lazy='joined')
3161 3179 pull_request_version = relationship('PullRequestVersion')
3162 3180
3163 3181 @classmethod
3164 3182 def get_users(cls, revision=None, pull_request_id=None):
3165 3183 """
3166 3184 Returns user associated with this ChangesetComment. ie those
3167 3185 who actually commented
3168 3186
3169 3187 :param cls:
3170 3188 :param revision:
3171 3189 """
3172 3190 q = Session().query(User)\
3173 3191 .join(ChangesetComment.author)
3174 3192 if revision:
3175 3193 q = q.filter(cls.revision == revision)
3176 3194 elif pull_request_id:
3177 3195 q = q.filter(cls.pull_request_id == pull_request_id)
3178 3196 return q.all()
3179 3197
3180 3198 @classmethod
3181 3199 def get_index_from_version(cls, pr_version, versions):
3182 3200 num_versions = [x.pull_request_version_id for x in versions]
3183 3201 try:
3184 3202 return num_versions.index(pr_version) +1
3185 3203 except (IndexError, ValueError):
3186 3204 return
3187 3205
3188 3206 @property
3189 3207 def outdated(self):
3190 3208 return self.display_state == self.COMMENT_OUTDATED
3191 3209
3192 3210 def outdated_at_version(self, version):
3193 3211 """
3194 3212 Checks if comment is outdated for given pull request version
3195 3213 """
3196 3214 return self.outdated and self.pull_request_version_id != version
3197 3215
3198 3216 def older_than_version(self, version):
3199 3217 """
3200 3218 Checks if comment is made from previous version than given
3201 3219 """
3202 3220 if version is None:
3203 3221 return self.pull_request_version_id is not None
3204 3222
3205 3223 return self.pull_request_version_id < version
3206 3224
3207 3225 @property
3208 3226 def resolved(self):
3209 3227 return self.resolved_by[0] if self.resolved_by else None
3210 3228
3211 3229 @property
3212 3230 def is_todo(self):
3213 3231 return self.comment_type == self.COMMENT_TYPE_TODO
3214 3232
3215 3233 @property
3216 3234 def is_inline(self):
3217 3235 return self.line_no and self.f_path
3218 3236
3219 3237 def get_index_version(self, versions):
3220 3238 return self.get_index_from_version(
3221 3239 self.pull_request_version_id, versions)
3222 3240
3223 3241 def __repr__(self):
3224 3242 if self.comment_id:
3225 3243 return '<DB:Comment #%s>' % self.comment_id
3226 3244 else:
3227 3245 return '<DB:Comment at %#x>' % id(self)
3228 3246
3229 3247 def get_api_data(self):
3230 3248 comment = self
3231 3249 data = {
3232 3250 'comment_id': comment.comment_id,
3233 3251 'comment_type': comment.comment_type,
3234 3252 'comment_text': comment.text,
3235 3253 'comment_status': comment.status_change,
3236 3254 'comment_f_path': comment.f_path,
3237 3255 'comment_lineno': comment.line_no,
3238 3256 'comment_author': comment.author,
3239 3257 'comment_created_on': comment.created_on
3240 3258 }
3241 3259 return data
3242 3260
3243 3261 def __json__(self):
3244 3262 data = dict()
3245 3263 data.update(self.get_api_data())
3246 3264 return data
3247 3265
3248 3266
3249 3267 class ChangesetStatus(Base, BaseModel):
3250 3268 __tablename__ = 'changeset_statuses'
3251 3269 __table_args__ = (
3252 3270 Index('cs_revision_idx', 'revision'),
3253 3271 Index('cs_version_idx', 'version'),
3254 3272 UniqueConstraint('repo_id', 'revision', 'version'),
3255 3273 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3256 3274 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3257 3275 )
3258 3276 STATUS_NOT_REVIEWED = DEFAULT = 'not_reviewed'
3259 3277 STATUS_APPROVED = 'approved'
3260 3278 STATUS_REJECTED = 'rejected'
3261 3279 STATUS_UNDER_REVIEW = 'under_review'
3262 3280
3263 3281 STATUSES = [
3264 3282 (STATUS_NOT_REVIEWED, _("Not Reviewed")), # (no icon) and default
3265 3283 (STATUS_APPROVED, _("Approved")),
3266 3284 (STATUS_REJECTED, _("Rejected")),
3267 3285 (STATUS_UNDER_REVIEW, _("Under Review")),
3268 3286 ]
3269 3287
3270 3288 changeset_status_id = Column('changeset_status_id', Integer(), nullable=False, primary_key=True)
3271 3289 repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
3272 3290 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None)
3273 3291 revision = Column('revision', String(40), nullable=False)
3274 3292 status = Column('status', String(128), nullable=False, default=DEFAULT)
3275 3293 changeset_comment_id = Column('changeset_comment_id', Integer(), ForeignKey('changeset_comments.comment_id'))
3276 3294 modified_at = Column('modified_at', DateTime(), nullable=False, default=datetime.datetime.now)
3277 3295 version = Column('version', Integer(), nullable=False, default=0)
3278 3296 pull_request_id = Column("pull_request_id", Integer(), ForeignKey('pull_requests.pull_request_id'), nullable=True)
3279 3297
3280 3298 author = relationship('User', lazy='joined')
3281 3299 repo = relationship('Repository')
3282 3300 comment = relationship('ChangesetComment', lazy='joined')
3283 3301 pull_request = relationship('PullRequest', lazy='joined')
3284 3302
3285 3303 def __unicode__(self):
3286 3304 return u"<%s('%s[v%s]:%s')>" % (
3287 3305 self.__class__.__name__,
3288 3306 self.status, self.version, self.author
3289 3307 )
3290 3308
3291 3309 @classmethod
3292 3310 def get_status_lbl(cls, value):
3293 3311 return dict(cls.STATUSES).get(value)
3294 3312
3295 3313 @property
3296 3314 def status_lbl(self):
3297 3315 return ChangesetStatus.get_status_lbl(self.status)
3298 3316
3299 3317 def get_api_data(self):
3300 3318 status = self
3301 3319 data = {
3302 3320 'status_id': status.changeset_status_id,
3303 3321 'status': status.status,
3304 3322 }
3305 3323 return data
3306 3324
3307 3325 def __json__(self):
3308 3326 data = dict()
3309 3327 data.update(self.get_api_data())
3310 3328 return data
3311 3329
3312 3330
3313 3331 class _PullRequestBase(BaseModel):
3314 3332 """
3315 3333 Common attributes of pull request and version entries.
3316 3334 """
3317 3335
3318 3336 # .status values
3319 3337 STATUS_NEW = u'new'
3320 3338 STATUS_OPEN = u'open'
3321 3339 STATUS_CLOSED = u'closed'
3322 3340
3323 3341 title = Column('title', Unicode(255), nullable=True)
3324 3342 description = Column(
3325 3343 'description', UnicodeText().with_variant(UnicodeText(10240), 'mysql'),
3326 3344 nullable=True)
3327 3345 # new/open/closed status of pull request (not approve/reject/etc)
3328 3346 status = Column('status', Unicode(255), nullable=False, default=STATUS_NEW)
3329 3347 created_on = Column(
3330 3348 'created_on', DateTime(timezone=False), nullable=False,
3331 3349 default=datetime.datetime.now)
3332 3350 updated_on = Column(
3333 3351 'updated_on', DateTime(timezone=False), nullable=False,
3334 3352 default=datetime.datetime.now)
3335 3353
3336 3354 @declared_attr
3337 3355 def user_id(cls):
3338 3356 return Column(
3339 3357 "user_id", Integer(), ForeignKey('users.user_id'), nullable=False,
3340 3358 unique=None)
3341 3359
3342 3360 # 500 revisions max
3343 3361 _revisions = Column(
3344 3362 'revisions', UnicodeText().with_variant(UnicodeText(20500), 'mysql'))
3345 3363
3346 3364 @declared_attr
3347 3365 def source_repo_id(cls):
3348 3366 # TODO: dan: rename column to source_repo_id
3349 3367 return Column(
3350 3368 'org_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3351 3369 nullable=False)
3352 3370
3353 3371 source_ref = Column('org_ref', Unicode(255), nullable=False)
3354 3372
3355 3373 @declared_attr
3356 3374 def target_repo_id(cls):
3357 3375 # TODO: dan: rename column to target_repo_id
3358 3376 return Column(
3359 3377 'other_repo_id', Integer(), ForeignKey('repositories.repo_id'),
3360 3378 nullable=False)
3361 3379
3362 3380 target_ref = Column('other_ref', Unicode(255), nullable=False)
3363 3381 _shadow_merge_ref = Column('shadow_merge_ref', Unicode(255), nullable=True)
3364 3382
3365 3383 # TODO: dan: rename column to last_merge_source_rev
3366 3384 _last_merge_source_rev = Column(
3367 3385 'last_merge_org_rev', String(40), nullable=True)
3368 3386 # TODO: dan: rename column to last_merge_target_rev
3369 3387 _last_merge_target_rev = Column(
3370 3388 'last_merge_other_rev', String(40), nullable=True)
3371 3389 _last_merge_status = Column('merge_status', Integer(), nullable=True)
3372 3390 merge_rev = Column('merge_rev', String(40), nullable=True)
3373 3391
3374 3392 reviewer_data = Column(
3375 3393 'reviewer_data_json', MutationObj.as_mutable(
3376 3394 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3377 3395
3378 3396 @property
3379 3397 def reviewer_data_json(self):
3380 3398 return json.dumps(self.reviewer_data)
3381 3399
3382 3400 @hybrid_property
3383 3401 def description_safe(self):
3384 3402 from rhodecode.lib import helpers as h
3385 3403 return h.escape(self.description)
3386 3404
3387 3405 @hybrid_property
3388 3406 def revisions(self):
3389 3407 return self._revisions.split(':') if self._revisions else []
3390 3408
3391 3409 @revisions.setter
3392 3410 def revisions(self, val):
3393 3411 self._revisions = ':'.join(val)
3394 3412
3395 3413 @hybrid_property
3396 3414 def last_merge_status(self):
3397 3415 return safe_int(self._last_merge_status)
3398 3416
3399 3417 @last_merge_status.setter
3400 3418 def last_merge_status(self, val):
3401 3419 self._last_merge_status = val
3402 3420
3403 3421 @declared_attr
3404 3422 def author(cls):
3405 3423 return relationship('User', lazy='joined')
3406 3424
3407 3425 @declared_attr
3408 3426 def source_repo(cls):
3409 3427 return relationship(
3410 3428 'Repository',
3411 3429 primaryjoin='%s.source_repo_id==Repository.repo_id' % cls.__name__)
3412 3430
3413 3431 @property
3414 3432 def source_ref_parts(self):
3415 3433 return self.unicode_to_reference(self.source_ref)
3416 3434
3417 3435 @declared_attr
3418 3436 def target_repo(cls):
3419 3437 return relationship(
3420 3438 'Repository',
3421 3439 primaryjoin='%s.target_repo_id==Repository.repo_id' % cls.__name__)
3422 3440
3423 3441 @property
3424 3442 def target_ref_parts(self):
3425 3443 return self.unicode_to_reference(self.target_ref)
3426 3444
3427 3445 @property
3428 3446 def shadow_merge_ref(self):
3429 3447 return self.unicode_to_reference(self._shadow_merge_ref)
3430 3448
3431 3449 @shadow_merge_ref.setter
3432 3450 def shadow_merge_ref(self, ref):
3433 3451 self._shadow_merge_ref = self.reference_to_unicode(ref)
3434 3452
3435 3453 def unicode_to_reference(self, raw):
3436 3454 """
3437 3455 Convert a unicode (or string) to a reference object.
3438 3456 If unicode evaluates to False it returns None.
3439 3457 """
3440 3458 if raw:
3441 3459 refs = raw.split(':')
3442 3460 return Reference(*refs)
3443 3461 else:
3444 3462 return None
3445 3463
3446 3464 def reference_to_unicode(self, ref):
3447 3465 """
3448 3466 Convert a reference object to unicode.
3449 3467 If reference is None it returns None.
3450 3468 """
3451 3469 if ref:
3452 3470 return u':'.join(ref)
3453 3471 else:
3454 3472 return None
3455 3473
3456 3474 def get_api_data(self, with_merge_state=True):
3457 3475 from rhodecode.model.pull_request import PullRequestModel
3458 3476
3459 3477 pull_request = self
3460 3478 if with_merge_state:
3461 3479 merge_status = PullRequestModel().merge_status(pull_request)
3462 3480 merge_state = {
3463 3481 'status': merge_status[0],
3464 3482 'message': safe_unicode(merge_status[1]),
3465 3483 }
3466 3484 else:
3467 3485 merge_state = {'status': 'not_available',
3468 3486 'message': 'not_available'}
3469 3487
3470 3488 merge_data = {
3471 3489 'clone_url': PullRequestModel().get_shadow_clone_url(pull_request),
3472 3490 'reference': (
3473 3491 pull_request.shadow_merge_ref._asdict()
3474 3492 if pull_request.shadow_merge_ref else None),
3475 3493 }
3476 3494
3477 3495 data = {
3478 3496 'pull_request_id': pull_request.pull_request_id,
3479 3497 'url': PullRequestModel().get_url(pull_request),
3480 3498 'title': pull_request.title,
3481 3499 'description': pull_request.description,
3482 3500 'status': pull_request.status,
3483 3501 'created_on': pull_request.created_on,
3484 3502 'updated_on': pull_request.updated_on,
3485 3503 'commit_ids': pull_request.revisions,
3486 3504 'review_status': pull_request.calculated_review_status(),
3487 3505 'mergeable': merge_state,
3488 3506 'source': {
3489 3507 'clone_url': pull_request.source_repo.clone_url(),
3490 3508 'repository': pull_request.source_repo.repo_name,
3491 3509 'reference': {
3492 3510 'name': pull_request.source_ref_parts.name,
3493 3511 'type': pull_request.source_ref_parts.type,
3494 3512 'commit_id': pull_request.source_ref_parts.commit_id,
3495 3513 },
3496 3514 },
3497 3515 'target': {
3498 3516 'clone_url': pull_request.target_repo.clone_url(),
3499 3517 'repository': pull_request.target_repo.repo_name,
3500 3518 'reference': {
3501 3519 'name': pull_request.target_ref_parts.name,
3502 3520 'type': pull_request.target_ref_parts.type,
3503 3521 'commit_id': pull_request.target_ref_parts.commit_id,
3504 3522 },
3505 3523 },
3506 3524 'merge': merge_data,
3507 3525 'author': pull_request.author.get_api_data(include_secrets=False,
3508 3526 details='basic'),
3509 3527 'reviewers': [
3510 3528 {
3511 3529 'user': reviewer.get_api_data(include_secrets=False,
3512 3530 details='basic'),
3513 3531 'reasons': reasons,
3514 3532 'review_status': st[0][1].status if st else 'not_reviewed',
3515 3533 }
3516 3534 for reviewer, reasons, mandatory, st in
3517 3535 pull_request.reviewers_statuses()
3518 3536 ]
3519 3537 }
3520 3538
3521 3539 return data
3522 3540
3523 3541
3524 3542 class PullRequest(Base, _PullRequestBase):
3525 3543 __tablename__ = 'pull_requests'
3526 3544 __table_args__ = (
3527 3545 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3528 3546 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3529 3547 )
3530 3548
3531 3549 pull_request_id = Column(
3532 3550 'pull_request_id', Integer(), nullable=False, primary_key=True)
3533 3551
3534 3552 def __repr__(self):
3535 3553 if self.pull_request_id:
3536 3554 return '<DB:PullRequest #%s>' % self.pull_request_id
3537 3555 else:
3538 3556 return '<DB:PullRequest at %#x>' % id(self)
3539 3557
3540 3558 reviewers = relationship('PullRequestReviewers',
3541 3559 cascade="all, delete, delete-orphan")
3542 3560 statuses = relationship('ChangesetStatus',
3543 3561 cascade="all, delete, delete-orphan")
3544 3562 comments = relationship('ChangesetComment',
3545 3563 cascade="all, delete, delete-orphan")
3546 3564 versions = relationship('PullRequestVersion',
3547 3565 cascade="all, delete, delete-orphan",
3548 3566 lazy='dynamic')
3549 3567
3550 3568 @classmethod
3551 3569 def get_pr_display_object(cls, pull_request_obj, org_pull_request_obj,
3552 3570 internal_methods=None):
3553 3571
3554 3572 class PullRequestDisplay(object):
3555 3573 """
3556 3574 Special object wrapper for showing PullRequest data via Versions
3557 3575 It mimics PR object as close as possible. This is read only object
3558 3576 just for display
3559 3577 """
3560 3578
3561 3579 def __init__(self, attrs, internal=None):
3562 3580 self.attrs = attrs
3563 3581 # internal have priority over the given ones via attrs
3564 3582 self.internal = internal or ['versions']
3565 3583
3566 3584 def __getattr__(self, item):
3567 3585 if item in self.internal:
3568 3586 return getattr(self, item)
3569 3587 try:
3570 3588 return self.attrs[item]
3571 3589 except KeyError:
3572 3590 raise AttributeError(
3573 3591 '%s object has no attribute %s' % (self, item))
3574 3592
3575 3593 def __repr__(self):
3576 3594 return '<DB:PullRequestDisplay #%s>' % self.attrs.get('pull_request_id')
3577 3595
3578 3596 def versions(self):
3579 3597 return pull_request_obj.versions.order_by(
3580 3598 PullRequestVersion.pull_request_version_id).all()
3581 3599
3582 3600 def is_closed(self):
3583 3601 return pull_request_obj.is_closed()
3584 3602
3585 3603 @property
3586 3604 def pull_request_version_id(self):
3587 3605 return getattr(pull_request_obj, 'pull_request_version_id', None)
3588 3606
3589 3607 attrs = StrictAttributeDict(pull_request_obj.get_api_data())
3590 3608
3591 3609 attrs.author = StrictAttributeDict(
3592 3610 pull_request_obj.author.get_api_data())
3593 3611 if pull_request_obj.target_repo:
3594 3612 attrs.target_repo = StrictAttributeDict(
3595 3613 pull_request_obj.target_repo.get_api_data())
3596 3614 attrs.target_repo.clone_url = pull_request_obj.target_repo.clone_url
3597 3615
3598 3616 if pull_request_obj.source_repo:
3599 3617 attrs.source_repo = StrictAttributeDict(
3600 3618 pull_request_obj.source_repo.get_api_data())
3601 3619 attrs.source_repo.clone_url = pull_request_obj.source_repo.clone_url
3602 3620
3603 3621 attrs.source_ref_parts = pull_request_obj.source_ref_parts
3604 3622 attrs.target_ref_parts = pull_request_obj.target_ref_parts
3605 3623 attrs.revisions = pull_request_obj.revisions
3606 3624
3607 3625 attrs.shadow_merge_ref = org_pull_request_obj.shadow_merge_ref
3608 3626 attrs.reviewer_data = org_pull_request_obj.reviewer_data
3609 3627 attrs.reviewer_data_json = org_pull_request_obj.reviewer_data_json
3610 3628
3611 3629 return PullRequestDisplay(attrs, internal=internal_methods)
3612 3630
3613 3631 def is_closed(self):
3614 3632 return self.status == self.STATUS_CLOSED
3615 3633
3616 3634 def __json__(self):
3617 3635 return {
3618 3636 'revisions': self.revisions,
3619 3637 }
3620 3638
3621 3639 def calculated_review_status(self):
3622 3640 from rhodecode.model.changeset_status import ChangesetStatusModel
3623 3641 return ChangesetStatusModel().calculated_review_status(self)
3624 3642
3625 3643 def reviewers_statuses(self):
3626 3644 from rhodecode.model.changeset_status import ChangesetStatusModel
3627 3645 return ChangesetStatusModel().reviewers_statuses(self)
3628 3646
3629 3647 @property
3630 3648 def workspace_id(self):
3631 3649 from rhodecode.model.pull_request import PullRequestModel
3632 3650 return PullRequestModel()._workspace_id(self)
3633 3651
3634 3652 def get_shadow_repo(self):
3635 3653 workspace_id = self.workspace_id
3636 3654 vcs_obj = self.target_repo.scm_instance()
3637 3655 shadow_repository_path = vcs_obj._get_shadow_repository_path(
3638 3656 workspace_id)
3639 3657 return vcs_obj._get_shadow_instance(shadow_repository_path)
3640 3658
3641 3659
3642 3660 class PullRequestVersion(Base, _PullRequestBase):
3643 3661 __tablename__ = 'pull_request_versions'
3644 3662 __table_args__ = (
3645 3663 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3646 3664 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3647 3665 )
3648 3666
3649 3667 pull_request_version_id = Column(
3650 3668 'pull_request_version_id', Integer(), nullable=False, primary_key=True)
3651 3669 pull_request_id = Column(
3652 3670 'pull_request_id', Integer(),
3653 3671 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3654 3672 pull_request = relationship('PullRequest')
3655 3673
3656 3674 def __repr__(self):
3657 3675 if self.pull_request_version_id:
3658 3676 return '<DB:PullRequestVersion #%s>' % self.pull_request_version_id
3659 3677 else:
3660 3678 return '<DB:PullRequestVersion at %#x>' % id(self)
3661 3679
3662 3680 @property
3663 3681 def reviewers(self):
3664 3682 return self.pull_request.reviewers
3665 3683
3666 3684 @property
3667 3685 def versions(self):
3668 3686 return self.pull_request.versions
3669 3687
3670 3688 def is_closed(self):
3671 3689 # calculate from original
3672 3690 return self.pull_request.status == self.STATUS_CLOSED
3673 3691
3674 3692 def calculated_review_status(self):
3675 3693 return self.pull_request.calculated_review_status()
3676 3694
3677 3695 def reviewers_statuses(self):
3678 3696 return self.pull_request.reviewers_statuses()
3679 3697
3680 3698
3681 3699 class PullRequestReviewers(Base, BaseModel):
3682 3700 __tablename__ = 'pull_request_reviewers'
3683 3701 __table_args__ = (
3684 3702 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3685 3703 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3686 3704 )
3687 3705
3688 3706 @hybrid_property
3689 3707 def reasons(self):
3690 3708 if not self._reasons:
3691 3709 return []
3692 3710 return self._reasons
3693 3711
3694 3712 @reasons.setter
3695 3713 def reasons(self, val):
3696 3714 val = val or []
3697 3715 if any(not isinstance(x, basestring) for x in val):
3698 3716 raise Exception('invalid reasons type, must be list of strings')
3699 3717 self._reasons = val
3700 3718
3701 3719 pull_requests_reviewers_id = Column(
3702 3720 'pull_requests_reviewers_id', Integer(), nullable=False,
3703 3721 primary_key=True)
3704 3722 pull_request_id = Column(
3705 3723 "pull_request_id", Integer(),
3706 3724 ForeignKey('pull_requests.pull_request_id'), nullable=False)
3707 3725 user_id = Column(
3708 3726 "user_id", Integer(), ForeignKey('users.user_id'), nullable=True)
3709 3727 _reasons = Column(
3710 3728 'reason', MutationList.as_mutable(
3711 3729 JsonType('list', dialect_map=dict(mysql=UnicodeText(16384)))))
3712 3730 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
3713 3731 user = relationship('User')
3714 3732 pull_request = relationship('PullRequest')
3715 3733
3716 3734
3717 3735 class Notification(Base, BaseModel):
3718 3736 __tablename__ = 'notifications'
3719 3737 __table_args__ = (
3720 3738 Index('notification_type_idx', 'type'),
3721 3739 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3722 3740 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
3723 3741 )
3724 3742
3725 3743 TYPE_CHANGESET_COMMENT = u'cs_comment'
3726 3744 TYPE_MESSAGE = u'message'
3727 3745 TYPE_MENTION = u'mention'
3728 3746 TYPE_REGISTRATION = u'registration'
3729 3747 TYPE_PULL_REQUEST = u'pull_request'
3730 3748 TYPE_PULL_REQUEST_COMMENT = u'pull_request_comment'
3731 3749
3732 3750 notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
3733 3751 subject = Column('subject', Unicode(512), nullable=True)
3734 3752 body = Column('body', UnicodeText().with_variant(UnicodeText(50000), 'mysql'), nullable=True)
3735 3753 created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
3736 3754 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3737 3755 type_ = Column('type', Unicode(255))
3738 3756
3739 3757 created_by_user = relationship('User')
3740 3758 notifications_to_users = relationship('UserNotification', lazy='joined',
3741 3759 cascade="all, delete, delete-orphan")
3742 3760
3743 3761 @property
3744 3762 def recipients(self):
3745 3763 return [x.user for x in UserNotification.query()\
3746 3764 .filter(UserNotification.notification == self)\
3747 3765 .order_by(UserNotification.user_id.asc()).all()]
3748 3766
3749 3767 @classmethod
3750 3768 def create(cls, created_by, subject, body, recipients, type_=None):
3751 3769 if type_ is None:
3752 3770 type_ = Notification.TYPE_MESSAGE
3753 3771
3754 3772 notification = cls()
3755 3773 notification.created_by_user = created_by
3756 3774 notification.subject = subject
3757 3775 notification.body = body
3758 3776 notification.type_ = type_
3759 3777 notification.created_on = datetime.datetime.now()
3760 3778
3761 3779 for u in recipients:
3762 3780 assoc = UserNotification()
3763 3781 assoc.notification = notification
3764 3782
3765 3783 # if created_by is inside recipients mark his notification
3766 3784 # as read
3767 3785 if u.user_id == created_by.user_id:
3768 3786 assoc.read = True
3769 3787
3770 3788 u.notifications.append(assoc)
3771 3789 Session().add(notification)
3772 3790
3773 3791 return notification
3774 3792
3775 3793
3776 3794 class UserNotification(Base, BaseModel):
3777 3795 __tablename__ = 'user_to_notification'
3778 3796 __table_args__ = (
3779 3797 UniqueConstraint('user_id', 'notification_id'),
3780 3798 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3781 3799 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3782 3800 )
3783 3801 user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), primary_key=True)
3784 3802 notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
3785 3803 read = Column('read', Boolean, default=False)
3786 3804 sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
3787 3805
3788 3806 user = relationship('User', lazy="joined")
3789 3807 notification = relationship('Notification', lazy="joined",
3790 3808 order_by=lambda: Notification.created_on.desc(),)
3791 3809
3792 3810 def mark_as_read(self):
3793 3811 self.read = True
3794 3812 Session().add(self)
3795 3813
3796 3814
3797 3815 class Gist(Base, BaseModel):
3798 3816 __tablename__ = 'gists'
3799 3817 __table_args__ = (
3800 3818 Index('g_gist_access_id_idx', 'gist_access_id'),
3801 3819 Index('g_created_on_idx', 'created_on'),
3802 3820 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3803 3821 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3804 3822 )
3805 3823 GIST_PUBLIC = u'public'
3806 3824 GIST_PRIVATE = u'private'
3807 3825 DEFAULT_FILENAME = u'gistfile1.txt'
3808 3826
3809 3827 ACL_LEVEL_PUBLIC = u'acl_public'
3810 3828 ACL_LEVEL_PRIVATE = u'acl_private'
3811 3829
3812 3830 gist_id = Column('gist_id', Integer(), primary_key=True)
3813 3831 gist_access_id = Column('gist_access_id', Unicode(250))
3814 3832 gist_description = Column('gist_description', UnicodeText().with_variant(UnicodeText(1024), 'mysql'))
3815 3833 gist_owner = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=True)
3816 3834 gist_expires = Column('gist_expires', Float(53), nullable=False)
3817 3835 gist_type = Column('gist_type', Unicode(128), nullable=False)
3818 3836 created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3819 3837 modified_at = Column('modified_at', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
3820 3838 acl_level = Column('acl_level', Unicode(128), nullable=True)
3821 3839
3822 3840 owner = relationship('User')
3823 3841
3824 3842 def __repr__(self):
3825 3843 return '<Gist:[%s]%s>' % (self.gist_type, self.gist_access_id)
3826 3844
3827 3845 @hybrid_property
3828 3846 def description_safe(self):
3829 3847 from rhodecode.lib import helpers as h
3830 3848 return h.escape(self.gist_description)
3831 3849
3832 3850 @classmethod
3833 3851 def get_or_404(cls, id_):
3834 3852 from pyramid.httpexceptions import HTTPNotFound
3835 3853
3836 3854 res = cls.query().filter(cls.gist_access_id == id_).scalar()
3837 3855 if not res:
3838 3856 raise HTTPNotFound()
3839 3857 return res
3840 3858
3841 3859 @classmethod
3842 3860 def get_by_access_id(cls, gist_access_id):
3843 3861 return cls.query().filter(cls.gist_access_id == gist_access_id).scalar()
3844 3862
3845 3863 def gist_url(self):
3846 3864 from rhodecode.model.gist import GistModel
3847 3865 return GistModel().get_url(self)
3848 3866
3849 3867 @classmethod
3850 3868 def base_path(cls):
3851 3869 """
3852 3870 Returns base path when all gists are stored
3853 3871
3854 3872 :param cls:
3855 3873 """
3856 3874 from rhodecode.model.gist import GIST_STORE_LOC
3857 3875 q = Session().query(RhodeCodeUi)\
3858 3876 .filter(RhodeCodeUi.ui_key == URL_SEP)
3859 3877 q = q.options(FromCache("sql_cache_short", "repository_repo_path"))
3860 3878 return os.path.join(q.one().ui_value, GIST_STORE_LOC)
3861 3879
3862 3880 def get_api_data(self):
3863 3881 """
3864 3882 Common function for generating gist related data for API
3865 3883 """
3866 3884 gist = self
3867 3885 data = {
3868 3886 'gist_id': gist.gist_id,
3869 3887 'type': gist.gist_type,
3870 3888 'access_id': gist.gist_access_id,
3871 3889 'description': gist.gist_description,
3872 3890 'url': gist.gist_url(),
3873 3891 'expires': gist.gist_expires,
3874 3892 'created_on': gist.created_on,
3875 3893 'modified_at': gist.modified_at,
3876 3894 'content': None,
3877 3895 'acl_level': gist.acl_level,
3878 3896 }
3879 3897 return data
3880 3898
3881 3899 def __json__(self):
3882 3900 data = dict(
3883 3901 )
3884 3902 data.update(self.get_api_data())
3885 3903 return data
3886 3904 # SCM functions
3887 3905
3888 3906 def scm_instance(self, **kwargs):
3889 3907 full_repo_path = os.path.join(self.base_path(), self.gist_access_id)
3890 3908 return get_vcs_instance(
3891 3909 repo_path=safe_str(full_repo_path), create=False)
3892 3910
3893 3911
3894 3912 class ExternalIdentity(Base, BaseModel):
3895 3913 __tablename__ = 'external_identities'
3896 3914 __table_args__ = (
3897 3915 Index('local_user_id_idx', 'local_user_id'),
3898 3916 Index('external_id_idx', 'external_id'),
3899 3917 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3900 3918 'mysql_charset': 'utf8'})
3901 3919
3902 3920 external_id = Column('external_id', Unicode(255), default=u'',
3903 3921 primary_key=True)
3904 3922 external_username = Column('external_username', Unicode(1024), default=u'')
3905 3923 local_user_id = Column('local_user_id', Integer(),
3906 3924 ForeignKey('users.user_id'), primary_key=True)
3907 3925 provider_name = Column('provider_name', Unicode(255), default=u'',
3908 3926 primary_key=True)
3909 3927 access_token = Column('access_token', String(1024), default=u'')
3910 3928 alt_token = Column('alt_token', String(1024), default=u'')
3911 3929 token_secret = Column('token_secret', String(1024), default=u'')
3912 3930
3913 3931 @classmethod
3914 3932 def by_external_id_and_provider(cls, external_id, provider_name,
3915 3933 local_user_id=None):
3916 3934 """
3917 3935 Returns ExternalIdentity instance based on search params
3918 3936
3919 3937 :param external_id:
3920 3938 :param provider_name:
3921 3939 :return: ExternalIdentity
3922 3940 """
3923 3941 query = cls.query()
3924 3942 query = query.filter(cls.external_id == external_id)
3925 3943 query = query.filter(cls.provider_name == provider_name)
3926 3944 if local_user_id:
3927 3945 query = query.filter(cls.local_user_id == local_user_id)
3928 3946 return query.first()
3929 3947
3930 3948 @classmethod
3931 3949 def user_by_external_id_and_provider(cls, external_id, provider_name):
3932 3950 """
3933 3951 Returns User instance based on search params
3934 3952
3935 3953 :param external_id:
3936 3954 :param provider_name:
3937 3955 :return: User
3938 3956 """
3939 3957 query = User.query()
3940 3958 query = query.filter(cls.external_id == external_id)
3941 3959 query = query.filter(cls.provider_name == provider_name)
3942 3960 query = query.filter(User.user_id == cls.local_user_id)
3943 3961 return query.first()
3944 3962
3945 3963 @classmethod
3946 3964 def by_local_user_id(cls, local_user_id):
3947 3965 """
3948 3966 Returns all tokens for user
3949 3967
3950 3968 :param local_user_id:
3951 3969 :return: ExternalIdentity
3952 3970 """
3953 3971 query = cls.query()
3954 3972 query = query.filter(cls.local_user_id == local_user_id)
3955 3973 return query
3956 3974
3957 3975
3958 3976 class Integration(Base, BaseModel):
3959 3977 __tablename__ = 'integrations'
3960 3978 __table_args__ = (
3961 3979 {'extend_existing': True, 'mysql_engine': 'InnoDB',
3962 3980 'mysql_charset': 'utf8', 'sqlite_autoincrement': True}
3963 3981 )
3964 3982
3965 3983 integration_id = Column('integration_id', Integer(), primary_key=True)
3966 3984 integration_type = Column('integration_type', String(255))
3967 3985 enabled = Column('enabled', Boolean(), nullable=False)
3968 3986 name = Column('name', String(255), nullable=False)
3969 3987 child_repos_only = Column('child_repos_only', Boolean(), nullable=False,
3970 3988 default=False)
3971 3989
3972 3990 settings = Column(
3973 3991 'settings_json', MutationObj.as_mutable(
3974 3992 JsonType(dialect_map=dict(mysql=UnicodeText(16384)))))
3975 3993 repo_id = Column(
3976 3994 'repo_id', Integer(), ForeignKey('repositories.repo_id'),
3977 3995 nullable=True, unique=None, default=None)
3978 3996 repo = relationship('Repository', lazy='joined')
3979 3997
3980 3998 repo_group_id = Column(
3981 3999 'repo_group_id', Integer(), ForeignKey('groups.group_id'),
3982 4000 nullable=True, unique=None, default=None)
3983 4001 repo_group = relationship('RepoGroup', lazy='joined')
3984 4002
3985 4003 @property
3986 4004 def scope(self):
3987 4005 if self.repo:
3988 4006 return repr(self.repo)
3989 4007 if self.repo_group:
3990 4008 if self.child_repos_only:
3991 4009 return repr(self.repo_group) + ' (child repos only)'
3992 4010 else:
3993 4011 return repr(self.repo_group) + ' (recursive)'
3994 4012 if self.child_repos_only:
3995 4013 return 'root_repos'
3996 4014 return 'global'
3997 4015
3998 4016 def __repr__(self):
3999 4017 return '<Integration(%r, %r)>' % (self.integration_type, self.scope)
4000 4018
4001 4019
4002 4020 class RepoReviewRuleUser(Base, BaseModel):
4003 4021 __tablename__ = 'repo_review_rules_users'
4004 4022 __table_args__ = (
4005 4023 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4006 4024 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4007 4025 )
4008 4026 repo_review_rule_user_id = Column('repo_review_rule_user_id', Integer(), primary_key=True)
4009 4027 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4010 4028 user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False)
4011 4029 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4012 4030 user = relationship('User')
4013 4031
4014 4032 def rule_data(self):
4015 4033 return {
4016 4034 'mandatory': self.mandatory
4017 4035 }
4018 4036
4019 4037
4020 4038 class RepoReviewRuleUserGroup(Base, BaseModel):
4021 4039 __tablename__ = 'repo_review_rules_users_groups'
4022 4040 __table_args__ = (
4023 4041 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4024 4042 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4025 4043 )
4026 4044 repo_review_rule_users_group_id = Column('repo_review_rule_users_group_id', Integer(), primary_key=True)
4027 4045 repo_review_rule_id = Column("repo_review_rule_id", Integer(), ForeignKey('repo_review_rules.repo_review_rule_id'))
4028 4046 users_group_id = Column("users_group_id", Integer(),ForeignKey('users_groups.users_group_id'), nullable=False)
4029 4047 mandatory = Column("mandatory", Boolean(), nullable=False, default=False)
4030 4048 users_group = relationship('UserGroup')
4031 4049
4032 4050 def rule_data(self):
4033 4051 return {
4034 4052 'mandatory': self.mandatory
4035 4053 }
4036 4054
4037 4055
4038 4056 class RepoReviewRule(Base, BaseModel):
4039 4057 __tablename__ = 'repo_review_rules'
4040 4058 __table_args__ = (
4041 4059 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4042 4060 'mysql_charset': 'utf8', 'sqlite_autoincrement': True,}
4043 4061 )
4044 4062
4045 4063 repo_review_rule_id = Column(
4046 4064 'repo_review_rule_id', Integer(), primary_key=True)
4047 4065 repo_id = Column(
4048 4066 "repo_id", Integer(), ForeignKey('repositories.repo_id'))
4049 4067 repo = relationship('Repository', backref='review_rules')
4050 4068
4051 4069 _branch_pattern = Column("branch_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4052 4070 _file_pattern = Column("file_pattern", UnicodeText().with_variant(UnicodeText(255), 'mysql'), default=u'*') # glob
4053 4071
4054 4072 use_authors_for_review = Column("use_authors_for_review", Boolean(), nullable=False, default=False)
4055 4073 forbid_author_to_review = Column("forbid_author_to_review", Boolean(), nullable=False, default=False)
4056 4074 forbid_commit_author_to_review = Column("forbid_commit_author_to_review", Boolean(), nullable=False, default=False)
4057 4075 forbid_adding_reviewers = Column("forbid_adding_reviewers", Boolean(), nullable=False, default=False)
4058 4076
4059 4077 rule_users = relationship('RepoReviewRuleUser')
4060 4078 rule_user_groups = relationship('RepoReviewRuleUserGroup')
4061 4079
4062 4080 @hybrid_property
4063 4081 def branch_pattern(self):
4064 4082 return self._branch_pattern or '*'
4065 4083
4066 4084 def _validate_glob(self, value):
4067 4085 re.compile('^' + glob2re(value) + '$')
4068 4086
4069 4087 @branch_pattern.setter
4070 4088 def branch_pattern(self, value):
4071 4089 self._validate_glob(value)
4072 4090 self._branch_pattern = value or '*'
4073 4091
4074 4092 @hybrid_property
4075 4093 def file_pattern(self):
4076 4094 return self._file_pattern or '*'
4077 4095
4078 4096 @file_pattern.setter
4079 4097 def file_pattern(self, value):
4080 4098 self._validate_glob(value)
4081 4099 self._file_pattern = value or '*'
4082 4100
4083 4101 def matches(self, branch, files_changed):
4084 4102 """
4085 4103 Check if this review rule matches a branch/files in a pull request
4086 4104
4087 4105 :param branch: branch name for the commit
4088 4106 :param files_changed: list of file paths changed in the pull request
4089 4107 """
4090 4108
4091 4109 branch = branch or ''
4092 4110 files_changed = files_changed or []
4093 4111
4094 4112 branch_matches = True
4095 4113 if branch:
4096 4114 branch_regex = re.compile('^' + glob2re(self.branch_pattern) + '$')
4097 4115 branch_matches = bool(branch_regex.search(branch))
4098 4116
4099 4117 files_matches = True
4100 4118 if self.file_pattern != '*':
4101 4119 files_matches = False
4102 4120 file_regex = re.compile(glob2re(self.file_pattern))
4103 4121 for filename in files_changed:
4104 4122 if file_regex.search(filename):
4105 4123 files_matches = True
4106 4124 break
4107 4125
4108 4126 return branch_matches and files_matches
4109 4127
4110 4128 @property
4111 4129 def review_users(self):
4112 4130 """ Returns the users which this rule applies to """
4113 4131
4114 4132 users = collections.OrderedDict()
4115 4133
4116 4134 for rule_user in self.rule_users:
4117 4135 if rule_user.user.active:
4118 4136 if rule_user.user not in users:
4119 4137 users[rule_user.user.username] = {
4120 4138 'user': rule_user.user,
4121 4139 'source': 'user',
4122 4140 'source_data': {},
4123 4141 'data': rule_user.rule_data()
4124 4142 }
4125 4143
4126 4144 for rule_user_group in self.rule_user_groups:
4127 4145 source_data = {
4128 4146 'name': rule_user_group.users_group.users_group_name,
4129 4147 'members': len(rule_user_group.users_group.members)
4130 4148 }
4131 4149 for member in rule_user_group.users_group.members:
4132 4150 if member.user.active:
4133 4151 users[member.user.username] = {
4134 4152 'user': member.user,
4135 4153 'source': 'user_group',
4136 4154 'source_data': source_data,
4137 4155 'data': rule_user_group.rule_data()
4138 4156 }
4139 4157
4140 4158 return users
4141 4159
4142 4160 def __repr__(self):
4143 4161 return '<RepoReviewerRule(id=%r, repo=%r)>' % (
4144 4162 self.repo_review_rule_id, self.repo)
4145 4163
4146 4164
4147 4165 class DbMigrateVersion(Base, BaseModel):
4148 4166 __tablename__ = 'db_migrate_version'
4149 4167 __table_args__ = (
4150 4168 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4151 4169 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4152 4170 )
4153 4171 repository_id = Column('repository_id', String(250), primary_key=True)
4154 4172 repository_path = Column('repository_path', Text)
4155 4173 version = Column('version', Integer)
4156 4174
4157 4175
4158 4176 class DbSession(Base, BaseModel):
4159 4177 __tablename__ = 'db_session'
4160 4178 __table_args__ = (
4161 4179 {'extend_existing': True, 'mysql_engine': 'InnoDB',
4162 4180 'mysql_charset': 'utf8', 'sqlite_autoincrement': True},
4163 4181 )
4164 4182
4165 4183 def __repr__(self):
4166 4184 return '<DB:DbSession({})>'.format(self.id)
4167 4185
4168 4186 id = Column('id', Integer())
4169 4187 namespace = Column('namespace', String(255), primary_key=True)
4170 4188 accessed = Column('accessed', DateTime, nullable=False)
4171 4189 created = Column('created', DateTime, nullable=False)
4172 4190 data = Column('data', PickleType, nullable=False)
General Comments 0
You need to be logged in to leave comments. Login now